[concurrency-interest] Race condition on singleton

David Holmes davidcholmes at aapt.net.au
Thu Dec 9 17:31:21 EST 2010


Hi Guy,

In addition to compilable/runnable test case can you tell us which platform
and which JDK version please. Also can you test if it happens
with -Xint -client and -server.

Other than the typo in the variable name there's nothing wrong with your
code and static initialization of the class should be ensuring full
visibility.

David Holmes
  -----Original Message-----
  From: concurrency-interest-bounces at cs.oswego.edu
[mailto:concurrency-interest-bounces at cs.oswego.edu]On Behalf Of Guy Korland
  Sent: Thursday, 9 December 2010 10:45 PM
  To: concurrency-interest
  Subject: [concurrency-interest] Race condition on singleton


  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/20101210/74db70e8/attachment.html>


More information about the Concurrency-interest mailing list