Skip to content

Path 1 · lesson 1 of 4

Foundation26 minJava 21 (OpenJDK 21.0.13, HotSpot) · Spring Boot 3.5

JVM architecture, class loading and bytecode execution

How a .class file becomes running code: loading, linking, initialisation, the three class loaders, and how to diagnose missing classes, loader leaks and slow startup.

What you will learn

  • Name the three parts of the JVM and say what each one does with a class
  • Describe loading, linking and initialisation, and say what triggers each
  • Explain parent delegation and why the same class name can exist twice in one JVM
  • Tell ClassNotFoundException from NoClassDefFoundError and find the real cause of each
  • Find a class loader leak with jcmd VM.classloader_stats
  • Read a class loading log and javap -c output

Before you start

Nothing: you can start here.

The concept

The Java compiler does not produce machine code. It produces bytecode: instructions for a simple stack machine, stored in .class files. The JVM is the program that turns those files into running code. It has three parts, and every class passes through all three.

PartWhat it doesWhat you see when it goes wrong
Class loader subsystemFinds the bytes of a class, checks them, and creates the class inside the JVM. Runs static initialisers.ClassNotFoundException, NoClassDefFoundError, NoSuchMethodError, slow startup
Runtime data areasMemory: the heap for objects, one stack per thread, Metaspace for class metadata, the code cache for compiled code.OutOfMemoryError, StackOverflowError, a container killed for using too much memory
Execution engineRuns bytecode. First with an interpreter, then with machine code produced by the JIT compilers for the methods that run often.Slow first requests after a deploy, high CPU during warm-up
This lesson covers the first part and introduces the third. Memory is the next lesson, the JIT is lesson 4.

A class is loaded when it is first needed, not when the JVM starts. A service with 20,000 classes on its class path loads only the ones that the running code touches, one at a time, and each one goes through three steps: loading (find the bytes and create the class), linking (verify, prepare, resolve) and initialisation (run the static initialiser).

Program outputjavap -c: the bytecode of one small method

Real JVM output
Compiled from "ClassLoading.java"
class ClassLoading$PriceCalculator {
  static final long TAX_PER_MILLE;
...
  static long gross(long);
    Code:
       0: lload_0
       1: lload_0
       2: getstatic     #7                  // Field TAX_PER_MILLE:J
       5: lmul
       6: ldc2_w        #13                 // long 1000l
       9: ldiv
      10: ladd
      11: lreturn
This is static long gross(long netCents) { return netCents + netCents * TAX_PER_MILLE / 1000; }. Each line is one instruction for a stack machine: lload_0 pushes the argument, getstatic #7 pushes the static field, lmul, ldiv and ladd pop two values and push the result. The #7 is an index into the class's constant pool, a symbolic reference by name. It is turned into a real address the first time the instruction runs. That is resolution, and it is why a missing class or method can fail at run time and not at startup.

Why it exists

Most engineers meet the class loader only through its errors. They are among the most misread errors in Java, because the exception that reaches the log is often not the first one. Three kinds of production problem come from this part of the JVM:

