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:

  1. 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 Class object.
  2. 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.
  3. 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 always come from the same place.

The built-in class loaders since Java 9
LoaderLoadsVisible asNotes
Bootstrapjava.base and other core modulesnullBuilt into the JVM, not a Java object
PlatformOther JDK modules, such as java.sqlClassLoader.getPlatformClassLoader()Replaced the extension loader in Java 9 (JEP 261)
Application (system)The class path and module pathClassLoader.getSystemClassLoader()Loads your code
URLClassLoaderJARs and directories you give itYour own instancePlugins, isolated components (Java 1.2)
Custom subclass of ClassLoaderAnything, via defineClassYour own instanceGenerated 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.

Java
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:

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)
  • String reports a null loader: the bootstrap loader is implemented inside the JVM and has no Java object. Code that calls getClassLoader().getResource(...) on a core class therefore fails with NullPointerException.
  • java.sql.Connection lives in the java.sql module, which the platform loader handles. Before Java 9 it came from the bootstrap loader along with everything in 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 String made to the application loader is passed up the chain and answered at the top.

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.

Java
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:

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 CONSTANT did not initialize Heavy. A static final primitive or string with a constant value is a compile-time constant, and javac copied the value 42 into LazyInit's bytecode. Changing the constant later without recompiling the classes that use it leaves them with the old value.
  • Class.forName(name, false, loader) loaded the class without initializing it. The one-argument Class.forName(name) initializes, which is why old JDBC code used it to register drivers.
  • Reading the non-constant counter 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.

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.

Java
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:

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 Config threw ExceptionInInitializerError, with the real cause, a NullPointerException, inside it. The second use threw NoClassDefFoundError: Could not initialize class InitFailure$Config, 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 first ExceptionInInitializerError.
  • Calling a static method of Derived initialized Base first, then Derived: a class's superclasses are always initialized before it.
  • Creating an Impl did not initialize the interface Limits. 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).

Defining a class from bytes in a child-first loader

Every class loader eventually calls defineClass with the bytes of a class file. The custom loader below gets the bytes of the program's own Counter class and defines a second copy of it. To do that it overrides loadClass to try its own classes before asking its parent, the opposite of normal delegation.

Java
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:

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 CAFEBABE, as every class file does.
  • The application's Counter 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.
  • 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 java.* classes to the parent; the JVM refuses to define classes in the java packages from any loader other than the built-in ones.
  • 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 ThreadLocal, keeps the whole loader and all its classes alive, which is the usual cause of "Metaspace" errors after repeated redeployments.

Isolation traps in plugin systems

A plugin compiled at run time into a temporary directory is loaded by two separate URLClassLoaders. It implements Supplier<String>, an interface the application also knows, which is the key to talking to it safely.

Java
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:

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
  1. Calling the plugin through Supplier worked. Both loaders delegated java.util.function.Supplier to the bootstrap loader, so the application and the plugin share that one interface.
  2. Casting loader A's Greeter object to loader B's Greeter 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.
  3. The two Greeter classes are not the same Class object, while Supplier resolved to the same Class through both loaders.

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. ServiceLoader builds on exactly this arrangement. Frameworks that need the "current" loader of the calling code, rather than their own, use 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.

Class loading errors and their usual causes
ErrorUsual cause
ClassNotFoundExceptionA loader was asked for a class by name (Class.forName, loadClass) and it is not on its path
NoClassDefFoundErrorA class was present at compile time but is missing at run time, or its initialization failed earlier
ExceptionInInitializerErrorA static initializer threw; the cause holds the real exception
ClassCastException: X cannot be cast to XThe same class loaded by two different loaders
LinkageError: loader constraint violationTwo loaders disagree about which class a shared signature refers to
UnsupportedClassVersionErrorThe class was compiled for a newer Java version than the running JVM
OutOfMemoryError: MetaspaceLoaders that are never released, for example after redeployments

java -Xlog:class+load=info -cp app.jar Main prints one line per loaded class with its source, which answers "where did this class come from?". -Xlog:class+unload logs unloading, and jcmd PID VM.classloaders prints the loader tree of a running JVM.

Choosing a loading approach

Class loading recipes
NeedUse
Load a class by name without running its initializerClass.forName(name, false, loader)
Load plugins from JAR filesURLClassLoader with the application loader as parent, plus ServiceLoader
Let a plugin override library versionsA child-first loader that still delegates java.*
Define generated bytecodeMethodHandles.Lookup.defineHiddenClass (Java 15), or a custom loader's defineClass
Unload pluginsClose the loader and drop every reference to it and its objects
Find out where a class came from-Xlog:class+load or getProtectionDomain().getCodeSource()

See also reflection for working with loaded classes, bytecode instrumentation for changing classes as they load, and modules for how the module system layers on top of loaders.