Sub topic 12
When and how classes are initialized
This chapter assumes you can read basic javap output. It also assumes you know the loading and linking phases from earlier chapters: a class is loaded, then verified, prepared and resolved. Initialization is the last phase. It is the point where the JVM runs your static initializers.
What initialization is
Loading creates a Class object from bytes. Preparation allocates static fields and sets them to default values (0, false, null). Neither step runs your code. Initialization runs the class's static initialization code, so static fields get the values you wrote and static { } blocks execute.
The compiler gathers all of that code into one synthetic method named <clinit>. It contains the static field initializers and static blocks in the order they appear in the source. You can see it in javap -c output. A class with no static initializers has no <clinit>.
The JVM initializes a class lazily, at the first use that requires it. That use is called an active use.
What triggers initialization
A class is initialized immediately before the first of these events:
| Trigger | Example |
|---|---|
| Creating an instance | `new Helper()` |
| Calling a static method | `Helper.run()` |
| Reading or writing a static field that is not a compile-time constant | `Helper.value` |
| Being the main class named on the command line | `java Lazy` |
| Reflection that initializes | `Class.forName("Helper")` |
| Initializing a subclass | superclass is initialized first |
These events do not initialize the class:
- Reading a
static finalfield whose value is a compile-time constant, such asstatic final int CONSTANT = 42.javaccopies the value into the caller's bytecode, so the class is never touched. - Using a class literal, such as
Helper.class. - Creating an array of the type, such as
new Helper[3]. This loads the array class but does not initializeHelper. - Reading a static field through a subclass name when a superclass declares it. Only the declaring class is initialized.
- Calling
Class.forName(name, false, loader), which loads without initializing.
Watching it happen
This is the example from the plan, with its output.
public class Lazy {
static final int CONSTANT = 42;
static int value = init();
static {
System.out.println("Lazy initialized");
}
static int init() {
System.out.println("Initializing value");
return 7;
}
public static void main(String[] args) {
System.out.println(Helper.CONSTANT);
System.out.println(Helper.value);
}
}
class Helper {
static final int CONSTANT = 42;
static int value = 7;
static {
System.out.println("Helper initialized");
}
}Initializing value
Lazy initialized
42
Helper initialized
7Lazy is the main class, so it is initialized first. Its field initializer and static block run in source order. Helper.CONSTANT is inlined as 42, so Helper stays untouched. Helper.value is not a constant, so reading it compiles to getstatic, which initializes Helper first.
Order across a class hierarchy
Before a class initializes, the JVM initializes its superclass. Superinterfaces are not initialized by default. An interface is initialized only if it declares a default method or if you use one of its non-constant fields.
public class Order {
static class Parent {
static int p = log("Parent.p");
static { log("Parent block"); }
static int log(String s) {
System.out.println(s);
return 1;
}
}
static class Child extends Parent {
static int c = log("Child.c");
static { log("Child block"); }
}
public static void main(String[] args) {
System.out.println(Child.p);
System.out.println("--");
System.out.println(Child.c);
}
}Parent.p
Parent block
1
--
Child.c
Child block
1Child.p compiles to a reference to Child, but the field is declared in Parent. The JVM resolves it to Parent and initializes only Parent. Child initializes on the second access. Its superclass is already done, so only the Child code runs.
Initialization state machine
Each class is in one of a few states, tracked by the JVM. Another thread can find the class in progress, and that matters for concurrency.
Static fields before their initializers run
Preparation sets static fields to defaults, and initializers run later in textual order. Code that runs earlier in <clinit> can therefore read a field before its initializer has run. The compiler forbids a direct forward reference by name, but a method call hides it from the compiler.
public class ForwardRead {
static int a = readB();
static int b = 5;
static int readB() {
return b;
}
public static void main(String[] args) {
System.out.println(a + " " + b);
}
}0 5a is set while b still holds its default 0. The same effect appears in cycles. If A's initializer uses B and B's initializer uses A, then whichever class started first is still in progress. The second class sees its partner's fields with default values.
Threads and the initialization lock
The JVM guarantees that a class is initialized once. Each class has an initialization lock. The thread that starts initialization marks the class in progress and runs <clinit>. Other threads that need the class block until it finishes. A thread that already holds the in-progress state, such as one that reenters through a cycle, continues without waiting.
Two consequences follow:
- Static initialization is thread-safe by construction. The lazy holder idiom relies on this: a private static nested class holds the instance in a static field, and the JVM creates it on first use without any explicit locking.
- Two threads can deadlock if class
Ainitialization needsBand classBinitialization needsA, and each thread starts from a different end. The cause is the two class initialization locks. A thread dump shows both threads waiting inside<clinit>. The fix is to remove the cyclic dependency, or to avoid doing work in static initializers.
Failed initialization
If <clinit> throws, the JVM wraps an unchecked exception in ExceptionInInitializerError, and the class becomes erroneous. It cannot be initialized again. Every later use throws NoClassDefFoundError.
public class InitFailure {
static class Broken {
static int value = Integer.parseInt("not a number");
}
public static void main(String[] args) {
try {
System.out.println(Broken.value);
} catch (Throwable t) {
System.out.println(t);
System.out.println("cause: " + t.getCause());
}
try {
System.out.println(Broken.value);
} catch (Throwable t) {
System.out.println(t);
}
}
}java.lang.ExceptionInInitializerError
cause: java.lang.NumberFormatException: For input string: "not a number"
java.lang.NoClassDefFoundError: Could not initialize class InitFailure$BrokenControlling initialization
- Use
Class.forName("Name")when you want initialization, as old JDBC code did to run a driver's static registration. UseClass.forName("Name", false, loader)to load without initializing. - Keep static initializers short and free of side effects. Avoid I/O, threads and calls into code that may depend on your class.
- Prefer lazy holder classes to eager singletons when creation is costly or may fail.
- Remember that each class loader defines its own classes. The same class loaded by two loaders is initialized twice, once per loader. Each copy has separate static state.
Seeing it in the log
Use unified logging to list the classes in your run, then add prints to your own static blocks to correlate them. Loading and initialization are separate events. Loading appears in the log, while initialization shows only through your own output.
$ java -Xlog:class+load:file=classload.log LazyIn this log Helper appears only after Helper.value is read. If you change the program to use only Helper.CONSTANT, Helper never appears at all, because the constant was inlined.
Exercise
In the Order example, what is printed if main contains only System.out.println(Child.class);? What if it contains only Parent p = null;?
Show answer
Neither prints a log line from the static code. A class literal loads the class but does not initialize it, so the first statement prints only class Order$Child. Declaring a variable of a type triggers no loading or initialization at all, so the second prints nothing.
Exercise
A class has static final String NAME = "app"; and static final String HOST = System.getProperty("host");. Reading which field from another class initializes it, and why?
Show answer
Reading HOST initializes the class. NAME is a compile-time constant that javac inlines into the caller. HOST is static final but is computed at run time, so reading it compiles to getstatic and triggers initialization.
Exercise
After a static initializer throws, a service logs NoClassDefFoundError: Could not initialize class Config on every request. Where do you look for the root cause?
Show answer
Find the first ExceptionInInitializerError for Config, which happened on the first use. Its cause holds the original exception. Later requests only see the erroneous state of the class, which cannot be retried without restarting the JVM or using a new class loader.