  • A class cannot be found or used. ClassNotFoundException, NoClassDefFoundError, NoSuchMethodError, ClassCastException between two classes with the same name. The cause is almost always the class path: a missing jar, two versions of a jar, or a static initialiser that failed earlier.
  • Class metadata that is never freed. Each class loader owns the metadata of the classes it defined. If anything keeps a loader reachable, none of its classes can be unloaded. A service that creates loaders (plugins, scripting, hot reload, some proxies) and leaks them ends with OutOfMemoryError: Metaspace.
  • Slow startup. Every class has to be found in a jar, parsed, verified and initialised before its first use. A Spring Boot service loads many thousands of classes before it can answer a request. That time is paid on every deploy and every scale-out.

All three are diagnosed with the same few tools: the class loading log (-Xlog:class+load), jcmd <pid> VM.classloader_stats, and reading a stack trace down to the first cause.

How it works inside

Loading, linking, initialisation

StepWhat the JVM doesWhat triggers itTypical failure
LoadingA class loader finds the bytes for a name and the JVM creates the class from them.The first reference to the class from running code, or Class.forName, or loadClass.ClassNotFoundException, or NoClassDefFoundError with that as its cause
Linking: verificationChecks that the bytecode is structurally correct and type safe.Before the class is initialised.VerifyError, UnsupportedClassVersionError (compiled for a newer Java)
Linking: preparationCreates the static fields and sets them to default values (0, null, false).With verification.Rare
Linking: resolutionReplaces a symbolic reference (a class, field or method name in the constant pool) with a direct one.HotSpot does this lazily, when the instruction that uses the reference first runs.NoSuchMethodError, NoSuchFieldError, IllegalAccessError
InitialisationRuns the static initialiser <clinit>: static field assignments and static { } blocks, in source order, once, under a per-class lock.new, a static method call, a non-constant static field access, initialisation of a subclass, some reflection.ExceptionInInitializerError, then NoClassDefFoundError forever after
After the Java Virtual Machine Specification, chapter 5. The specification allows resolution to be eager or lazy; HotSpot resolves lazily.

Loading and initialisation are separate events, and the log shows it. The program below loads a class with Class.forName(name, false, loader), which asks for loading without initialisation, and calls a static method on it later.

Program outputjava -Xlog:class+load,class+init ClassLoading lifecycle (filtered)

Real JVM output
[0.011s][info][class,load] java.lang.Object source: shared objects file
[0.011s][info][class,load] java.lang.String source: shared objects file
[0.024s][info][class,load] ClassLoading source: file:/tmp/lab/out/
[0.024s][info][class,init] Start class verification for: ClassLoading
[0.025s][info][class,init] End class verification for: ClassLoading
[0.025s][info][class,init] 323 Initializing 'ClassLoading'(no method) (0x00007d824c000800) by thread "main"
1. main starts, PriceCalculator has not been touched
2. Class.forName(name, false, loader): load without initialising
[0.025s][info][class,load] ClassLoading$PriceCalculator source: file:/tmp/lab/out/
   loaded ClassLoading$PriceCalculator by app loader
3. first call of a static method: initialisation happens now
[0.041s][info][class,init] Start class verification for: ClassLoading$PriceCalculator
[0.041s][info][class,init] End class verification for: ClassLoading$PriceCalculator
[0.041s][info][class,init] 433 Initializing 'ClassLoading$PriceCalculator' (0x00007d824c000a08) by thread "main"
  [PriceCalculator] static initialiser runs
   gross(1000) = 1200
4. second call: nothing left to do
   gross(2000) = 2400
[0.048s][info][class,load] java.sql.Driver source: jrt:/java.sql
loaders: String -> null, java.sql.Driver -> platform, ClassLoading -> app
Read the lines that mention PriceCalculator. It is loaded at 0.025 s, when Class.forName asks for it, from file:/tmp/lab/out/. It is verified and initialised only at 0.041 s, when gross() is first called, and the static initialiser prints its line exactly once. The source: field tells you where every class came from: shared objects file is the CDS archive shipped with the JDK, jrt:/java.sql is a JDK module, a file: or jar: URL is your class path. The last line shows the three loaders: String has loader null (bootstrap), java.sql.Driver the platform loader, and the application class the app loader. The unfiltered log of this run has 652 class loading lines, 614 of them from the shared archive.

Three loaders and parent delegation

LoaderLoadsHow it appears
BootstrapThe core of the JDK, such as java.base. Built into the JVM.getClassLoader() returns null. Shown as <boot class loader> by jcmd.
PlatformThe other Java SE and JDK modules, such as java.sql.Named platform.
Application (system)Everything on the class path and module path: your code and your dependencies.Named app. Its parent is the platform loader.
Your ownWhatever you give it: a plugin directory, a jar uploaded at run time, generated classes. Frameworks and application servers create loaders of their own as well.A URLClassLoader or a subclass.

When a loader is asked for a class, the default loadClass does three things in order: check whether it has already loaded that name, ask its parent, and only then look in its own location with findClass. This is parent delegation. It means a class in java.base always comes from the bootstrap loader, whatever is on your class path, and that a class is loaded by the highest loader that can find it.

ClassNotFoundException and NoClassDefFoundError

ClassNotFoundExceptionNoClassDefFoundError
KindChecked exceptionError (a LinkageError)
Who askedYour code asked for a class by name, as a string: Class.forName, loadClass, a framework reading a class name from configuration.The JVM needed a class that compiled code refers to, and could not get a usable one.
Usual causeThe name is on no class path: a missing dependency, a typo in configuration, the wrong loader asked.(a) Present at compile time, absent at run time: a missing jar, an optional or provided dependency. (b) The class was found, but its static initialiser failed earlier.
What to readThe class name in the message, and which loader was asked (the top frames).The message. Could not initialize class X is case (b): look for the first ExceptionInInitializerError for X, earlier in the log.

Program outputjava ClassLoading missing: the three errors in order

Real JVM output
--- 1. a class name that is on no class path
java.lang.ClassNotFoundException: com.example.billing.InvoiceMapper
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:526)
	at java.base/java.lang.Class.forName0(Native Method)
	at java.base/java.lang.Class.forName(Class.java:423)
	at java.base/java.lang.Class.forName(Class.java:414)
	at ClassLoading.missing(ClassLoading.java:76)
	at ClassLoading.main(ClassLoading.java:53)
