Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Newsflash: Double-checked locking is still broken

Tony responds to a reader's suggestion about synchronization

  • Print
  • Feedback

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 I'll keep this short: Double-checked locking is still broken. Please read:



Also, consider this alternative:

About the author

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).
public class Singleton {
    public final static Singleton INSTANCE = new Singleton();
    private Singleton() {}
}


  • Print
  • Feedback

Resources