As we know for synchronous operation while creating singleton class we make whole method as synchronized or only block of statements which are responsible for creation of object as synchronized.But, among these two approaches which one is better and why?
Approach 1
public static A getA(){
if (obj == null){
synchronized(Singleton.class) {
if (obj == null) {
obj = new Singleton();//instance will be created at request time
}
}
}
return obj;
}
Approach 2
public synchronized static A getA(){
if (obj == null){
obj = new Singleton();//instance will be created at request time
}
return obj;
}