dimanche 4 octobre 2015

Why we need volatile in double checked locking in Singleton?

I understand there are lots of question around this and almost all of them are answered but I could not really understand the exact need for volatile. So I am creating a new one, below are my understanding and questions

Sample Code:

private static volatile Singleton _instance; 
public static Singleton getInstanceDC() { 
  if (_instance == null) {    // Single Checked 
     synchronized (Singleton.class) { 
        if (_instance == null) { // Double checked 
            _instance = new Singleton(); 
        } 
     } 
  } 
  return _instance; 
}

Understandings: When we put something in synchronized block, first is that will be executed by one thread at a time, and also when it finishes synchronized block it refreshes main memory with all the data required from thread local cache.

Question: So if my understanding is correct than in the double checked locking mechanism once the thread finishes the synchronized object creation block it also refreshes the object details into the object level INSTANCE variable in main memory, which should be visible to other threads.

Now we can argue that the second thread may cache that variable before it is updated by the first thread and that's why second thread might miss the updated value, if that is the case then in multi-threaded environment is not it become necessary that all the properties of shared object should be volatile which can change?

I know there is another explanation about object creation which is 3 step process and compiler can reorder the statements and put the assignment statement at the end and that may give half baked object to other thread but again as it is happening inside the synchronized block it does not matter.

Kindly help me with your expertise.

Aucun commentaire:

Enregistrer un commentaire