I want to know what is use of making Instance variable as volatile in double null check implementation of Singleton. Because as per my understanding synchronize block provide happens before implicitly. No two threads can access that synchronized block concurrently and while exiting from synchronized block, thread write all its local cached data to main memory. I search a lot but still i have doubts in this implementation. Please explain correct use.
private volatile Singleton INSTANCE;
public Singleton get() {
if (INSTANCE == null) {
synchronized (this) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
In above double checking code. What may b the issue if i dont make my instance as volatile. Because when first thread enter in synchronize block, no other thread will get access to that block. And when first thread leaves that block. Object will be created and due to happens before property, latest value of instance will be written in main memory. So why volatile is important in this scenario?
Here's a link (Is there any need to add volatile keyword to guarantee thread-safe singleton class in java?) of similar question. But answers are not very clear. I don't think in above given scenario any kind of JVM optimization can cause breaking of happens before of synchronize block