[concurrency-interest] DCL clarification Immutable singelton

Michael Kuhlmann concurrency at kuli.org
Wed Apr 9 04:46:35 EDT 2014

Hi vikas,

you are absolutely right: _instance must be either volatile, or
Singleton must be immutable.

In this case it's easy since Singleton only has primitive types, so
marking all of them final makes Singleton immutable. It's getting more
problematic when Singleton contains values like HashMap or ArrayList; in
that case it's not enough to declare them as final because the values
themselves are not immutable. You'd had a safe publication of Singleton
itself then, but not of its contents.

The best choice would be to get rid of the lazy initialization
completely. I don't see a point here why Singleton shouldn't be
instantiated after the class has been loaded at all.

If you really need lazy initialization, it's better to put a static
final field into an inner class that does nothing else excepting keeping
this field. So the main class can be loaded without immediately
instantiating it, and Java's class loading mechanism can be used to
perform the lazy loading strategy.


Am 09.04.2014 08:20, schrieb vikas:
> Hi just wanted a little clarification. 
> I know the below code is broken and making _instance volatile would help 
> fixing this this.  The reason for broken code is unsafe publication of
> Singleton. Other threads can see non-null 
> reference even before the object is fully constructed.
> But if the Singleton is immutable i.e all instance fields are final, even
> then would it be broken?.
> AFAIK final fields give guarantees of safe publication of objects.
> So my question is if i,j,k below are final do i need *_instance* to be
> volatile. 
> final class  Singleton {
>           private static  Singleton _instance;
>           public static Singleton getInstance() {
>                             if(_instance == null) {
>                                        synchronized(Singleton.class) {
>                                                  if(_instance == null) {
>                                                        _instance = new
> Singleton();
>                                                  }
>                                        }
>                              }
>                             return _instance;
>            }      
>           private Singleton() {
>                       i=9;
>                       j=99;
>                       k=999;
>           }
>           private int i,j,k;               
> }
> --
> View this message in context: http://jsr166-concurrency.10961.n7.nabble.com/DCL-clarification-Immutable-singelton-tp10862.html
> Sent from the JSR166 Concurrency mailing list archive at Nabble.com.
> _______________________________________________
> 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