Suppose I have those two implementations of a singleton:
1)
class Singleton {
private static Singleton singleton;
private Singleton(){}
public static synchronized Singleton getInstance() {
if(singleton == null ){ singleton = new Singleton(); }
return this.singleton;
}
}
2)
class Singleton {
private static Singleton singleton;
private Singleton(){}
public static Singleton getInstance(){
synchronized(Singleton.class){
if(singleton == null ){ singleton = new Singleton(); }
}
return this.singleton;
}
}
What is the difference between those? In other words, is there a difference between using a synchronized block and using the synchronized keyword on the method for this case?