Class loading
The JVM does not load every class at startup. It loads each one the first time it is needed, through a chain of class loaders that decides where the bytes come from, and initializes it at a precisely defined moment. This page explains loading, linking and initialization, prints the loader chain, shows when initialization happens and what a failed initializer leaves behind, defines a class from bytes in a child-first loader, runs the isolation traps that plugin systems hit, and unloads a class.
Contents
Loading, linking and initialization
A class goes through three phases before its code can run, described in chapter 5 of the JVM specification and section 12.4 of the language specification:
- Loading: a class loader finds the bytes of the class file, from a JAR, a directory, the network or memory, and the JVM turns them into a
object.Class - Linking: the bytecode is verified to be safe, static fields are prepared with default values (0, null), and symbolic references to other classes are resolved, usually lazily when first used.
- Initialization: the class's static initializers and static field assignments run, exactly once, under a lock, the first time the class is actively used: creating an instance, calling a static method, or reading or writing a static field that is not a compile-time constant.
Which loader loads a class matters, because a class's identity is its name plus its defining loader. Two loaders can load classes with the same name from the same bytes, and the JVM treats them as unrelated types. Loaders form a tree. By default each one delegates to its parent first and only looks for the class itself if the parent cannot find it, so core classes such as java.lang.String
| Loader | Loads | Visible as | Notes |
|---|---|---|---|
| Bootstrap | java.base | null | Built into the JVM, not a Java object |
| Platform | Other JDK modules, such as java.sql | ClassLoader.getPlatformClassLoader() | Replaced the extension loader in Java 9 (JEP 261) |
| Application (system) | The class path and module path | ClassLoader.getSystemClassLoader() | Loads your code |
URLClassLoader | JARs and directories you give it | Your own instance | Plugins, isolated components (Java 1.2) |
Custom subclass of ClassLoader | Anything, via defineClass | Your own instance | Generated code, encrypted classes, child-first loading |
The examples ran on JDK 21.
The loader hierarchy
Three classes from three places, a core class, a JDK module class and the program's own class, show which loader defines each, and the program then walks up the parent chain.
import java.sql.Connection;
public class LoaderTree {
static void describe(Class<?> c) {
ClassLoader l = c.getClassLoader();
String loader = l == null ? "bootstrap (null)" : l.getName();
System.out.printf("%-26s loaded by %s%n", c.getName(), loader);
}
public static void main(String[] args) {
describe(String.class); // java.base: bootstrap loader
describe(Connection.class); // java.sql: platform loader
describe(LoaderTree.class); // your code: application loader
System.out.println("parent chain of the application loader:");
ClassLoader l = LoaderTree.class.getClassLoader();
while (l != null) {
System.out.println(" " + l.getName() + " (" + l.getClass().getSimpleName() + ")");
l = l.getParent();
}
System.out.println(" bootstrap (shown as null)");
}
}
Output:
java.lang.String loaded by bootstrap (null)
java.sql.Connection loaded by platform
LoaderTree loaded by app
parent chain of the application loader:
app (AppClassLoader)
platform (PlatformClassLoader)
bootstrap (shown as null)
reports aString loader: the bootstrap loader is implemented inside the JVM and has no Java object. Code that callsnull on a core class therefore fails withgetClassLoader().getResource(...) .NullPointerException lives in thejava.sql.Connection module, which the platform loader handles. Before Java 9 it came from the bootstrap loader along with everything injava.sql .rt.jar- The program's own class came from the application loader, whose parent is the platform loader, whose parent is the bootstrap loader. A request for
made to the application loader is passed up the chain and answered at the top.String
When a class is initialized
A class's static initializer prints a line, which shows exactly when it runs. The program touches the class in four ways that look similar but are treated differently.
public class LazyInit {
static class Heavy {
static {
System.out.println(" Heavy initialized");
}
static final int CONSTANT = 42; // compile-time constant: inlined, no init
static int counter = 1; // reading this triggers initialization
}
public static void main(String[] args) throws Exception {
System.out.println("1. reading a constant: " + Heavy.CONSTANT);
System.out.println("2. getting the Class object without initializing:");
Class<?> c = Class.forName("LazyInit$Heavy", false, LazyInit.class.getClassLoader());
System.out.println(" got " + c.getSimpleName());
System.out.println("3. reading a static field:");
System.out.println(" counter = " + Heavy.counter);
System.out.println("4. again, no second initialization: counter = " + Heavy.counter);
}
}
Output:
1. reading a constant: 42
2. getting the Class object without initializing:
got Heavy
3. reading a static field:
Heavy initialized
counter = 1
4. again, no second initialization: counter = 1
- Reading
did not initializeCONSTANT . AHeavy primitive or string with a constant value is a compile-time constant, andstatic final copied the value 42 intojavac 's bytecode. Changing the constant later without recompiling the classes that use it leaves them with the old value.LazyInit loaded the class without initializing it. The one-argumentClass.forName(name, false, loader) initializes, which is why old JDBC code used it to register drivers.Class.forName(name)- Reading the non-constant
triggered the initializer, once. The second read did nothing: initialization happens exactly once per class and loader, and the JVM's lock makes it thread-safe, which is what the lazy holder idiom relies on.counter
Failed initializers, superclasses and interfaces
A configuration class whose initializer reads a system property that is not set is the classic way to break a class permanently. The program also checks the initialization order of a class hierarchy and of an interface.
public class InitFailure {
static class Config {
static final String URL = System.getProperty("db.url").trim(); // NPE: property unset
}
static class Base {
static {
System.out.println(" Base initialized");
}
}
static class Derived extends Base {
static {
System.out.println(" Derived initialized");
}
static void touch() {
}
}
interface Limits {
int MAX = logged(" Limits initialized", 10); // not a compile-time constant
}
static class Impl implements Limits {
}
static int logged(String message, int value) {
System.out.println(message);
return value;
}
public static void main(String[] args) {
// 1. A failing static initializer: first ExceptionInInitializerError ...
try {
System.out.println(Config.URL);
} catch (ExceptionInInitializerError e) {
System.out.println("1st use: ExceptionInInitializerError, cause "
+ e.getCause().getClass().getSimpleName());
}
// ... and every later use fails with NoClassDefFoundError
try {
System.out.println(Config.URL);
} catch (NoClassDefFoundError e) {
System.out.println("2nd use: NoClassDefFoundError: " + e.getMessage());
}
// 2. Initializing a class first initializes its superclass
System.out.println("calling Derived.touch():");
Derived.touch();
// 3. ...but not the interfaces it implements
System.out.println("new Impl():");
new Impl();
System.out.println("reading Limits.MAX:");
System.out.println(" MAX = " + Limits.MAX);
}
}
Output:
1st use: ExceptionInInitializerError, cause NullPointerException
2nd use: NoClassDefFoundError: Could not initialize class InitFailure$Config
calling Derived.touch():
Base initialized
Derived initialized
new Impl():
reading Limits.MAX:
Limits initialized
MAX = 10
- The first use of
threwConfig , with the real cause, aExceptionInInitializerError , inside it. The second use threwNullPointerException , without that cause. The JVM marks the class as erroneous after a failed initialization and never retries. In production logs the second error is often the only one people see, so search for the firstNoClassDefFoundError: Could not initialize class InitFailure$Config .ExceptionInInitializerError - Calling a static method of
initializedDerived first, thenBase : a class's superclasses are always initialized before it.Derived - Creating an
did not initialize the interfaceImpl . An interface is initialized only when one of its own non-constant fields is used, or, if it has default methods, when an implementing class is initialized (JLS 12.4.1).Limits
Defining a class from bytes in a child-first loader
Every class loader eventually calls defineClassCounterloadClass
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.Map;
public class BytesLoader {
// A class the application has: we will load a second, isolated copy of it
public static class Counter {
static int created;
public Counter() {
created++;
}
public static int created() {
return created;
}
}
// Defines classes from byte arrays, and tries its own classes BEFORE asking the parent
static class ChildFirstLoader extends ClassLoader {
private final Map<String, byte[]> classes;
ChildFirstLoader(String name, Map<String, byte[]> classes, ClassLoader parent) {
super(name, parent);
this.classes = classes;
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> c = findLoadedClass(name);
if (c == null && classes.containsKey(name)) {
byte[] b = classes.get(name);
c = defineClass(name, b, 0, b.length); // child first
}
if (c == null) {
return super.loadClass(name, resolve); // normal parent delegation
}
return c;
}
}
}
public static void main(String[] args) throws Exception {
String name = Counter.class.getName();
byte[] bytes;
try (InputStream in = BytesLoader.class.getResourceAsStream("BytesLoader$Counter.class")) {
bytes = in.readAllBytes();
}
System.out.println("class file bytes: " + bytes.length + ", magic "
+ String.format("%02X%02X%02X%02X", bytes[0], bytes[1], bytes[2], bytes[3]));
new Counter();
new Counter();
ChildFirstLoader loader = new ChildFirstLoader("isolated", Map.of(name, bytes),
BytesLoader.class.getClassLoader());
Class<?> copy = loader.loadClass(name);
copy.getConstructor().newInstance();
System.out.println("app Counter created " + Counter.created()
+ ", isolated copy created " + copy.getMethod("created").invoke(null)
+ " (separate static fields)");
System.out.println("copy's loader: " + copy.getClassLoader().getName()
+ ", same Class as app's: " + (copy == Counter.class));
// A class can be unloaded once its loader and all its objects are unreachable
WeakReference<Class<?>> ref = new WeakReference<>(copy);
copy = null;
loader = null;
for (int i = 0; i < 5 && ref.get() != null; i++) {
System.gc();
Thread.sleep(50);
}
System.out.println("isolated Counter class unloaded after GC: " + (ref.get() == null));
}
}
Output:
class file bytes: 377, magic CAFEBABE
app Counter created 2, isolated copy created 1 (separate static fields)
copy's loader: isolated, same Class as app's: false
isolated Counter class unloaded after GC: true
- The class file is 377 bytes and starts with the magic number
, as every class file does.CAFEBABE - The application's
had created 2 objects and the isolated copy 1: the two classes have separate static fields, because to the JVM they are different classes that happen to share a name and bytes.Counter - Child-first loading is how servlet containers let each web application use its own version of a library that the server also contains. It must still delegate
classes to the parent; the JVM refuses to define classes in thejava.* packages from any loader other than the built-in ones.java - Once the program dropped every reference to the loader and the class, the garbage collector unloaded the class: the weak reference was cleared. Classes are unloaded only together with their loader, and classes of the three built-in loaders are never unloaded. A single leftover reference, for example in a static cache or a
, keeps the whole loader and all its classes alive, which is the usual cause of "Metaspace" errors after repeated redeployments.ThreadLocal
Isolation traps in plugin systems
A plugin compiled at run time into a temporary directory is loaded by two separate URLClassLoaderSupplier<String>
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.function.Supplier;
import java.util.spi.ToolProvider;
public class IsolationTraps {
// A plugin that implements an interface the application also knows: Supplier<String>
static final String PLUGIN = """
public class Greeter implements java.util.function.Supplier<String> {
public String get() {
return "hi from " + getClass().getClassLoader().getName();
}
}
""";
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("plugin");
Files.writeString(dir.resolve("Greeter.java"), PLUGIN);
ToolProvider.findFirst("javac").orElseThrow().run(System.out, System.err,
"-d", dir.toString(), dir.resolve("Greeter.java").toString());
URL[] path = {dir.toUri().toURL()};
ClassLoader app = IsolationTraps.class.getClassLoader();
try (URLClassLoader a = new URLClassLoader("loader-A", path, app);
URLClassLoader b = new URLClassLoader("loader-B", path, app)) {
Object fromA = a.loadClass("Greeter").getDeclaredConstructor().newInstance();
Class<?> typeB = b.loadClass("Greeter");
// 1. Talking through a shared interface works: Supplier comes from the JDK
@SuppressWarnings("unchecked")
Supplier<String> s = (Supplier<String>) fromA;
System.out.println("1. via shared interface: " + s.get());
// 2. Casting to the "same" class from another loader fails
try {
typeB.cast(fromA);
} catch (ClassCastException e) {
System.out.println("2. " + e.getMessage());
}
// 3. The defining loader is part of a class's identity
System.out.println("3. A's Greeter == B's Greeter: " + (fromA.getClass() == typeB)
+ "; both delegate Supplier to the same loader: "
+ (a.loadClass("java.util.function.Supplier")
== b.loadClass("java.util.function.Supplier")));
}
try (var files = Files.walk(dir)) {
files.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
}
}
}
Output:
1. via shared interface: hi from loader-A
2. Cannot cast Greeter to Greeter
3. A's Greeter == B's Greeter: false; both delegate Supplier to the same loader: true
- Calling the plugin through
worked. Both loaders delegatedSupplier to the bootstrap loader, so the application and the plugin share that one interface.java.util.function.Supplier - Casting loader A's
object to loader B'sGreeter class failed with the confusing message "Cannot cast Greeter to Greeter". The two types have the same name but different defining loaders. The same error appears when a class is accidentally present both in a plugin JAR and on the application class path.Greeter - The two
classes are not the sameGreeter object, whileClass resolved to the sameSupplier through both loaders.Class
The design rule for plugins: put the shared API (interfaces and data types) in a loader that is the parent of every plugin loader, keep each plugin's implementation in its own child loader, and talk only through the API types. Thread.currentThread().getContextClassLoader()
Diagnosing class loading
Most class loading problems show up as one of a few errors, and the JVM can log every load as it happens.
| Error | Usual cause |
|---|---|
ClassNotFoundException | A loader was asked for a class by name (Class.forNameloadClass |
NoClassDefFoundError | A class was present at compile time but is missing at run time, or its initialization failed earlier |
ExceptionInInitializerError | A static initializer threw; the cause holds the real exception |
ClassCastException: X cannot be cast to X | The same class loaded by two different loaders |
LinkageError: loader constraint violation | Two loaders disagree about which class a shared signature refers to |
UnsupportedClassVersionError | The class was compiled for a newer Java version than the running JVM |
OutOfMemoryError: Metaspace | Loaders that are never released, for example after redeployments |
java -Xlog:class+load=info -cp app.jar Main-Xlog:class+unloadjcmd PID VM.classloaders
Choosing a loading approach
| Need | Use |
|---|---|
| Load a class by name without running its initializer | Class.forName(name, false, loader) |
| Load plugins from JAR files | URLClassLoader |
| Let a plugin override library versions | A child-first loader that still delegates java.* |
| Define generated bytecode | MethodHandles.Lookup.defineHiddenClassdefineClass |
| Unload plugins | Close the loader and drop every reference to it and its objects |
| Find out where a class came from | -Xlog:class+loadgetProtectionDomain().getCodeSource() |
See also