Double-checked locking tries to initialize a field on demand and in a thread-safe manner while avoiding the cost of synchronization.
Unfortunately it is not thread-safe when used on a field that is not declared volatile
.
When using Java 1.4 or earlier, double-checked locking doesn't work even with volatile
fields.
Read the article linked above for the detailed explanation of the problem.
Example of an incorrect double-checked locking:
class Foo {
private Helper helper = null;
public Helper getHelper() {
if (helper == null)
synchronized(this) {
if (helper == null) helper = new Helper();
}
return helper;
}
}
// other functions and members...
}