Sunday, November 5, 2006

Singleton pattern and Double-Checked Locking problem

Double-Checked Locking is widely cited and used as an efficient method for implementing lazy initialization in a multithreaded environment.
Unfortunately, it will not work reliably in a platform independent way when implemented in Java [...]
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

All programming languages have their share of idioms. Many are useful to know and use, and programmers spend valuable time creating, learning, and implementing them. The problem is that some idioms are later proven not to be all that they were purported, or to simply not work as described. The Java programming language contains several useful programming idioms. It also contains some that further study has shown should not be used. Double-checked locking is one such idiom that should never be used. In this article, Peter Haggar examines the roots of the double-checked locking idiom, why it was developed, and why it doesn't work.
http://www-128.ibm.com/developerworks/java/library/j-dcl.html


I think the problem with DCL comes from checking the wrong variable. Instead of checking the static instance itself one should check a boolean, which is by nature an atomic operation. This would prevent the mentioned JVM memory model "problem". What do you think?



public class Singleton {

private static Singleton _instance = null;
private static boolean _initialized = false;

private Singleton() {
}

public static Singleton getInstance() {
if (!_initialized) {
synchronized (Singleton.class) {
if (!_initialized) {
_instance = new Singleton();
_initialized = true;
}
}
}
return _instance;
}

}