[concurrency-interest] Race condition on singleton

David Holmes davidcholmes at aapt.net.au
Thu Dec 9 17:28:04 EST 2010


Fuad Malikov writes:
> The proper usage should be:
>
> public class MyClass{
>
>  private static class MyClassHolder {
>     public static MyClass myClass = new MyClass();
> }

You only need the holder idiom if you want lazy initialization. There's
nothing wrong with eager initialization if you know your class is always
going to be lkoaded anyway.

David Holmes

>   private final HashMap map;
>
>   private MyClass(){
>       map = new HashMap();
>   }
>
>   public void put(Object k, Object v){
>      map.put(k,v);
>   }
>
>   static public getMyClass(){
>     return MyClassHolder.myClass;
>   }
> }
>
> Fuad
>
> On Thu, Dec 9, 2010 at 2:44 PM, 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
> >
> >
>
>
>
> --
>
> @fuadm
>
> _______________________________________________
> 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