--- 2. first use of a class whose static initialiser throws
java.lang.ExceptionInInitializerError
	at ClassLoading.missing(ClassLoading.java:82)
	at ClassLoading.main(ClassLoading.java:53)
Caused by: java.lang.IllegalStateException: rates.csv not found
	at ClassLoading$RateTable.load(ClassLoading.java:36)
	at ClassLoading$RateTable.<clinit>(ClassLoading.java:34)
	... 2 more
--- 3. second use of the same class
java.lang.NoClassDefFoundError: Could not initialize class ClassLoading$RateTable
	at ClassLoading.missing(ClassLoading.java:88)
	at ClassLoading.main(ClassLoading.java:53)
Caused by: java.lang.ExceptionInInitializerError: Exception java.lang.IllegalStateException: rates.csv not found [in thread "main"]
	at ClassLoading$RateTable.load(ClassLoading.java:36)
	at ClassLoading$RateTable.<clinit>(ClassLoading.java:34)
	at ClassLoading.missing(ClassLoading.java:82)
	... 1 more
Part 1 is a ClassNotFoundException: Class.forName was given a name that no loader can find. The frames show the application loader was asked. Part 2 is the first use of RateTable, whose static initialiser throws: the JVM wraps the exception in ExceptionInInitializerError and marks the class as failed. Part 3 is the second use: now the error is NoClassDefFoundError: Could not initialize class, although the class file is present and was loaded. JDK 21 attaches the original failure as Caused by, including the thread it happened in. In a real service the first failure may be hours earlier and in another thread's log, and every later request shows only part 3.

From bytecode to machine code

Once a class is initialised its methods can run. HotSpot starts every method in the interpreter, which executes the bytecode one instruction at a time and counts how often each method and loop runs. Methods that run often are compiled to machine code in the background, first by the quick C1 compiler and later, with the profile the earlier tiers collected, by the optimising C2 compiler. The compiled code is stored in the code cache. This is why a JVM gets faster during its first minutes, and it is the subject of JIT compilation and profiling.

Class data sharing

Parsing and verifying classes is repeated work: every start of the same application does it again. Class data sharing (CDS) stores classes in the JVM's internal form in an archive file that is mapped into memory at startup. The JDK ships a default archive with about 1,300 core classes and uses it unless you pass -Xshare:off; those are the source: shared objects file lines above. You can add your application's classes with a dynamic archive: -XX:ArchiveClassesAtExit=app.jsa on a trial run, then -XX:SharedArchiveFile=app.jsa, or both steps in one with -XX:+AutoCreateSharedArchive -XX:SharedArchiveFile=app.jsa. The archive is only valid for the same JDK build and class path.

Architecture

Drawing diagram…

Flowchart. A class file enters the class loader subsystem and passes through loading, linking and initialisation. Its metadata is stored in Metaspace and its Class object on the heap. The interpreter runs its bytecode, hot methods go to the JIT compilers, and compiled code is stored in the code cache. Both interpreter and compiled code use thread stacks.

