Sub topic 8
The class loading lifecycle
This chapter assumes you can compile and run Java programs with javac and java. It also assumes you know what static members and exceptions are, and that you have seen the class file layout and constant pool from earlier chapters. Here you get the big picture of how a class goes from bytes to usable code. Later chapters cover the loader hierarchy, delegation, verification and initialization in detail.
Why classes are loaded lazily
The JVM does not read every class of your program at startup. It loads a class when running code first needs it. A class that sits in your jar but is never used is never loaded. This keeps startup fast and memory use low, and it explains why some errors only show up in the middle of a run.
Every class goes through the same stages, in this order:
- Loading finds the binary form of the class and creates a
Classobject from it. - Linking prepares the class for use. It has three sub-steps: verification, preparation and resolution.
- Initialization runs the class's static initializers.
After initialization the class is ready for normal use. The JVM may later unload it, but only under specific conditions covered at the end of this chapter.
Phase 1: loading
Loading starts when the JVM needs a class it has not yet seen, identified by its binary name such as com.example.Greeter. The JVM asks a class loader to produce that class. A class loader is an object (or, for core classes, built-in JVM code) that locates the bytes and hands them back.
Where the bytes come from is up to the loader. They can come from a .class file in a directory, an entry in a jar, the runtime image holding the JDK modules, a network connection, or a byte array generated at run time.
Once the bytes are found, the JVM does the following:
- It parses them and checks that they form a well-structured class file. The magic number must be
0xCAFEBABE, the version must be supported, and the constant pool and attributes must be well formed. A failure throwsClassFormatErrororUnsupportedClassVersionError. - It loads the direct superclass and all direct superinterfaces first, using the same loader. This is recursive, so loading
ArrayListloadsAbstractList,AbstractCollectionandObjectalong the way. - It builds the runtime representation of the class in metaspace and creates a
java.lang.Classobject on the heap that points to it.
Loading does not run any of the class's code. Static initializers have not run yet, and the class's static fields do not hold values yet.
Watching loading happen
Java 9 and later have unified JVM logging. The class+load tag records every class as it is loaded, along with where it came from.
public class LifecycleDemo {
public static void main(String[] args) {
System.out.println("main started");
if (args.length > 0) {
new Greeter().hello();
}
System.out.println("main done");
}
}
class Greeter {
void hello() {
System.out.println("hello");
}
}Compile the file, then run it twice and search each log for Greeter:
$ javac LifecycleDemo.java
$ java -Xlog:class+load:file=classload.log LifecycleDemo
$ grep -c Greeter classload.log
0
$ java -Xlog:class+load:file=classload2.log LifecycleDemo go
$ grep Greeter classload2.log
[0.04s][info][class,load] Greeter source: file:/home/you/demo/Without an argument, the new Greeter() line never runs, so the JVM never loads Greeter. With an argument, the class loads at the moment that line first executes. The exact timestamps and paths will differ on your machine. Core classes show a source such as jrt:/java.base, and your own classes show a file: location.
Phase 2: linking
Linking takes the loaded class and makes it safe and ready to run. It has three sub-steps.
Verification
The verifier checks that the bytecode obeys the language's safety rules. For example, it checks that the operand stack never overflows or underflows, that each instruction receives operands of the right type, that local variables are read only after being assigned, and that jumps land on valid instruction boundaries. Verification is what lets the JVM run classes from untrusted sources without crashing. A failure throws VerifyError.
Preparation
Preparation allocates memory for the class's static fields and gives them default values: 0 for numeric types, false for boolean, and null for references. It does not run initializer expressions. After preparation, a field declared static int value = 7; holds 0. The value 7 is assigned later, during initialization. The one exception is a static final field with a compile-time constant value. Its ConstantValue attribute is applied during preparation.
Resolution
The constant pool holds symbolic references such as "the method println in class java.io.PrintStream". Resolution replaces a symbolic reference with a direct reference to the actual class, field or method. HotSpot typically resolves a reference lazily, the first time an instruction that uses it executes. Resolving a reference can trigger loading of another class. Resolution errors surface as subclasses of IncompatibleClassChangeError, such as NoSuchMethodError and NoSuchFieldError, or as NoClassDefFoundError.
The table summarizes what each sub-step does and how it fails.
| Sub-step | What it does | Typical failure |
|---|---|---|
| Verification | Checks bytecode against safety rules | `VerifyError` |
| Preparation | Allocates statics with default values | `OutOfMemoryError` (rare) |
| Resolution | Turns symbolic references into direct ones | `NoSuchMethodError`, `NoClassDefFoundError` |
Phase 3: initialization
Initialization runs the class's initializer. The compiler gathers all static blocks and static field initializers, in source order, into one special method named <clinit>. The JVM runs it once per class. Only now do static fields get the values you wrote in your code.
The JVM initializes a class when one of these things happens for the first time:
- An instance is created with
new. - A static method of the class is called.
- A static field is read or written, unless it is a compile-time constant.
- The class is the entry point named on the
javacommand line. - Reflection forces it, for example
Class.forName("Name")with its one-argument form.
The JVM initializes the superclass before the subclass. It does not initialize interfaces just because a class implements them, unless the interface has default methods. If a <clinit> throws, the class is marked as erroneous. The first attempt fails with ExceptionInInitializerError, and every later use fails with NoClassDefFoundError.
Initialization is thread-safe. If two threads need the same class at once, one runs <clinit> and the other waits. Two classes whose initializers depend on each other, run from different threads, can deadlock.
Linking and initialization are separate
New programmers often blur the two. Keep in mind that:
- Linking happens before any of the class's code runs, and it never runs your static blocks.
- Initialization is where your code first executes.
- A class can be loaded and linked without ever being initialized.
Class.forName("Name", false, loader)does exactly this.
You can observe it with Class.forName:
public class PhaseDemo {
static class Probe {
static {
System.out.println("Probe initialized");
}
}
public static void main(String[] args) throws Exception {
Class<?> c = Class.forName("PhaseDemo$Probe", false,
PhaseDemo.class.getClassLoader());
System.out.println("loaded: " + c.getName());
Class.forName("PhaseDemo$Probe", true,
PhaseDemo.class.getClassLoader());
System.out.println("done");
}
}The output is:
loaded: PhaseDemo$Probe
Probe initialized
doneThe first call loads the class and returns a Class object without running the static block. The second call, with true, forces initialization.
Unloading
A class can be unloaded only when its defining class loader is garbage collected. That requires that nothing references the loader, any of its classes, or any instance of those classes. Classes loaded by the bootstrap, platform and application loaders live as long as the JVM does, so in practice they are never unloaded. Unloading matters for application servers, plugin systems and tools that create many short-lived loaders. A forgotten reference to one class can keep the whole loader and all its classes in metaspace.
Common mistakes
- Assuming a class loads at startup. A missing dependency may only fail when the code path using it first runs.
- Putting side effects in a static block and expecting them at a specific time. They run at first initialization, which may be later than you expect, or never.
- Treating
NoClassDefFoundErroras "the class file is missing". It can also mean the class's initializer failed earlier.
Exercise
In the LifecycleDemo program, Greeter is not loaded when you run it with no arguments. Name the phase in which the <clinit> method of a class runs, and say why static int value = 7; holds 0 right after preparation.
Show answer
<clinit> runs in the initialization phase, after loading and linking. Preparation only allocates static fields and sets them to default values (0 for int), so the initializer expression = 7 has not run yet. It runs later, inside <clinit>.
Exercise
A class Config has static final String NAME = "app"; and static final int SIZE = compute();. Code in another class reads Config.NAME and nothing else. Is Config initialized, and what changes if the code reads Config.SIZE?
Show answer
Reading Config.NAME does not initialize Config, because NAME is a compile-time constant that javac inlines into the reader. Reading Config.SIZE triggers initialization, because compute() is not a constant expression, so <clinit> runs and compute() is called first.