Unsafe lazy initialization of 'static' field
Reports static
variables that are 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 quick-fix, which introduces the lazy initialization holder class idiom, is suggested. This idiom makes use of the fact that the JVM guarantees that a class will not be initialized until it is used.
Example:
class X {
private static List<String> list;
public List<String> getList() {
if (list == null) {
list = List.of("one", "two", "tree");
}
return list;
}
}
After the quick-fix is applied:
class X {
private static final class ListHolder {
static final List<String> list = List.of("one", "two", "tree");
}
public List<String> getList() {
return ListHolder.list;
}
}
Inspection Details | |
---|---|
Available in: | IntelliJ IDEA 2023.3, Qodana for JVM 2023.3 |
Plugin: | Java, 233.SNAPSHOT |
Last modified: 13 July 2023