I have seen some similar questions,but I still have some confusions.
code is here:
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;
}
In this question Why is volatile used in double checked locking, it says that without a volatile
keyword, a thread may assign the instance variable before the constructor finishes, so another thread may see a half-constructed object, which can cause serious problem.
But I don't understand how volatile can solve the problem. Volatile
is used to ensure visibility, so when thread A assign a half-constructed object to instance variable, the other thread can immediately see the change, which makes the situation worse.
How does volatile
solve the problem, somebody please explain to me. Thanks!