I read the reason for synchronize the new instance creation is two threads can access getInstance same time and find that _instance is null and create two instances of Singleton class. So in order to eliminate that we synchronized it. But again how come a double-checked locking method introduce again check whether the instance is null inside the Synchronized block. Does this necessary? Once a code block is synchronized it already thread safe know?
public class Singleton {
private static Singleton _instance = null;
private Singleton() { }
public static Singleton getInstance() {
if (_instance == null) {
synchronized (Singleton.class) {
_instance = new Singleton(); // why need to again check null
}
}
return _instance;
}
}