org.sonar.l10n.java.rules.squid.S2444.html Maven / Gradle / Ivy
The newest version!
In a multi-threaded situation, un-synchronized
lazy initialization of non-volatile
fields could mean that a second thread has access to a half-initizliaed object while the first thread is still creating it. Allowing such access could cause serious bugs. Instead. the initizliation block should be synchronized
or the variable made volatile
.
Similarly, updates of such fields should also be synchronized
.
Noncompliant Code Example
protected static Object instance = null;
public static Object getInstance() {
if (instance != null) {
return instance;
}
instance = new Object(); // Noncompliant
return instance;
}
Compliant Solution
protected static volatile Object instance = null;
public static Object getInstance() {
if (instance != null) {
return instance;
}
instance = new Object();
return instance;
}
or
protected static Object instance = null;
public static synchronized Object getInstance() {
if (instance != null) {
return instance;
}
instance = new Object();
return instance;
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy