Skip to content
Tutorials Center
My learning

Topics

Lesson 153 of 201 ยท JVM and Advanced Topics

JVM Architecture and Class Loading

How the JVM works inside - class loaders and delegation, loading, linking and initialization, the runtime data areas, bytecode you can read, and JIT tiers.

When you press Run, javac turns your source into bytecode, and the Java Virtual Machine turns that bytecode into a running program. You met this pipeline in How Java Works. This lesson opens the box: how the JVM finds and loads classes, what happens between "class loaded" and "class ready," where your data lives while the program runs, what bytecode really looks like, and how the JIT compiler makes hot code fast.

You don't need any of this to write a "Hello, world." You do need it the first time you see NoClassDefFoundError, a ClassCastException that says a class can't be cast to itself, a static initializer that runs at a surprising moment, or a benchmark that gets faster the longer it runs. Every example below runs on the same JVM our editor uses, so you can watch the machinery directly.

The big picture

The JVM is a specification, not one program. HotSpot (the JVM inside OpenJDK, Temurin, Oracle JDK and most others) is by far the most common implementation, and it is what this lesson describes when details differ. Every JVM has the same three major parts:

TEXT
   .class files / JARs / modules
              โ”‚
              โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚     Class loader subsystem    โ”‚  load โ†’ link (verify, prepare, resolve) โ†’ initialize
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                     Runtime data areas                     โ”‚
โ”‚  shared:      heap  ยท  method area (metaspace)             โ”‚
โ”‚  per thread:  JVM stack  ยท  PC register  ยท  native stack   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚       Execution engine        โ”‚ โ”€โ”€โ”€โ–ถ โ”‚  Native interface   โ”‚
โ”‚ interpreter ยท JIT ยท GC        โ”‚      โ”‚  (JNI, FFM API)     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  1. The class loader subsystem finds class files and turns them into runtime Class objects.
  2. The runtime data areas hold everything the program needs while it runs: objects, class metadata, and one stack per thread.
  3. The execution engine runs bytecode, first with an interpreter and then with compiled machine code, while the garbage collector reclaims memory (see Memory and Garbage Collection).

Class loaders

A class loader is an object that, given a class name, produces a Class. The JDK ships three built-in loaders, arranged as a chain of parents:

Loader Loads In Java
Bootstrap Core modules such as java.base (String, List, Thread) Written in native code; shows up as null
Platform Other Java SE and JDK modules, such as java.sql and java.net.http ClassLoader.getPlatformClassLoader()
Application (system) Your classes and libraries from the class path or module path ClassLoader.getSystemClassLoader()

Before Java 9, the middle loader was called the extension class loader and read JARs from a jre/lib/ext folder. That mechanism is gone; the platform loader replaced it when the JDK became modular.

Java Walking the class loader chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows one more loader than you might expect. Our editor runs your file with the source-file launcher (java Main.java), which compiles the code in memory and loads it with its own MemoryClassLoader. Its parent is the application loader, whose parent is the platform loader, whose parent is the bootstrap loader. In a normal project packaged as a JAR, Main would be loaded directly by the application loader. String reports null, which is how Java represents the bootstrap loader.

Parent delegation

When a loader is asked for a class, it follows the parent delegation model:

  1. If it has already loaded the class, it returns the cached Class.
  2. Otherwise it asks its parent first (recursively, up to the bootstrap loader).
  3. Only if the parent can't find the class does the loader search its own locations.

Delegation is a safety feature. If you put your own java/lang/String.class on the class path, the application loader never loads it, because the bootstrap loader answers first. Core classes can't be replaced by accident or by an attacker. (In the module system, packages are additionally mapped to exactly one module, which makes the rule even stricter.)

A class is its name plus its loader

At run time, a class's identity is the pair (fully qualified name, defining loader). Two loaders can each define a class called com.shop.Order, and the JVM treats them as two unrelated types. This is how application servers and plugin systems isolate applications that use different versions of the same library. It is also the source of the infamous message "com.shop.Order cannot be cast to com.shop.Order": the object came from one loader, and the variable's type from another.

The next example creates a class from raw bytes. It uses the Class-File API (java.lang.classfile, final in Java 24) to generate a tiny class called Answer with one method, then defines it in two separate loaders:

Java Same name, different loaders, different classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

defineClass is the protected method every loader ultimately uses to turn bytes into a Class. Real custom loaders override findClass(String name), read the bytes from a file, network or database, and call defineClass; delegation to the parent then happens automatically in loadClass. You rarely write one yourself, but frameworks, test runners, hot-reload tools and application servers all do.

Loading, linking and initialization

Getting a class ready happens in three phases, and the JVM is allowed to do them lazily: a class is typically loaded when it's first referenced and initialized only when it's first actively used.

  1. Loading. A loader finds the bytes and creates the Class object.
  2. Linking, in three steps:
    • Verification checks that the bytecode is well formed and type-safe: no jumping into the middle of an instruction, no treating an int as a reference, no stack overflow within a method. This is why a corrupted or malicious class file fails with VerifyError instead of crashing the JVM.
    • Preparation allocates static fields and sets them to default values (0, false, null).
    • Resolution replaces symbolic references ("method println in class java/io/PrintStream") with direct ones. HotSpot resolves each reference lazily, the first time an instruction uses it.
  3. Initialization runs the class's static initializer, a hidden method named <clinit> that javac builds from static field initializers and static { } blocks, in source order. Superclasses are initialized first.

Initialization happens exactly once, and is thread-safe: if two threads use a class at the same time, one runs <clinit> and the other waits. That guarantee is what makes the lazy-holder singleton in Creational Design Patterns work.

What triggers initialization

A class is initialized on its first active use: creating an instance, calling a static method, reading or writing a static field (except a compile-time constant), initializing a subclass, or reflection such as Class.forName("X"). Many things that mention a class do not initialize it:

Java When does a static initializer run?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look closely at each step:

  • Step 1 prints nothing extra, because VERSION is a constant variable (a static final primitive or String initialized with a constant expression). javac copies the value 3 straight into Main's bytecode, so Config isn't involved at all. LOADED_AT is not a constant, and reading it would initialize Config.
  • Steps 2 and 3 load Config without initializing it. An array type is a separate class created by the JVM, and the two-argument-false forName explicitly asks for no initialization.
  • Step 4 triggers <clinit>; step 5 doesn't, because it runs once per class per loader.
  • Step 6 initializes only Base. The field shared is declared in Base, so accessing it through Derived is still an access to Base.

Constants are copied into the classes that use them. If library A has public static final int LIMIT = 10; and your class reads A.LIMIT, your compiled class contains 10. Recompile A with LIMIT = 20 but not your class, and your code still sees 10. Use a static method or a non-constant field for values that may change between releases.

Class loading errors

When loading or linking fails, the JVM throws an Error rather than an exception. ClassNotFoundException is thrown when your code asks for a class by name (for example Class.forName) and no loader can find it. NoClassDefFoundError means a class that was present at compile time is missing at run time (or failed to initialize, as shown below). ClassFormatError means the bytes are not a valid class file, for instance a truncated or corrupted download. UnsupportedClassVersionError means the class was compiled for a newer Java version than the JVM running it. VerifyError means bytecode verification rejected the class during linking.

When initialization fails

If a static initializer throws, the JVM wraps the exception in ExceptionInInitializerError and marks the class as erroneous. It never retries: every later use throws NoClassDefFoundError, even though the class file is right there. This confuses many developers, because the second error message hides the real cause. Always scroll up in the log to the first error.

Java A failed static initializer poisons the class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first attempt shows the real problem (a NumberFormatException as the cause). The second attempt only says the class could not be initialized. Keep static initializers simple, and move anything that can fail (reading files, parsing configuration, connecting to services) into ordinary methods you can call, retry and test.

The runtime data areas

While your program runs, the JVM organizes memory into several areas. Some are shared by all threads; others exist once per thread.

