I am confused about this , double-checked locking need volatile.
public class someClass {
public volatile static uniqueInstance = null;
public static someClass getInstance() {
if(uniqueInstance == null) {
synchronized(someClass.class) {
if(uniqueInstance == null) {
uniqueInstance = new someClass();
}
}
}
return uniqueInstance;
}
The reason is this , Why is volatile used in this example of double checked locking. according this explains, the reason is that be "initialized" with partially constructed object.
The real problem is that Thread A may assign a memory space for instance before it is finished constructing instance. Thread B will see that assignment and try to use it. This results in Thread B failing because it is using a partially constructed version of instance.
But why Thread B will see the latest value , Thread B will read the old value before synchronized block finished.
Each thread may see a different snapshot, so the fact that one thread reads a variable inside a synchronized block does not mean that another thread which reads the variable without synchronization will see the same state thanks in advance.
thanks in advance