hi,i have a problem on double check lock in singleton pattern。 in follow code :
private volatile static DoubleCheckSingleton instance;
private DoubleCheckSingleton() {}
public static DoubleCheckSingleton getInstance(){
if(instance==null){ //first
synchronized (DoubleCheckSingleton.class){
if(instance==null){ // second
instance=new DoubleCheckSingleton();
}
}
}
return instance;
}
Suppose there are now two threads, A and B respectively. Afterwards they execute simultaneously. According to happens-before definition, after one thread releases the lock, another thread acquires the lock, then the latter can see the previous change.
If so, I don't think the volatile keyword is needed, so why should we use the volatile keyword here? Which friend can explain it? Thank you for your answer