by Tony Sintes

Newsflash: Double-checked locking is still broken

news
Apr 12, 20021 min

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):
    • March 2001
    • June 2001
    • July 2001
    • November 2001

Also, consider this alternative:

public class Singleton {
    public final static Singleton INSTANCE = new Singleton();
    private Singleton() {}
}
Tony Sintes is an independent consultant and founder of First Class Consulting, Inc., a consulting firm that specializes in bridging disparate enterprise systems and training. Outside of First Class Consulting, Tony is an active freelance writer, as well as author of Sams Teach Yourself Object-Oriented Programming in 21 Days (Sams, 2001; ISBN: 0672321092).