static
variables being lazily initialized
in a non-thread-safe manner. Lazy initialization of static
variables should be done
with an appropriate synchronization construct, to prevent different threads from
performing conflicting initialization.
When applicable, a quickfix is suggested which introduces the lazy initialization holder class idiom. This idiom makes use of the fact that the JVM guarantees that a class will not be initialized until it is used.
Unsafe lazy initialization example:
class X {
private static List<String> list;
public List<String> getList() {
if (list == null) {
list = List.of("one", "two", "tree");
}
return list;
}
}
Lazy initialization holder class idiom example:
class X {
private static final class ListHolder {
static final List<String> list = List.of("one", "two", "tree");
}
public List<String> getList() {
return ListHolder.list;
}
}