Following is my singleton class where I am using double-checked-locking without using volatile keyword and without synchronizing the entire getInstance() method:
public class MySingleton {
private static MySingleton mySingleton;
public static MySingleton getInstance() {
if(mySingleton == null) {
synchronized(MySingleton.class) {
if(mySingleton == null) {
MySingleton temp = new MySingleton();
mySingleton = temp;
}
}
}
return mySingleton;
}
}
According to me, this is thread-safe. If anyone thinks, this is not thread-safe, can someone please elaborate on why he/she thinks this is not thread-safe? Thanks.
I wasn't aware of this issue until I read all the comments. The problem is that the various optimization processes (compiler, Hot Spot, whatever) rewrite the code. Your "temp" solution could easily be removed. I find it hard to believe that a constructor could return a partial object, but if knowledgeable contributors are saying so, I'd trust their opinion.