out-of-order write 때문에 문제가 발생할수 있다고 한다. 메모리 가시성에 대해서도 알아야하고, JDK 버전에 따라 작동 방식이 다를 수도 있다.
public class MyDCLSingleton {
private static volatile MyDCLSingleton instance;
private MyDCLSingleton() {
// ...
}
public static MyDCLSingleton getInstance() {
if (instance == null) { // A
synchronized (MyDCLSingleton.class) {
if (instance == null) { // B
instance = new MyDCLSingleton();
}
}
}
return instance; // C
}
}