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:

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).

Learn more about this topic

Join the discussion
Be the first to comment on this article. Our Commenting Policies