Video in progress

What breaks in double-checked locking if there is no volatile?

class ConfigHolder {
    private static Config instance;   // no volatile

    static Config get() {
        if (instance == null) {
            synchronized (ConfigHolder.class) {
                if (instance == null) {
                    instance = new Config(loadProperties());
                }
            }
        }
        return instance;
    }
}

Another thread may see instance != null while the object isn't fully constructed yet, because the writes inside the constructor and the write of the reference can be reordered. volatile guarantees both the ordering and the visibility.

📖 Answer

instance = new Config(...) is really several steps: allocate memory, fill in the fields, write the reference to instance. In the Java memory model, without a happens-before relationship, another thread may see those writes in a different order. The second thread reads the first if without a lock, sees the reference, but the fields inside Config are still null or 0.

This bug is reproduced rarely and is almost never caught in tests, which is what makes it dangerous.

The fix is a single word:

private static volatile Config instance;

But often you don't need this pattern at all. For a lazy singleton, the holder idiom is simpler, and the JVM's class loading itself provides thread-safety:

class ConfigHolder {
    private static class Lazy {
        static final Config INSTANCE = new Config(loadProperties());
    }
    static Config get() { return Lazy.INSTANCE; }
}

In a Spring application, though, a singleton bean usually does this job, and there is no need to write it by hand.

An interesting detail: if all of Config's fields are final, they are seen correctly (final field semantics), but relying on that to drop the volatile is not a good habit.