flowchart LR
  A["OrderService.class in a jar"] --> B["Class loader subsystem"]
  B --> C["Loading, find bytes and create class"]
  C --> D["Linking, verify, prepare, resolve"]
  D --> E["Initialisation, run static initialiser"]
  E --> F["Metaspace, class metadata"]
  E --> G["Heap, the Class object and static fields"]
  F --> H["Interpreter runs bytecode"]
  H -->|"method is hot"| I["JIT compilers C1 and C2"]
  I --> J["Code cache, machine code"]
  J --> K["Thread stacks, one frame per call"]
  H --> K
The path of one class through the JVM, from a file in a jar to machine code.
  • The three steps on the left happen once per class per loader, at first use. A request that touches a class for the first time pays for all three.
  • Class metadata (methods, bytecode, constant pool) lives in Metaspace, outside the heap. The java.lang.Class object and the static fields live on the heap. A class can be unloaded only when its loader is unreachable, and then all of that is freed together.
  • The interpreter and the compiled code are two ways to run the same method. The JVM switches a method from one to the other while the program runs.
  • Every thread has its own stack. Each method call pushes a frame with the local variables and, in the interpreter, the operand stack that the javap -c listing manipulates.

Step by step

Drawing diagram…

Sequence diagram. A request thread uses a class for the first time. The application loader checks its own loaded classes, delegates to the platform loader, which delegates to the bootstrap loader. Both answer that they do not have it, the application loader finds it on the class path and defines it, the JVM verifies and prepares it, and the first static call runs the static initialiser.

sequenceDiagram
  participant T as Request thread
  participant A as App loader
  participant P as Platform loader
  participant B as Bootstrap loader
  participant V as JVM linker
  T->>A: First use of InvoiceMapper
  A->>A: Already loaded by me, no
  A->>P: Delegate to parent
  P->>B: Delegate to parent
  B-->>P: Not in the core modules
  P-->>A: Not in the platform modules
  A->>A: Search the class path, found in billing.jar
  A->>V: Define class from bytes
  V->>V: Verify and prepare
  V-->>T: Class is loaded and linked
  T->>V: First static call
  V->>V: Run static initialiser under the class lock
  V-->>T: Initialised, call proceeds
The first use of an application class: delegation upwards, a search downwards, then linking and initialisation.
  1. The parents are asked first, so the application loader searches its own class path only after both parents have said no. If no loader finds the class, the result is ClassNotFoundException.
  2. The loader that calls defineClass becomes the defining loader. Together with the name it is the identity of the class.
  3. Initialisation runs under a lock that belongs to the class. If two threads use a class for the first time at the same moment, one runs the initialiser and the other waits. A slow static initialiser (one that opens a connection or reads a large file) blocks every thread that needs the class.
  4. All of this happens on the request thread, inside the request. This is one reason the first request through any code path is slower than the following ones.

In a real system

A pricing service lets the business team upload a jar of pricing rules without a redeploy. On every upload the service creates a new URLClassLoader for the jar and instantiates the rule classes. After a few weeks the service dies with java.lang.OutOfMemoryError: Metaspace, usually soon after an upload. The heap graphs are flat. This is a class loader leak: the old loaders are still reachable, so their classes cannot be unloaded.

The lab reproduces the shape with 40 loaders that each define one class, with one object from each kept in a long-lived list. One command shows it:

Program outputjcmd <pid> VM.classloader_stats, after 40 reloads

Real JVM output
6410:
ClassLoader         Parent              CLD*               Classes   ChunkSz   BlockSz  Type
0x00007672d4041698  0x00007672d3069090  0x000076734814a190       1      6144      1768  java.net.URLClassLoader
0x00007672d4041698  0x00007672d3069090  0x00007673481469e0       1      6144      1768  java.net.URLClassLoader
0x00007672d4041698  0x00007672d3069090  0x000076734814be00       1      6144      1768  java.net.URLClassLoader
...
0x0000000000000000  0x0000000000000000  0x00007673480d2c80     946   4456448    654640  <boot class loader>
                                                                10     30720     18000   + hidden classes
