New to Java from C++ and came across this synchronized block example (more context on this page). My question is:
Shouldn't the "if" statement also be included in the "synchronized block"? Or else other threads could be executing the same piece of code, pass the "if" checkpoint and thought that the "_instance" is null and then after the current thread finishes executing the synchronized block (and creates a new instance), other thread(s) will create duplicated instances? Thanks!
Now I realized that the code was actually doing double-checking, I have a new question then, why is double-checking needed? Thanks!
The code block is copied below:
public class Singleton{
private static volatile Singleton _instance;
public static Singleton getInstance(){
if(_instance == null){ //Shouldn't this line be included in the synchronized block?
synchronized(Singleton.class){
if(_instance == null) _instance = new Singleton();
}
}
return _instance;
}