Area Shared? Holds Error when full
Heap All threads Every object and array, including the Class objects themselves OutOfMemoryError: Java heap space
Method area (HotSpot: metaspace, native memory) All threads Per-class metadata: field and method info, bytecode, the runtime constant pool OutOfMemoryError: Metaspace
JVM stack One per thread A frame per active method call: local variables, the operand stack, a link to the class's constant pool StackOverflowError
PC register One per thread The address of the bytecode instruction the thread is executing โ€”
Native method stack One per thread Frames of native (C/C++) code called via JNI StackOverflowError

The code cache, where the JIT puts compiled machine code, is another native area. Before Java 8, class metadata lived in a fixed-size heap region called PermGen, which often ran out in application servers; metaspace grows as needed (you can cap it with -XX:MaxMetaspaceSize).

Each frame holds an array of local variable slots (parameters first, with this in slot 0 for instance methods) and an operand stack that bytecode instructions push to and pop from. A thread's stack has a fixed maximum size (-Xss), so the number of frames that fit depends on how big each frame is:

Java Measuring stack depth

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Your exact numbers depend on the JVM version, flags and whether the method was JIT-compiled (our editor gives the main thread an 8 MB stack with -Xss8m), but the pattern is always the same: bigger frames mean fewer of them, and a smaller stack holds fewer calls. Catching StackOverflowError is fine for a demo like this; in real code, fix the unbounded recursion instead (see Recursion).

Bytecode: what javac produces

Bytecode is a compact instruction set for a stack machine: instructions take their operands from the operand stack and push results back. The JDK's javap tool disassembles class files. For this method:

Java
static int square(int n) {
    return n * n;
}

javap -c Main.class prints:

TEXT
  static int square(int);
    Code:
       0: iload_0
       1: iload_0
       2: imul
       3: ireturn

Read it as: push local slot 0 (n) twice, multiply the top two values, return the int on top of the stack. The number before each instruction is its byte offset. The prefix tells you the type: i for int, l for long, d for double, a for references. Other tools you'll meet: javap -v for the constant pool and flags, javap -p to include private members.

javap isn't available inside our editor, but the Class-File API can read class files too. This program reads the bytes of its own nested record and prints a small javap-style listing:

Java A tiny javap written with the Class-File API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A few things stand out:

  • Class file version 69 means Java 25 (version 52 was Java 8; each release adds one). Running a class on an older JVM than it was compiled for fails with UnsupportedClassVersionError.
  • A record really is a class that extends java.lang.Record, and its accessor x() is an ordinary method that does getfield. See Records.
  • Math.abs is an invokestatic, and calling the record's own fields uses aload_0 (push this) followed by getfield.
  • String concatenation compiles to a single invokedynamic with makeConcatWithConstants. Since Java 9, the JVM decides at run time how to build the string. Lambdas also use invokedynamic, which is why they don't create an extra .class file per lambda.

The JVM has about 200 opcodes in five families: load/store (iload, astore), arithmetic (iadd, dmul), object operations (new, getfield, checkcast, instanceof), method calls (invokestatic, invokevirtual for normal instance methods, invokeinterface, invokespecial for constructors and super calls, invokedynamic), and control flow (if_icmpge, goto, tableswitch, athrow).

The execution engine: interpreter and JIT

HotSpot starts by interpreting bytecode, one instruction at a time. That starts fast but runs slowly. While it interprets, it counts how often each method is called and how often each loop runs. Hot code gets compiled to native machine code by the just-in-time (JIT) compiler, using what the profile revealed (which branches are taken, which concrete classes appear at a call site).

Modern HotSpot uses tiered compilation with two compilers:

Tier Runs as Purpose
0 Interpreter Everything starts here and is profiled
1โ€“3 C1 (client compiler) Fast compilation with few optimizations; tiers 2 and 3 keep collecting profile data
4 C2 (server compiler) Slow, aggressive compilation for the hottest code: inlining, escape analysis, loop unrolling, vectorization

The JIT makes speculative optimizations. If only one class has ever reached a virtual call, C2 may inline that method directly. If a new subclass later shows up, the JVM deoptimizes: it throws away the compiled code and falls back to the interpreter until it recompiles. A long-running loop inside one method can even be swapped to compiled code in the middle of executing it, called on-stack replacement (OSR).