...
0x00007672d30687f8  0x00007672d3069090  0x000076734810b000       1     10240      6664  jdk.internal.loader.ClassLoaders$AppClassLoader
0x00007672d3069090  0x0000000000000000  0x00007673480e3020       1      6144      2640  jdk.internal.loader.ClassLoaders$PlatformClassLoader
...
Total = 43                                                     998   4747264    752664
ChunkSz: Total size of all allocated metaspace chunks
BlockSz: Total size of all allocated metaspace blocks (each chunk has several blocks)
One row per live class loader. Type is the loader's class, Classes how many classes it has defined, ChunkSz the Metaspace it holds in bytes. A healthy service has a small, stable number of rows. Here the total is 43 loaders: the three built-in ones and 40 URLClassLoader rows with one class each, one per reload. The CLD* column differs on every row, so these are 40 separate loaders. Run the command twice, some minutes and a few reloads apart: a row count for one loader type that only grows is the leak. A class histogram of the same process (jcmd <pid> GC.class_histogram) lists the plugin class 40 times, once per loader, each with one instance.

To find what keeps a loader alive, take a heap dump and follow the path from one of the stale loader objects to a GC root. The usual holders are a static collection or cache that still contains an object of an old class, a ThreadLocal on a pooled thread, a thread started by the plugin that never ended, or a JDBC driver or shutdown hook the plugin registered. The method is the one in Memory leaks and heap dumps.

The second everyday case is slow startup. A trivial program in the lab loads 652 classes before main finishes, and takes them almost entirely from the shared archive. A Spring Boot service loads many thousands of classes from nested jars, and none of your classes are in the default archive. Measure first: -Xlog:class+load:file=classes.log shows how many classes were loaded and from where. Then decide between an application CDS archive, fewer dependencies, and lazy initialisation of beans.

Java and Spring Boot

Two things a Spring Boot 3.5 service can do: report what the class loader did during startup, so that a regression is visible in the log of every deploy, and start from an application CDS archive. The Java file uses only JDK management APIs behind Spring annotations; it was compiled against stub annotations here, not run inside Spring.

src/main/java/com/example/pricing/StartupClassReport.javaJava
package com.example.pricing;import java.lang.management.ClassLoadingMXBean;import java.lang.management.ManagementFactory;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.boot.context.event.ApplicationReadyEvent;import org.springframework.context.event.EventListener;import org.springframework.stereotype.Component;/** Logs what class loading cost during startup, once, when the application is ready. */@Componentpublic class StartupClassReport {    private static final Logger log = LoggerFactory.getLogger(StartupClassReport.class);    @EventListener(ApplicationReadyEvent.class)    public void report() {        ClassLoadingMXBean classes = ManagementFactory.getClassLoadingMXBean();        long uptimeMs = ManagementFactory.getRuntimeMXBean().getUptime();        long metaspaceBytes = ManagementFactory.getMemoryPoolMXBeans().stream()                .filter(pool -> pool.getName().equals("Metaspace"))                .mapToLong(pool -> pool.getUsage().getUsed())                .sum();        log.info("ready after {} ms: classes loaded={} unloaded={} metaspace used={} MB",                uptimeMs,                classes.getTotalLoadedClassCount(),                classes.getUnloadedClassCount(),                metaspaceBytes / (1024 * 1024));    }}

Why it is written this way

  • ClassLoadingMXBean is the same source Micrometer reads for jvm.classes.loaded and jvm.classes.unloaded. Logging it at readiness puts the number next to the startup time in every deploy log.
  • A loaded count that jumps between two releases explains a slower start better than any guess: a new dependency pulled in thousands of classes.
  • After startup the loaded count should go flat. A count that keeps climbing in a running service, with unloaded at zero, means classes are being generated or loaders are being leaked.
  • The Metaspace memory pool is the non-class part of class metadata. jcmd <pid> VM.metaspace gives the full picture.

Wrong, then right

The pricing service reloads a rules jar at run time. The first version creates a loader per reload and never lets go of the old one. The second version makes the old loader collectable.

Incorrect implementation

