[concurrency-interest] AtomicBoolean and Double-Checking Locking? Is this Singleton safe?

Jeremy Manson jmanson at cs.purdue.edu
Tue Jun 28 15:02:23 EDT 2005


Hi John,

This is safe, in the sense that AtomicBooleans can be used for volatiles.
It would probably make somewhat more sense to use AtomicReference
rather than AtomicBoolean.

Having said that, I am not sure this is a good idea.  Not all platforms are 
guaranteed
to support efficient AtomicXXXs.  The code is uglier than the simple use
of volatile, which is designed to work correctly in this case.  
Where is the win here?

					Jeremy

On Tue, Jun 28, 2005 at 01:17:15PM -0500, John D. Heintz wrote:
> Hello all,
> 
> I've been waiting for a bunch of new Double-Checked locking articles
> to come out since the release of the java.util.concurrent.atomic
> package, but I've seen very little ;-)
> 
> The most recent discussion I could find was
> http://altair.cs.oswego.edu/pipermail/concurrency-interest/2005-May/001472.html,
> but of course I may have missed something.
> 
> I have a simple question: can an AtomicBoolean check _safely_ replace
> the '== null' from yester-years un-safe Double-Checked Locking
> Singleton idiom?
> 
> Here's an example Singleton implementation to show what I mean.
> ================================================
> import java.util.concurrent.atomic.AtomicBoolean;
> 
> public class Singleton {
> 	static Singleton _instance;
> 	static AtomicBoolean _instanceFlag = new AtomicBoolean(false);
> 	
> 	public Singleton() {
> 		
> 	}
> 	
> 	static Singleton getInstance() {
> 		if (_instanceFlag.get() != true) {
> 
> 			synchronized (_instanceFlag) { // block others until finished constructing
> 				// double check
> 				if (_instanceFlag.get() != true) {
> 					_instance = new Singleton();
> 					
> 					if (!_instanceFlag.compareAndSet(false, true)) {
> 						throw new IllegalStateException("Ack! Can't fail this call!!!");
> 					}
> 				}
> 			}
> 			
> 		}
> 		return _instance;
> 	}
> }
> ===============================================
> 
> 
> Thanks all,
> John
> 
> -- 
> John D. Heintz
> Software Craftsman
> Austin, TX
> (512) 633-1198
> 
> jheintz at pobox.com
> http://johnheintz.homeip.net
> 
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest


More information about the Concurrency-interest mailing list