I am learning Java concurrency and know that the following singleton is not completely thread safe. A thread may get instance before it is initialized because of instructions reordering. A correct way to prevent this potential problem is to use volatile keyword.
public class DoubleCheckedLocking {
private static Instance instance;
public static Instance getInstance() {
if (instance == null) {
synchronized (DoubleCheckedLocking.class) {
if (instance == null)
instance = new Instance();
}
}
return instance;
}
}
I tried to reproduce the potential problem without volatile keyword and wrote a demo to show that using the above code may cause a NullPointerException in multithreading environment. But I failed to find a way to explicitly let the Java compiler perform instructions reordering and my demo with the above singleton always works pretty well without any problems.
So my question is how to explicitly enable/disable Java compiler to reorder instructions or how to reproduce the problem without using volatile keyword in a double-checked locking singleton?