Why is this an issue?
Double-checked locking is the practice of checking a lazy-initialized object’s state both before and after a synchronized
block is
entered to determine whether to initialize the object. In early JVM versions, synchronizing entire methods was not performant, which sometimes caused
this practice to be used in its place.
Apart from float
and int
types, this practice does not work reliably in a platform-independent manner without additional
synchronization of mutable instances. Using double-checked locking for the lazy initialization of any other type of primitive or mutable object risks
a second thread using an uninitialized or partially initialized member while the first thread is still creating it. The results can be unexpected,
potentially even causing the application to crash.
How to fix it
Given significant performance improvements of synchronized
methods in recent JVM versions, synchronized
methods are now
preferred over the less robust double-checked locking.
If marking the entire method as synchronized
is not an option, consider using an inner static class
to hold the reference
instead. Inner static classes are guaranteed to be initialized lazily.
Code examples
Noncompliant code example
public class ResourceFactory {
private static Resource resource;
public static Resource getInstance() {
if (resource == null) {
synchronized (DoubleCheckedLocking.class) { // Noncompliant, not thread-safe due to the use of double-checked locking.
if (resource == null)
resource = new Resource();
}
}
return resource;
}
}
Compliant solution
public class ResourceFactory {
private static Resource resource;
public static synchronized Resource getInstance() { // Compliant, the entire method is synchronized and hence thread-safe
if (resource == null)
resource = new Resource();
return resource;
}
}
Compliant solution
Alternatively, a static inner class can be used. However, this solution is less explicit in its intention and hence should be used with care.
public class ResourceFactory {
private static class ResourceHolder {
public static Resource resource = new Resource(); // Compliant, as this will be lazily initialised by the JVM
}
public static Resource getResource() {
return ResourceFactory.ResourceHolder.resource;
}
}
Resources