[concurrency-interest] Race condition on singleton

Guy Korland gkorland at gmail.com
Thu Dec 9 07:44:48 EST 2010


Hi,

We found a very strange pattern that seems like contradicting the Java
Memory Model.
It seems like a class that is maintained as singleton doesn't have its
constructor fully initialized!
See the code example bellow.

public class MyClass{

  private static final MyClass = new MyClass();

  private final HashMap map;

  private MyClass(){
      map = new HashMap();
  }

  public void put(Object k, Object v){
     map.put(k,v);
  }

  static public getMyClass(){
    return myClass;
  }
}


And when we invoke the following:

MyClass.getMyClass().put("a","b");

We get a NullPointerException on the "map.put(k,v);", meaning the map==null
!?!?

Any ideas?

Thanks,
Guy Korland
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20101209/96b5eaa7/attachment.html>


More information about the Concurrency-interest mailing list