[concurrency-interest] Race condition on singleton

Marco Villalobos mvillalobos at kineteque.com
Mon Dec 13 00:28:18 EST 2010


By simply reading his code, which I assume is an abridged version of
the original, I didn't notice anything that would cause an NPE.

However, if his original code uses static variables, then order of
those declarations will matter.

For example:

public class WillNPE {

    private final static WillNPE instance = new WillNPE();
    private final static Set<Integer> set = new HashSet<Integer>();

    public static WillNPE getInstance() {
        return instance;
    }

    public WillNPE() {
        set.add(1);
    }

    public static void main(String args[]) {
        WillNPE local = WillNPE.getInstance();
    }
}


On Sun, Dec 12, 2010 at 9:10 PM, Justin T. Sampson <justin at krasama.com> wrote:
> I'm surprised with all the replies that no one commented on the lack of
> synchronization on accessing the contents of the map. That can easily cause
> NPEs from within map.put(k, v), or almost any other arbitrary behavior for
> that matter.
> Cheers,
> Justin
>
> On Thu, Dec 9, 2010 at 4:44 AM, Guy Korland <gkorland at gmail.com> wrote:
>>
>> 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
>>
>> _______________________________________________
>> Concurrency-interest mailing list
>> Concurrency-interest at cs.oswego.edu
>> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>>
>
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
>



More information about the Concurrency-interest mailing list