One common (1,2) way of implementing a singleton uses an inner class with a static member:
public class Singleton {
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
private Singleton() {
//...
}
}
This implementation is said to be lazily initialized and thread-safe. But what exactly guarantees its thread safety? JLS 17 that deals with Threads and Locks doesn't mention that static fields have any sort of happens-before relationship. How can I be sure that the initialization will only happen once and that all threads see the same instance?