Video in progress

Strong Middle ⚙️ JVM and memory

When exactly does a class's static initializer run, and how does the lazy holder idiom rely on that?

A static block runs the first time the class is actively used: when an object is created, a static method is called, or a non-constant static field is read. The JVM makes this step thread-safe, and the lazy holder takes advantage of that.

📖 Answer

A class goes through three stages: loading (the bytecode is read), linking (verify, prepare, which gives static fields their default values, and resolve) and initialization, where <clinit> is executed. A loaded class may not be initialized yet.

Initialization happens only on the "first active use". Getting Foo.class or creating a Foo[] array does not trigger it. Reading a compile-time constant (static final int MAX = 10) doesn't either, because the value was copied straight into the calling class.

The JVM specification guarantees that <clinit> runs once and under a lock. The lazy holder uses exactly this:

public final class Config {
    private Config() {}

    private static class Holder {
        // Holder is initialized only when get() is called for the first time
        static final Config INSTANCE = new Config();
    }

    public static Config get() {
        return Holder.INSTANCE;
    }
}

You need neither synchronized nor volatile. One caveat: if an exception is thrown inside the static block, the class stays in a "broken" state; we can talk about that in the next questions. Another trap: if two classes refer to each other in their static initializers and two threads start them in parallel, a deadlock can occur.