Tuesday, July 19, 2005

Double-Checked Locking is Broken in Java

The double-checked locking is broken in Java and it doesn't work. This declaration explains in great detail why?

Double-Checked Locking is Broken

This widely used idiom in singletons doesn't work:


public class ClassA {
private static ClassA INSTANCE;

private ClassA() {
super();
init();
}

public static ClassA getInstance() {
if (null == INSTANCE)
synchronized (this) {
if (null == INSTANCE) {
INSTANCE = new ClassA();
}
}

return INSTANCE;
}
}


An approach that will work is to do the following:


public class ClassA {
private static final ClassA INSTANCE = new ClassA();

private ClassA() {
super();
init();
}

public static ClassA getInstance() {
return INSTANCE;
}
}

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?