By using a volatile boolean that is read only if the instance is null, can I avoid the default/frequent volatile read once the instance is initailized like so? Havent seen anyone recommend double checked locking like this, but seems to avoid volatile reads once fully initialized…
public class Singleton {
private static volatile boolean initialized = false;
private static Object lock = new Object();
private static Singleton instance;
public static Singleton getInstance(){
if(instance != null) return instance;
if(!initialized){
synchronized(lock){
if(!initialized){
instance = new Singleton();
initialized = true;
}
}
}
return instance;
}
}
No, you cannot. If thread A has reached the synchronized block and is executing the
line, a thread B entering your function could see
instanceas initialized before thread A has finished constructing the object. So you risk having thread B try to work on a partially constructed object.See the DLCP article for variations and explanations on this pattern.