[concurrency-interest] How seriously should we take broken double checked idiom

Jeremy Manson jmanson at cs.purdue.edu
Mon May 2 21:21:26 EDT 2005


Unmesh joshi wrote:

> Is my understanding right?
> 

This is, in fact, one of the things that can happen when double-checked 
initialization is not written correctly.  For a full discussion, consult 
this web page:

http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

The fix is pretty easy, so you may want to implement it anyway.  If you 
have this:

class Foo {
   private Helper helper = null;
   public Helper getHelper() {
     if (helper == null)
       synchronized(this) {
         if (helper == null)
           helper = new Helper();
       }
     return helper;
     }
}

All you have to do in Java 5.0 and later is declare helper as 
"volatile", and the problem is fixed.

If you are stuck with an earlier version of Java, (or even if you 
aren't) strongly consider using the Initialization On Demand Holder Idiom:

private static class LazySomethingHolder {
   public static Something something = new Something();
}

public static Something getInstance() {
   return LazySomethingHolder.something;
}

It has the virtue of being simple, clean and having good performance.

					Jeremy


More information about the Concurrency-interest mailing list