CRITICAL
Rule Definition
Double checked locking is a software design pattern used to reduce locking overhead when implementing lazy initialization in a multi-thread environment. This avoid to initializing a value until the first time it is accessed.
This pattern is unsafe because there is no guarantee it will work on single or multi-processor machines.
Note also that even if this issue as been fixed in JSE 5.0 it doesn't provide performance optimization.
Remediation
To remediate, there are two solutions depending on performance choice:
1/ synchronize the method: each call to this method will cost but the initialization will be made when needed
2/ make the field static (Initialize-On-Demand Holder Class idiom): the field will be initialized during the initialization of the class even if not required, but each call to the method that return this field will not cost.
Violation Code Sample
class Foo {
private Helper helper = null;
public Helper getHelper() {
if (helper == null) {
synchronized(this) {
if (helper == null) {
helper = new Helper();
}
}
}
return helper;
}
}
Fixed Code Sample
1/ synchronized the method getHelper()
class Foo {
private Helper helper = null;
public synchronized Helper getHelper() {
if (helper == null)
helper = new Helper();
return helper;
}
2/ declare the field as static
class Foo {
private static Helper helper = new Helper();
public Helper getHelper() {
return helper;
}
Reference
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
http://www.artima.com/designtechniques/threadsafety.html
http://www-128.ibm.com/developerworks/java/library/j-dcl.html
http://www-128.ibm.com/developerworks/java/library/j-jtp03304/
Related Technologies
JEE
Technical Criterion
Secure Coding - Time and State
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.