Video in progress

When and how many times is a static block in a class executed?

A static block runs once, during class initialization, that is, on the first active use of the class. If there are several static blocks, they run in the order they appear in the code.

📖 Answer

class Config {
    static final Map<String, String> VALUES = new HashMap<>();

    static {
        System.out.println("Config yuklanyapti");
        VALUES.put("env", "prod");
    }
}

The first time Config.VALUES is accessed, "Config yuklanyapti" is printed once. It doesn't run again on later accesses: within a single ClassLoader, a class is initialized once.

Even if several threads access it at the same time, the JVM performs the initialization under a lock: one thread runs it and the rest wait.

Something to watch for: if an exception is thrown in a static block, an ExceptionInInitializerError is thrown, and on later attempts a NoClassDefFoundError: the class is marked as "broken". Also, doing heavy work (network, files) in a static block slows startup and makes the error harder to understand.