src/main/java/com/example/pricing/PricingRuleReloader.java (leaks a loader per reload)Java
package com.example.pricing;import java.net.URL;import java.net.URLClassLoader;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;import org.springframework.stereotype.Service;@Servicepublic class PricingRuleReloader {    public interface PricingRule {        long apply(long cents);    }    // every version ever loaded, "for audit"    private static final List<PricingRule> HISTORY = new ArrayList<>();    private volatile PricingRule current;    public synchronized void reload(Path rulesJar) throws Exception {        URL[] urls = { rulesJar.toUri().toURL() };        URLClassLoader loader = new URLClassLoader(urls, PricingRule.class.getClassLoader());        Class<?> ruleClass = loader.loadClass("com.example.rules.CurrentRule");        PricingRule rule = (PricingRule) ruleClass.getDeclaredConstructor().newInstance();        HISTORY.add(rule);        current = rule;    }    public long price(long cents) {        return current.apply(cents);    }}

Why it is written this way

  • HISTORY keeps one object per reload. An object references its class, the class references its defining loader, and the loader references every class it defined. One small object pins a whole loader.
  • The loader is never closed, so the jar file also stays open: one file descriptor per reload.
  • The parent is the application loader, which is correct: PricingRule must be the same class on both sides, or the cast would fail.

Why it fails

  • Nothing fails on the first reload, or the tenth. Each reload adds one loader with its classes to Metaspace and nothing is ever removed, because the static list makes every old rule object reachable from a GC root.
  • Class metadata is not on the heap. Heap graphs stay flat while Metaspace climbs by a step per reload. With -XX:MaxMetaspaceSize set, the service eventually throws java.lang.OutOfMemoryError: Metaspace in whatever thread loads the next class. Without a limit, the process grows until the container is killed.
  • In production the visible symptom is jvm.classes.loaded rising for ever with jvm.classes.unloaded at 0, and jcmd <pid> VM.classloader_stats showing one more URLClassLoader row after each upload.

Corrected implementation

src/main/java/com/example/pricing/PricingRuleReloader.java (old loader becomes collectable)Java
package com.example.pricing;import java.net.URL;import java.net.URLClassLoader;import java.nio.file.Path;import org.springframework.stereotype.Service;@Servicepublic class PricingRuleReloader {    public interface PricingRule {        long apply(long cents);    }    /** The rule and the loader that defined it travel together. */    private record Loaded(PricingRule rule, URLClassLoader loader, String version) {}    private volatile Loaded current;    public synchronized void reload(Path rulesJar, String version) throws Exception {        URL[] urls = { rulesJar.toUri().toURL() };        URLClassLoader loader = new URLClassLoader("rules-" + version, urls, PricingRule.class.getClassLoader());        Loaded next;        try {            Class<?> ruleClass = loader.loadClass("com.example.rules.CurrentRule");            next = new Loaded((PricingRule) ruleClass.getDeclaredConstructor().newInstance(), loader, version);        } catch (Exception | LinkageError e) {            loader.close();   // a failed reload must not leave a loader behind            throw e;        }        Loaded previous = current;        current = next;       // the only long-lived reference to the new loader        if (previous != null) {            previous.loader().close();   // releases the jar file        }    }    public long price(long cents) {        return current.rule().apply(cents);    }    public String version() {        return current.version();    }}

Why it is written this way

  • There is exactly one long-lived reference to a rule and its loader: the current field. Replacing it makes the previous loader unreachable once in-flight calls have returned, and its classes can then be unloaded by the garbage collector.
  • The audit need is met by keeping the version string, not the object. Anything kept from an old version must be a JDK or application type, never an instance of a class the old loader defined.
  • The loader has a name (for example rules-v42). It appears in stack traces and in ClassCastException messages, which makes a leak far easier to recognise.
  • close() releases the jar. It does not unload classes: that happens when the collector finds the loader unreachable.
  • catch (Exception | LinkageError e) covers both a missing class and a class that cannot be linked or initialised.

Trade-offs

  • After close() the old loader can no longer load classes it has not loaded yet. A request that is still inside the old rule and touches a new class for the first time fails with NoClassDefFoundError. If rules are large, delay the close until in-flight calls have drained.
  • Unloading is not immediate. Metaspace falls only when a collection that unloads classes runs, so the graph is a saw-tooth and not a flat line.
  • Static state inside the rule classes is lost on every reload, because the new loader defines new classes with new static fields. Rules must not keep counters or caches in statics.
  • One stray reference brings the leak back: a rule that registers itself as a listener, starts a thread or sets a ThreadLocal. Reloading code at run time needs a test that reloads 100 times and checks the loader count.

Configuration

Flags that show or change what the class loader subsystem does. Defaults are from the JDK 21 java command reference.

-Xlog:class+load=infoDefault off
What it does
Logs one line per loaded class with its source: a jar, a JDK module or the shared archive. -verbose:class is the older spelling.
When to change it
Write it to a file (-Xlog:class+load:file=classes.log) to find which jar a class really came from, or to count classes loaded during startup. Add class+unload to see unloading.
-XshareDefault auto
What it does
Whether to use class data sharing. auto uses the shared archive if possible, off never does.
When to change it
Leave it on. Use -Xshare:off only to measure what CDS saves, or to rule it out while debugging.
-XX:SharedArchiveFileDefault none (the JDK's default archive is used)
What it does
Path of a CDS archive to use: your own static archive, or a dynamic archive on top of the default one.
When to change it
Point it at an archive built for exactly this JDK build and class path. A mismatched archive is ignored.
-XX:ArchiveClassesAtExitDefault none
What it does
On exit, writes a dynamic archive of the application classes that were loaded in this run.
When to change it
Use it in a training run in the build pipeline. -XX:+AutoCreateSharedArchive with -XX:SharedArchiveFile does the same without a separate run, if the process may write the file.
-XX:MaxMetaspaceSizeDefault unlimited
What it does
Upper limit on native memory for class metadata.
When to change it
Set it in containers so that a loader leak ends as OutOfMemoryError: Metaspace, which names the cause, and not as a kill by the container runtime, which does not.
spring.main.lazy-initializationDefault false
What it does
Spring Boot creates beans when they are first needed and not at startup, which also postpones loading their classes.
When to change it
It shortens startup and moves the cost to the first requests. The Spring Boot reference warns that it also delays the discovery of misconfigured beans.

Hands-on exercise

Watch a class being loaded, initialised and failing

Run the lab program on your own JDK 21 and see loading and initialisation as separate events, read the bytecode of a method, and produce the three class loading errors in order.

Steps · 0 of 6 done

What can go wrong

Reading NoClassDefFoundError as 'the jar is missing'
Symptom
Requests fail with NoClassDefFoundError: Could not initialize class com.example.RateTable. The class is in the jar. A restart fixes it for a while.
Cause
The static initialiser of that class threw once, perhaps because a file, an environment variable or a remote service was missing at that moment. The JVM marked the class as failed and every later use gets NoClassDefFoundError.
Fix
Search the log from process start for the first ExceptionInInitializerError naming the class; its cause is the real error. Then move work that can fail out of static initialisers into a bean that can report the failure and retry.
Two versions of one library on the class path
Symptom
NoSuchMethodError or NoSuchFieldError at run time in code that compiled without errors, often only in one environment.
Cause
The class was loaded from an older jar that comes first on the class path. Resolution of the method reference is lazy, so the error appears only when that line first runs.
Fix
Find the source with -Xlog:class+load and grep for the class name. Then fix the dependency tree (mvn dependency:tree or gradle dependencies) so that one version remains.
Keeping anything from an old class loader
Symptom
Metaspace and the loaded class count rise by a step on every reload or redeploy and never fall. Eventually OutOfMemoryError: Metaspace.
Cause
A static collection, a ThreadLocal on a pooled thread, a running thread or a registered listener still references an object whose class the old loader defined.
Fix
Hold one reference to the current version and drop it on reload. Stop threads and deregister listeners that the reloaded code created. Verify with jcmd <pid> VM.classloader_stats after repeated reloads.
Expensive work in static initialisers
Symptom
The first request that touches a class takes seconds, or many threads hang at startup with stack traces that end in a class's <clinit>.
Cause
The static initialiser runs once under the class's initialisation lock. Every other thread that needs the class waits until it finishes.
Fix
Keep static initialisers to constants. Build expensive objects in a bean at startup, where the time is visible and failures are reported properly.

How to troubleshoot

ClassNotFoundException or NoClassDefFoundError for a class you expect to be present

Check

java -Xlog:class+load:file=classes.log -jar app.jar   then   grep 'com.example.billing' classes.log
How to read it
If the class is listed, its source: shows the jar it was loaded from, and the problem is elsewhere (a failed initialiser, or the wrong version). If it is not listed, it is on no class path that the asking loader can see: check the built artifact with jar tf.
NoClassDefFoundError: Could not initialize class X

Check

grep -n 'ExceptionInInitializerError' app.log | head -1   (JDK 21 also prints it as the 'Caused by' of the later error)
How to read it
The first occurrence carries the real exception from the static initialiser. Everything after it is a consequence. The class stays unusable until the JVM restarts.
Metaspace or the loaded class count grows without bound

Check

jcmd <pid> VM.classloader_stats   (twice, some minutes apart); Micrometer `jvm.classes.loaded` and `jvm.classes.unloaded`
How to read it
A row count that grows for one loader type is a loader leak. One loader whose Classes number grows is class generation without reuse, for example proxies or scripts compiled per request.
ClassCastException where both class names are the same

Check

Read the full message: it names the loader of each class. Then jcmd <pid> VM.classloaders to see the loader hierarchy.
How to read it
The class was defined by two loaders. A shared interface must be defined by a common parent of both sides, and only there.
Startup is slow and you do not know where the time goes

Check

java -XX:StartFlightRecording:filename=startup.jfr,class-loading=true -jar app.jar   then   jfr view longest-class-loading startup.jfr
How to read it
Class loading events are off in the default JFR settings; class-loading=true switches them on. The view lists the classes whose loading took longest. Many slow loads from one jar point at that dependency. A long gap with no class loading points at a slow initialiser or a remote call during startup.

Key takeaways

  • A class goes through loading, linking and initialisation at its first use, on the thread that uses it. Each step has its own errors.
  • Loaders delegate to their parent first. The bootstrap, platform and application loaders are built in; a class is identified by its name and its defining loader.
  • ClassNotFoundException means code asked for a name no loader could find. NoClassDefFoundError means the JVM could not get a usable class: missing at run time, or its static initialiser failed earlier.
  • For Could not initialize class, the real error is the first ExceptionInInitializerError, which may be far up the log.
  • Classes are unloaded only with their loader. Any reference to any object of any class of a loader keeps all of it in Metaspace.
  • -Xlog:class+load shows where each class came from, and jcmd <pid> VM.classloader_stats shows how many loaders are alive.
  • The JVM interprets bytecode first and compiles hot methods later. CDS removes repeated loading work at startup.

Practical check

Small scenarios, one decision each. Pick what you would do, then read why.

Scenario 1 of 3

A payment service has run for six hours. Since 14:02 every call to the fee calculation fails with NoClassDefFoundError: Could not initialize class com.acme.FeeTable. The jar contains FeeTable.class, and the service worked this morning. At 14:02 the configuration server was unreachable for 40 seconds.

What is the most likely cause, and what do you do first?

Scenario 2 of 3

A rules engine compiles customer scripts into classes. jcmd VM.classloader_stats at 09:00 shows 212 rows of type ScriptClassLoader. At 13:00 it shows 3,480. Heap after GC is steady at 400 MB. The metric jvm.classes.unloaded is 0. Metaspace has grown from 150 MB to 620 MB.

What does this tell you?

Scenario 3 of 3

After a dependency upgrade, one endpoint fails in staging with NoSuchMethodError: com.fasterxml.jackson.databind.ObjectMapper.readerFor. The code compiles and unit tests pass. Other endpoints that use ObjectMapper work.

Which check finds the cause fastest?

References

References: Java Virtual Machine Specification, Java SE 21, chapter 5: Loading, Linking, and Initializing ↗ · Java SE 21 API: java.lang.ClassLoader (delegation model, built-in loaders) ↗ · JDK 21: the java command (-Xlog, -Xshare, class data sharing, -XX:MaxMetaspaceSize) ↗ · JDK 21 HotSpot Virtual Machine Guide: Class Data Sharing ↗ · JDK 21: the jcmd command (VM.classloader_stats, VM.classloaders, VM.metaspace) ↗ · JDK 21 Garbage Collection Tuning Guide: Other Considerations (class metadata and unloading) ↗ · Spring Boot 3.5 reference: Class Data Sharing ↗ · Report a problem