[concurrency-interest] Race condition on singleton

Guy Korland gkorland at gmail.com
Fri Dec 10 10:31:11 EST 2010


David,

we got it while running jdk6u19.
The problem is that it happened to us only once and in two different places in the code that uses the same pattern. 

Regards,
Guy Korland
-----Original Message-----
From: David Holmes
Sent:  10-12-2010, 00:31 
To: Guy Korland; concurrency-interest
Subject: RE: [concurrency-interest] Race condition on singleton


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




More information about the Concurrency-interest mailing list