[concurrency-interest] DCL clarification Immutable singelton

vikas vikas.vksingh at gmail.com
Wed Apr 9 02:20:54 EDT 2014


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.


More information about the Concurrency-interest mailing list