Fix double check locking in Java 5

We can fix the double check locking  using volatile keyword. In Java 5, the JRE system will not allow a write of volatile to be reordered i.e read and write of volatile cannot be reordered w.r.t any previous read and write. So the volatile always gives the latest value.
class Foo{
               private volatile Helper helper=null;
               public Helper getHelper(){
                  if(helper=null){
                      synchronized(this){
                          if(helper=null)
                              helper=new Helper();
                   }
               }
               return helper;
          }
}

Comments

  1. I've always wondered why is double check locking still used. If you simply synchronize the getter itself, there will be no need to check twice or worry about read/write reordering and volatile behavior inconsistency (as you said, it changed it's behavior in Java 5). Much simpler that way and it behaves well even on Java 4.

    ReplyDelete
  2. I have a better option. Why go for Lazy loading of a resource. Just create statically and there will be no need for synchronization. as explained below:-

    Do:-

    private volatile Helper helper=new Helper();

    Instead of :-

    private volatile Helper helper=null;

    ReplyDelete
  3. Yes Munish.. but lazy loading can be requirement some time...

    It would be good if you place 2 code snapshotlike.. before and now will help others a lot.

    ReplyDelete
  4. What about IODH? See http://www.oreillynet.com/onjava/blog/2007/01/singletons_and_lazy_loading.html or http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

    ReplyDelete
  5. How much of the solution is the volatile keyword, and how much is the synchronized block?

    ReplyDelete
  6. @veggen - if you synchronize the getter, then every fetch of the value pays the price of that lock. We want both lazy loading (don't create unless/until needed, since creation might be expensive) and no overhead from unnecessary locking. The initialize-on-demand holder is the best solution I've found -- see http://blog.temposwc.com/2011/02/getting-around-double-checked-locking.html.

    ReplyDelete
  7. In the age of dependency injection/tdd code I don't really think the singletons are necessary. I prefer to enforce singletonness through the DI container.

    ReplyDelete

Post a Comment

Popular posts from this blog

When to use getClass() and instanceOf in Java

Generate Heap Dump in Unix