It's not a secret anymore!
The moose likes Java in General and the fly likes Double-checked locking and Singleton Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Double-checked locking and Singleton" Watch "Double-checked locking and Singleton" New topic

Double-checked locking and Singleton

avihai marchiano
Ranch Hand

Joined: Jan 10, 2007
Posts: 342

The following article explian about issues that can pop up when you implement Singleton.

They claim there that the double checked locking is not good because -
Unfortunately, double-checked locking is not guaranteed to work because the compiler is free to assign a value to the singleton member variable before the singleton's constructor is called. If that happens, Thread 1 can be preempted after the singleton reference has been assigned, but before the singleton is initialized, so Thread 2 can return a reference to an uninitialized singleton instance.

Is this problem still relevant to java 5?

What is the solution in case that my constructor needs to throw exceptions? (In this case I can�t initialize the singleton instance in the declaration as suggested by them)
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Basically you just want to synchronize the whole access method -- i.e.,

People worry far too much about the cost of synchronization. It's quite minimal, really.

[Jess in Action][AskingGoodQuestions]
avihai marchiano
Ranch Hand

Joined: Jan 10, 2007
Posts: 342
This is one of the suggested solution.

but -
however, the astute reader may realize that the getInstance() method only needs to be synchronized the first time it is called. Because synchronization is very expensive performance-wise (synchronized methods can run up to 100 times slower than unsynchronized methods),
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Synchronization has gotten much cheaper over the years. Frankly I think that article in 2003 was already rather out-of-date in this area, and now it's more out-of date. Synchronization is not that big a deal, performance-wise, and much convoluted, hard-to-maintain code has been written needlessly by people trying to avoid it.

As for your original question, Java 5 does allow the double-checked locking technique to work correctly, if you mark the variable as volatile. If you don't mark the variable volatile, it's still broken. See this FAQ for more info. And note that they suggest a better way to achieve a lazily-initialized singleton anyway:

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Double-checked locking and Singleton
It's not a secret anymore!