Lesson · JVM Internals
Class loading: three loaders, one parent chain, one lock
17 min readClass Loading
Before a class runs, something has to find its bytes, check them, prepare its storage and run its static initializers. That something is a class loader, and it works by name, at the moment of use. The three built-in loaders, parent delegation, the five initialization triggers, and the loader leaks that keep whole deployments alive.
A name the compiler cannot check
This compiles, whatever the string says:
// The name is resolved at run time, by a class loader, not by javac. Class<?> type = Class.forName("com.acme.FastPlugin"); Runnable plugin = (Runnable) type.getDeclaredConstructor().newInstance(); plugin.run();
- Nothing here is checked at build time. By the time javac sees the plugin name it is data, so a typo is a run-time failure and the loader decides whether the name resolves at all.
- Reflection is the visible version of a mechanism every class uses. An ordinary
new Profile(...), a static call, a static field read: each one resolves through a loader. Reflection only lets you start the request yourself, by name, at a moment you chose.
Classes arrive by name, on demand. A VM may read class files earlier than the use that needs them, but it may never load later than that use. There is no startup inventory of a program's classes.
Three built-in loaders, one question each
A standard JDK ships three loaders. Each answers the same question, do I know a class with this name, and they differ in where they look and in how close to the machine they sit.
| Loader | Written in | Looks in | How you reach it |
|---|---|---|---|
| Bootstrap | native code inside the VM | the core runtime modules, java.base first | String.class.getClassLoader() returns null: it is not a Java object |
| Platform | Java | the platform modules (the former extension directory became modules in Java 9) | ClassLoader.getPlatformClassLoader() |
| Application, also called the system loader | Java | the class path and module path of your program | ClassLoader.getSystemClassLoader() |
- Bootstrap first, platform next, application last. That order is the chain; a request enters at the loader that needs the class and leaves through the same door.
- Parent means loader, not superclass. The link is set when a loader is constructed. A custom loader usually adopts
getSystemClassLoader()as its parent so it can still see your application classes. - The application loader is the one your code meets first. It loads the entries you put on the class path, and it is the loader behind ordinary
newexpressions in a plain program.
The three loaders are a chain, not a menu. Which loader ends up owning a class decides who else can see it, and the answer is always printable: obj.getClass().getClassLoader().
Class loading · the chain and the life cycle
one name, one loader: ask upward first, then run the phases
The parent chain
A class already defined by the asking loader is returned immediately. A class an ancestor owns is answered by the ancestor, which is how a name the parent can resolve stays the parent. Only when every ancestor declines does the loader search its own sources, in findClass.
The phases, in order
1 Loading
bytes become a Class object owned by the loader that defined it.
2 Verification
type checks over the bytecode, driven by the StackMapTable since Java 7.
3 Preparation
static storage allocated and filled with defaults. No source code runs.
4 Resolution
symbolic references become direct ones. Allowed to be lazy, so it can trail behind use.
5 Initialization
<clinit> runs: static initializers and assignments, textual order, superclass first.
Initialization runs on first active use
Anything else, declaring a reference or reading a compile-time constant, initializes nothing.
Parent delegation: ask upward first
loadClass is the public entry point, and the default implementation runs the same three steps in every loader: return the class if this loader already defined it; otherwise ask the parent; only if the parent cannot answer, search this loader's own sources through findClass.
That order is parent delegation, and its guarantee is exact: a name an ancestor can resolve is resolved by the ancestor. Put a file called java/lang/String.class on your class path and the application loader still hands you the bootstrap loader's String, because the bootstrap loader answers first.
new Profile(...)reaches the application loader as a request forcom.acme.Profile.- The application loader checks the classes it already defined: not there. It asks its parent, the platform loader.
- The platform loader checks itself, finds nothing, and asks its parent the bootstrap loader, which searches the core modules and reports that the name is not its own.
- The refusal travels back down: the platform loader searches platform modules, finds nothing, and only then does the application loader search the class path, find Profile.class, and define the class.
Ask the parent first: that is why java.lang stays yours. Two clarifications, because this is where diagrams overclaim. Delegation is lookup order, not a sandbox: it guarantees that a name the parent can resolve is the parent's class, and it does not restrict what code on the class path may do. And a loader that adds a new source of classes overrides findClass, not loadClass, because loadClass is where the parent-first rule lives.
Loading, linking, initialization
One satisfied request runs three phases in order, and each has its own family of failures. Only the last phase runs code you wrote.
| Phase | What the JVM does | What fails here |
|---|---|---|
| Loading | find the bytes and define a Class object owned by that loader | ClassNotFoundException on your own lookup, NoClassDefFoundError when the program needs a definition that cannot be resolved |
| Linking: verification | structural and type checks over the bytecode; since Java 7 the verifier is a type-checking pass over the StackMapTable the compiler emitted | VerifyError |
| Linking: preparation | allocate static storage and fill it with defaults (0, false, null); no source code runs | an allocation failure, so OutOfMemoryError |
| Linking: resolution | turn symbolic constant-pool references into direct ones; the specification allows this to be lazy, so it can trail behind the first uses | NoSuchMethodError, NoSuchFieldError, IllegalAccessError, thrown at the use that needs the reference |
| Initialization | run <clinit>: static initializers and static field assignments in textual order, superclass first, once per class | ExceptionInInitializerError, or a hang |
- Preparation writes defaults; initialization runs code. After preparation,
static int limit;is 0 andstatic int limit = readConfig();is still 0. The read happens in <clinit>, in the last phase. - Resolution is allowed to be lazy, which is why a linkage error can appear on the ten-thousandth call instead of at startup. The order the specification does fix: completely loaded, verified and prepared before initialization.
- Verification is a real type check, not a formality. It is what makes a class file from disk safe to execute, and why a hand-edited .class dies with VerifyError instead of corrupting the VM.
Three phases, three error families. The phase named in an error tells you what to inspect: visibility for loading, the artifact for linking, your own static code for initialization.
One request · com.acme.Profile
class path · module path
platform modules
core modules, java.base · native
static fields: not allocated yet
Execution reaches new Profile("ada"). No loader has defined com.acme.Profile yet, so a load request starts at the application loader, the one that loaded the calling class.
When initialization happens: the five triggers
A class is initialized on first active use, and JLS 12.4.1 defines exactly what counts:
| Active use | Example |
|---|---|
| an instance of the class is created | new Profile() |
| a static method declared by the class is invoked | Profile.load() |
| a non-constant static field declared by the class is read or assigned | Profile.cache (a compile-time constant is inlined by javac and triggers nothing) |
| a reflective operation performs one of the above | Class.forName(name), Method.invoke on a static method, Field.set on a static field |
| a subclass is initialized | initializing a class also initializes its superclasses and any superinterfaces that declare default methods |
- The declaring class is the one initialized. Reading
Sub.taxiwhere taxi is declared in Super initializes Super; Sub stays uninitialized. Use the declaration site, not the expression. - The default-method case is a real trigger, and it can be synthetic. A compiler-generated default method counts too, so an interface can be initialized for reasons its source does not show. Initializing an interface does not initialize its own superinterfaces.
- forName versus loadClass:
Class.forName(name)isforName(name, true, callerLoader)and initializes;Class.forName(name, false, loader)loads and links only;loader.loadClass(name)never initializes. Static setup that must run cannot hide behind loadClass. - Merely naming a type is not a trigger. Declaring a reference (
Profile p = null;) and reading a constant (Profile.LIMIT) initialize nothing.
Load is not initialize. loadClass hands you a Class object you can inspect: getDeclaredMethods, isInstance, type checks. Only an active use runs <clinit>, and the triggers in the table are the complete list.
One thread runs <clinit>, everyone else waits
Initialization is guarded by a lock unique to each class (JLS 12.4.2). The first thread to arrive runs the initializer; any other thread that requests the same class blocks until the first finishes. A request from the thread that is already initializing the class is allowed to proceed, and that recursion rule is exactly how a cycle can hang: two threads, each initializing a class whose initializer waits on the other. No exception, no output, two threads parked in class initialization. Nothing is broken in the JVM; the code asked for a cycle it cannot unroll.
- Once per loader: a successful <clinit> never runs twice, and the VM may drop the initialization checks from the code path afterwards.
- Failure is cached: an initializer that throws a non-Error is wrapped in ExceptionInInitializerError; the class is marked erroneous, and every later attempt throws NoClassDefFoundError.
- Textual order: static field assignments and static blocks run in source order, and the compiler restricts forward references so most accidental cycles fail at build time instead.
- Superclass first: initializing a class initializes what it extends, plus default-method superinterfaces, before its own initializer runs.
A class initializes once, under a lock: make <clinit> boring. Assignments, maybe a lookup. Anything that starts threads, reads files, or calls back into your own class belongs in an explicit init method you call, where a cycle is visible instead of a silent hang.
What keeps a loader alive
A loader keeps every class it defined, every Class object knows its loader, and every class keeps its static fields reachable. Read that chain backwards and the consequence is severe: one reachable object from a loader pins the loader, and with it every class that loader ever defined.
The classic shape is a redeploy leak: deploy, undeploy, deploy again, and metaspace grows cycle after cycle while the heap looks flat. The old loader is still reachable, usually through one of these:
- A ThreadLocal on a pooled thread outlives the deployment, and its value holds classes from the loader you wanted gone.
- A JDBC driver registered with DriverManager sits in a static JDK-side registry while the driver instance belongs to your loader.
- A static field, cache or thread that the JDK or a shared loader pins. Reachability does not care how small the object is; a single entry is enough to keep thousands of classes.
Class unloading is a loader question, not a class question. JLS 12.7: a class can be unloaded only when its defining loader is reclaimable, and classes loaded by the bootstrap loader never unload. To free a deployment's classes, make its loader unreachable, which in practice means untangling its threads, registries and caches.
Reading a loading problem
Five moves, in order:
- Identify the loader first: print
obj.getClass().getClassLoader(), or read the loader named in the error. Web apps, plugins and test harnesses are loader stories before they are class path stories. - Check visibility before existence. Parent delegation means a class visible to a child may be invisible to a parent, so the jar being on the class path does not answer whether this loader can see it.
- Read the error family. ClassNotFoundException is a failed lookup; NoClassDefFoundError is a definition the program needed and could not resolve or initialize; ExceptionInInitializerError means the class was found and its static code threw, once.
- For initialization surprises, name the trigger: instance creation, a static method, a non-constant static field, reflection, or a subclass. Then check which class declares the member that was touched.
- For a hang, look for a class cycle across threads: two <clinit>s waiting on each other look exactly like a deadlock in a thread dump, and are diagnosed the same way.
Find the loader before you touch the class path. Most loading mysteries are visibility stories, not missing jars.
Two loaders, two different classes
The JVM identifies a class by its name and its defining loader, not by name alone. If two loaders both define com.acme.Plugin, you get two distinct Class objects: a cast between them fails with ClassCastException, instanceof is false across the boundary, == never matches, and the static state is separate. Application servers, plugin systems and hot-reload frameworks all live on this fact, and it is the mechanism behind most it-works-in-the-test, fails-in-the-server loading bugs.
Interview angles
Name the three built-in class loaders and what each loads.+
Bootstrap loads the core runtime modules, java.base first, and is native code with no Java object behind it, so String.class.getClassLoader() is null. Platform loads the platform modules beyond the base and replaced the extension loader in Java 9. The application loader, also called the system loader, loads the class path and module path of your program.
How does parent delegation work, and what does it buy?+
The default loadClass returns an already-defined class, then asks the parent, then searches its own sources via findClass. Core classes always win their own names, so a jar on the class path cannot shadow java.lang.String, and core types stay shared across loaders.
Common misconception: That delegation is a security sandbox. It is a lookup order: it decides who gets to answer for a name the ancestors can resolve. It does not restrict what code on the class path may do once it runs.
Follow-up: If you write a loader with a new source of classes, which method do you override, and why?
What are the phases a class goes through before first use?+
Loading, linking and initialization. Linking splits into verification (bytecode safety and type checks, driven by the StackMapTable since Java 7), preparation (static storage allocated with default values) and resolution (symbolic references become direct, allowed to be lazy).
Only initialization runs your code. Preparation is the step that explains why a static field is 0 before its initializer has run: the storage exists, the defaults are written, and the assignment waits for <clinit>.
Common misconception: That linking and initialization are one step. They are separate phases with separate failure modes: VerifyError for verification, ExceptionInInitializerError for initialization.
When is a class initialized?+
On first active use, per JLS 12.4.1: an instance is created, a static method declared by the class is invoked, a non-constant static field declared by the class is read or written, or reflection performs one of those. Initializing a subclass also initializes its superclasses and default-method superinterfaces.
A reference to a field initializes the class that declares it, not the class named in the expression: Sub.taxi where taxi lives in Super initializes Super only. Compile-time constants are inlined by javac and trigger nothing.
Common misconception: That loading a class initializes it. loadClass loads and links; forName(name) initializes; forName(name, false, loader) deliberately does not.
What happens if two threads ask for the same class at the same moment?+
One thread takes the class initialization lock and runs <clinit>; the other blocks until it finishes, then proceeds. Initialization happens once, and a failure is cached: the class is marked erroneous and later attempts throw NoClassDefFoundError.
The recursion rule is what makes cycles hang instead of failing fast: a request from the thread already initializing the class is allowed through, so two threads can each wait on a class the other is initializing, with no exception and no output.
static class A { static { new B(); } // A's initializer touches B } static class B { static { new A(); } // B's initializer touches A } // Two threads started at the same moment: // t1: new A() holds A's init lock, then blocks asking for B // t2: new B() holds B's init lock, then blocks asking for A // // One thread alone would not hang: while initializing A, the same thread // may touch A again (the recursion rule). Two threads, two locks: hang. // In a thread dump both sit in class initialization, waiting on each other.
Follow-up: How would you recognise that hang in a thread dump?
What is a class loader leak, and how does it show up?+
Any reachable reference from outside the loader keeps it alive, and the loader keeps every class it defined, with metadata in metaspace and statics intact. Repeat that across redeploys and metaspace grows while the heap stays flat, ending in OutOfMemoryError: Metaspace.
Class unloading is only possible when the defining loader is reclaimable (JLS 12.7), so unload bugs are really reachability bugs. Common carriers: a ThreadLocal or executor on a pooled thread, a JDBC driver still registered with DriverManager, a static cache on a class the JDK or a shared loader pins.
Common misconception: That calling a cleanup method unloads classes. Unloading is the collector's decision; your job is to remove the paths that keep the loader reachable.
Follow-up: Which objects would you inspect first in a heap dump from a redeployed application server?