Newsflash: Double-checked locking is still broken
Tony responds to a reader’s suggestion about synchronization
April 12, 2002
Q: In ” Singletons with Needles and Thread ,” you declare the getInstance() method in the Singleton class as synchronized. The drawback to this approach: the getInstance() call is synchronized even if the Singleton exists — thus introducing unneeded overhead.
I suggest the following as a better approach:
public class Singleton {
private static Singleton instance;
public static Singleton getInstance() {
if (null == instance) {
synchronized(Singleton.class) {
if (null == instance) {
instance = new Singleton();
}
}
}
return instance;
}
}
A:
- “The ‘Double-Checked Locking Is Broken’ Declaration,” David Bacon, et al.
- “Double-Checked Locking: Clever, but Broken,” Brian Goetz (JavaWorld, February 2001)
- “Warning! Threading in a Multiprocessor World,” Allen Holub (JavaWorld, February 2001)
- “Can Double-Checked Locking Be Fixed?,” Brian Goetz (JavaWorld, May 2001)
- “Can ThreadLocal Solve the Double-Checked Locking Problem?,” Brian Goetz (JavaWorld, November 2001)
- “Letters to the Editor,” (JavaWorld):
Also, consider this alternative:
public class Singleton {
public final static Singleton INSTANCE = new Singleton();
private Singleton() {}
}