You can watch the warm-up effect by timing the same work repeatedly:

Java Watching JIT warm-up

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first rounds run partly in the interpreter and are typically about twice as slow as the later ones, which run compiled code. You may also see an occasional spike: our sandbox gives the JVM a single CPU, so the JIT compiler and your code take turns, and the garbage collector can pause briefly too. Our editor also starts the JVM with -XX:TieredStopAtLevel=1, which stops at C1 so short programs start faster; on a server running C2, the final speed-up is larger. Printing checksum matters: if the result were never used, the JIT could legally delete the work, which is one reason hand-written benchmarks lie. The performance lesson shows how JMH handles warm-up and dead-code elimination properly.

Useful flags when you want to see the JIT at work on your own machine:

Terminal
java -XX:+PrintCompilation Main.java       # one line per compiled method, with its tier
java -Xint Main.java                       # interpreter only (very slow, for comparison)
java -Xlog:class+load Main.java            # log every class as it is loaded
java -Xlog:class+init=info Main.java       # log class initialization

Startup: CDS and the AOT cache

Starting a JVM means loading, verifying and linking thousands of JDK classes. Class Data Sharing (CDS) stores pre-parsed JDK classes in an archive that is memory-mapped at startup; it's on by default. Java 24 and 25 extend this into an ahead-of-time cache: you run your application once in a training run, and the JVM records the classes it loaded and linked (and, since Java 25, method profiles), so later runs start faster and warm up sooner:

Terminal
java -XX:AOTCacheOutput=app.aot -jar app.jar   # training run (Java 25)
java -XX:AOTCache=app.aot -jar app.jar         # production runs

GraalVM's Native Image goes further and compiles a whole application to a native executable ahead of time, trading some peak performance and dynamic features (like unrestricted reflection) for millisecond startup.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Class Limits has static final int MAX = 5; and a static { } block that prints a message. What happens when main in another class runs System.out.println(Limits.MAX); for the first time?

    MAX is a compile-time constant, so javac copies 5 into the calling class. Limits is never actively used, so its static initializer doesn't run.
  2. 2. A class's static initializer threw an exception the first time it ran. What does the second attempt to use the class throw?

    The first failure throws ExceptionInInitializerError and marks the class as erroneous. The JVM never retries, so later uses throw NoClassDefFoundError.
  3. 3. Two different class loaders each define a class named com.shop.Order from identical bytes. What is true?

    A runtime class is identified by its name plus its defining loader, so these are unrelated types, and casting between them throws ClassCastException.
  4. 4. Which statement about parent delegation is correct?

    Loaders delegate to their parent before searching themselves, which is why core classes can't be replaced from the class path. The platform loader replaced the extension loader, but delegation remains.
  5. 5. In the bytecode iload_0, iload_0, imul, ireturn, where do the operands of imul come from?

    The JVM is a stack machine. iload_0 pushes local slot 0 onto the operand stack, imul pops two ints and pushes their product, and ireturn returns the top value.

Summary

  • The JVM has a class loader subsystem, runtime data areas and an execution engine (interpreter, JIT compilers, garbage collector).
  • Built-in loaders form a chain: bootstrap (shown as null), platform, application. Loaders delegate to their parent first, which protects core classes.
  • A runtime class is identified by its name and its defining loader; the same name in two loaders gives two incompatible types.
  • Classes go through loading, linking (verification, preparation, resolution) and initialization. <clinit> runs once, thread-safely, on the first active use; constants, arrays and class literals don't trigger it.
  • A failed static initializer gives ExceptionInInitializerError once and NoClassDefFoundError forever after.
  • The heap and metaspace are shared; each thread has its own stack of frames (locals plus operand stack) and PC register.
  • Bytecode is a stack-machine instruction set you can read with javap -c; string concatenation and lambdas use invokedynamic.
  • HotSpot interprets first, then compiles hot code with C1 and C2 (tiered compilation), speculating and deoptimizing as needed. CDS and the AOT cache speed up startup.

Next: Annotations, where you'll see how @Override, @Deprecated and your own annotations attach metadata to code that tools and frameworks can read.