While implementing the Singleton pattern, could someone please explain the difference between:
Synchronized Static Method:
public static synchronized Singleton getInstance() {
if(instance==null){
instance = new Singleton();
}
return instance;
}
and Synchronized block inside a static method:
public static Singleton getInstance() {
if(instance==null){
synchronized(Singleton.class){
if(instance==null){
instance = new Singleton();
}
}
}
return instance;
}
Why do we have to check instance==null
twice in the second method and what is the advantage of the second method over the first?