Sub topic 2
Class loading, verification and linking
This chapter covers what the JVM does between "this class is needed" and "this class can run". The AOT cache removes much of that work, so you need the model first. I assume you can compile and run Java from the command line, know what a classpath and a JAR are, and have used -Xlog or a similar JVM flag at least once.
Why classes are the startup cost
A JVM does not read your whole program at launch. It starts, finds main, and loads each class the first time something needs it. A small application that uses streams, lambdas and string formatting touches hundreds or thousands of classes before it prints its first line. Most of them belong to the JDK, not to your code.
For every class, the JVM does the same work on every run:
- Locate the bytes of the class.
- Parse them into internal data structures.
- Check that the bytecode is safe.
- Prepare the class's memory and link it to other classes.
- Run its static initializers.
Each step is small. Multiplied by thousands of classes, together they make up a large share of startup time, and the result is identical on every run of the same application. That repetition is what the AOT cache removes.
The class lifecycle
The JVM Specification describes a class moving through these phases. HotSpot, the JVM in OpenJDK, follows them closely.
| Phase | What happens | Result |
|---|---|---|
| Loading | A class loader finds the `.class` bytes and the JVM parses them into a runtime class representation | A `Class` object and internal metadata exist |
| Verification | The JVM checks that the bytecode obeys the language's safety rules | Malformed or unsafe code is rejected |
| Preparation | Static fields are allocated and set to default values (`0`, `null`, `false`) | Memory for statics exists, but no code has run |
| Resolution | Symbolic references in the constant pool become direct references to classes, methods and fields | Calls and field accesses can go straight to their targets |
| Initialization | The static initializer (`<clinit>`) runs and static field initializers execute | The class is ready for use |
Verification, preparation and resolution together are called linking. The specification allows the JVM to be lazy about linking, and HotSpot is. It usually links a class just before initializing it, and it resolves each constant pool entry the first time the bytecode using it executes.
Loading and the class loader hierarchy
Loading is done by a class loader, an object that turns a class name into a class. A standard JVM has three loaders arranged in a delegation chain.
- The boot loader is built into the JVM. It loads the core modules such as
java.base. - The platform loader loads other JDK modules, such as
java.sql. - The application loader (also called the system loader) loads classes from the classpath and module path.
When the application loader is asked for a class, it first asks its parent, which asks its own parent. Only when the parents cannot supply the class does the application loader search the classpath itself. This parent-first delegation means a class is loaded once and java.lang.String always comes from the JDK, never from a JAR on your classpath.
The classpath search is a real cost. For a JAR, the loader looks up the entry in the central directory, inflates the compressed bytes, and defines the class. A long classpath means more JARs to probe for classes that live late in the list.
After the bytes arrive, the JVM parses them. It checks the class file format, builds the constant pool, and creates internal structures for the fields, methods and attributes. It also loads the superclass and all superinterfaces first, so one class can pull in a whole chain.
Loading is triggered lazily
Loading does not happen when the JVM starts. It happens when the bytecode first needs the class. The same is true of initialization, and the two are separate events. The following program shows the order in which they occur.
import java.lang.management.ManagementFactory;
public class LoadCount {
static class Lazy {
static {
System.out.println("Lazy is being initialized");
}
static void touch() {
System.out.println("Lazy.touch called");
}
}
public static void main(String[] args) {
System.out.println("main started");
Lazy.touch();
long loaded = ManagementFactory.getClassLoadingMXBean()
.getTotalLoadedClassCount();
System.out.println("Classes loaded so far: " + loaded);
}
}Compile and run it:
javac LoadCount.java
java LoadCountThe output prints main started before Lazy is being initialized, because Lazy is not touched until Lazy.touch() runs. The final count is typically several hundred, even though this program defines only two classes. Everything else comes from the JDK, including the management classes used to report the number.
Verification
Verification protects the JVM from bytecode that breaks the rules the Java language normally enforces. A hand-edited or malicious class file could pop from an empty stack, treat an int as an object reference, or jump into the middle of an instruction. The JVM refuses to run such code.
The verifier checks things such as:
- Every instruction operates on values of the right type.
- The operand stack never underflows or exceeds its declared depth.
- Branch targets land on instruction boundaries.
- Final classes and methods are not overridden.
- Local variables are assigned before they are read.
Modern class files (version 50 and later, Java 6 and up) carry a StackMapTable attribute that the compiler generates. It records the expected types at each branch target. The JVM then verifies in one linear pass and does not need to infer types iteratively. This is faster than the older approach, but it is still work proportional to the amount of bytecode.
By default, HotSpot does not verify classes from the boot loader, because the JDK itself is trusted. Classes from the application and platform loaders are verified. So application code and library JARs pay for verification on every run. This is why a large framework costs more at startup than the same amount of JDK code.
Preparation and resolution
Preparation allocates storage for static fields and gives them default values. Initializers like static int limit = 100; do not run here. They run later, in initialization.
Resolution deals with symbolic references. In a class file, a call such as list.add(x) is stored as a name: a class name, a method name and a descriptor. Before the call can run, the JVM must find the real method, check access rules, and replace the name with a direct pointer. Resolution can trigger more class loading, because resolving a reference to a class that is not loaded yet loads it.
HotSpot resolves lazily, one entry at a time, when the instruction first executes. That keeps unused paths cheap. It also means resolution work is scattered across the first seconds of the run, rather than collected into one measurable block.
Initialization
Initialization runs the class's static initializer, which contains the static field assignments and static { } blocks in source order. The JVM initializes a class when one of these first happens:
- An instance is created with
new. - A static method is called.
- A non-constant static field is read or written.
- A subclass is initialized.
- The class is the one holding
main.
The JVM guarantees that initialization runs once and is thread-safe. It takes a per-class lock, which is why circular static dependencies between classes can deadlock in concurrent code.
Initialization runs arbitrary code. It can read system properties, open files, start threads or register shutdown hooks. For that reason a cache cannot safely run it ahead of time and replay the effects. Static initializers keep running on every launch, and a cache can only reduce the work done before them.
Lambdas and generated classes
The example application in this tutorial uses String::toUpperCase and a stream pipeline. Lambdas and method references compile to invokedynamic instructions. The first time one executes, the JVM calls a bootstrap method in LambdaMetafactory, which generates a new hidden class at runtime to implement the functional interface. It then links the call site to it.
This is expensive on the first call. The JVM must run the bootstrap machinery, which itself loads many classes, and generate and define a class that exists in no .class file. A program with a handful of lambdas can spend a visible fraction of its startup on this. Because the classes are generated, a plain classpath scan cannot find them. They are one reason the AOT cache needs to observe a real run, rather than just reading JAR files.
Seeing the work with logging
You can watch loading with unified logging. The class+load tag prints one line per class, including where it came from.
java -Xlog:class+load:file=load.log LoadCount
grep -c "source: shared objects file" load.log
grep -c "source: jrt:" load.log
grep "LoadCount" load.logThe log lines look like this:
[0.014s][info][class,load] java.lang.Object source: shared objects file
[0.081s][info][class,load] LoadCount source: file:/home/user/The first count shows classes served from the JDK's default archive, which Chapter 3 covers. The second shows JDK classes that had to be read from the runtime image and parsed. To see the full cost, disable the default archive and compare:
time java -Xshare:off LoadCount
time java LoadCountWith -Xshare:off, every JDK class goes through the full load and verify path. The difference is a rough picture of how much work class data sharing already saves for JDK classes. The application classes and the lambda-generated classes are still handled the slow way, and that is the gap the AOT cache fills.
Common mistakes
- Assuming loading and initialization are the same event. A class can be loaded without being initialized, for example when it is only mentioned in a type check. A log line proves loading, not that the static initializer ran. Use
-Xlog:class+initto see initialization. - Blaming the JIT for all startup cost. The JIT compiler works in background threads. Early startup is dominated by class loading, verification and interpreting cold code.
- Counting only your own classes. Application classes are often a small minority of what a run loads. Check the log before deciding where time goes.
- Expecting verification to apply to JDK code. Boot loader classes skip verification by default, so the verification cost comes from your classpath.
- Expecting a cache to skip static initializers. The work saved is loading, verification and linking. Initialization still runs.
Exercise
A program loads 4,000 classes, of which 3,200 come from the JDK and 800 from application JARs. Which classes does HotSpot verify by default, and why do the application's JARs raise startup time more than their count suggests? Name one phase that stays on the critical path even after loading and linking are precomputed.
Show answer
HotSpot verifies classes from the platform and application loaders, so the 800 classes from the JARs are verified on every run, while the boot loader's JDK classes are trusted and skipped. Those JAR classes also cost more because they must be found by searching the classpath, inflated from the JAR and parsed, and they are not in the JDK's default archive. Initialization stays on the critical path, because static initializers can run arbitrary code and must execute on every launch.
Exercise
In the LoadCount program, why does "main started" print before "Lazy is being initialized", and which of the two events (loading or initialization) is triggered by the call to Lazy.touch()?
Show answer
The JVM loads and initializes a class only when the bytecode first needs it. Nothing touches Lazy until the call to Lazy.touch(), which is a static method call. That call triggers initialization, and loading happens just before it, so the static block prints after "main started".