SteelReed

Search

Search posts, questions…

3. Advanced Java

Inside the JVM: runtime memory areas, class loading and ClassLoaders

Where a running Java program lives in memory: heap, stack, metaspace, PC register, code cache; how classes are loaded, linked and initialized; the ClassLoader tree, parent delegation, why the same class name can be two different types, and ClassLoader leaks.

19 Nov 20268 min readSenior

–

1. The problem

An app on Tomcat gains about 80 MB of metaspace on every hot redeploy; on the 6th it dies with OutOfMemoryError: Metaspace. The same week a plugin reports ClassCastException: class com.shop.Order cannot be cast to class com.shop.Order: same name, different loader.

2. Key idea

Area Per thread or shared Holds Error when full
JVM stack per thread frames: locals, operand stack StackOverflowError (default -Xss 1 MB on Linux x64)
Heap shared objects, arrays, Class objects, string pool Java heap space
Metaspace shared class metadata: methods, fields, bytecode Metaspace

PermGen was removed in JDK 8. A growing static Map fills the heap; metaspace only fills with too many classes (dynamically generated proxies, loaders leaking on redeploy).

Classes load lazily and initialise on first real use (new, calling a static method). The JVM holds a lock while running <clinit>, so class initialisation is thread-safe out of the box. If <clinit> throws, the class is broken for good in that loader.

2.1 Loaders and common errors

Each loader asks its parent before looking itself (parent delegation). Tomcat and plugin systems have their own loaders, sometimes looking locally first.

Error When Usually caused by
ClassNotFoundException loading by name (Class.forName) finds nothing a missing jar, a wrong name, the wrong loader
NoClassDefFoundError the class existed at compile time but can't load at runtime a provided-scope jar, or a <clinit> that once threw
ClassCastException: X to X same name, defined by two loaders a jar duplicated in the app and a shared folder
Metaspace OOM after redeploy old loaders aren't collected static maps, ThreadLocal, unstopped threads, unregistered JDBC drivers

A loader and all its classes are collected only when nothing references any class it defined.

3. In Java

Where things live, and a common loader leak.

JAVA
public class Booking {
    static int created = 0;                 // value lives in the Booking.class object (heap)
    private final String code;              // instance field: in the Booking object (heap)
 
    static Booking open(String code) {
        int len = code.length();            // local: in the frame on the stack
        return new Booking(code);           // reference in the frame, object on the heap
    }
    Booking(String code) { this.code = code; created++; }
}
 
// Leaking a loader on redeploy: a long-lived thread holds the app's classes
static final ThreadLocal<Formatter> FMT = ThreadLocal.withInitial(Formatter::new);
// Tomcat's threads survive redeploys -> hold Formatter -> hold the old loader -> metaspace never shrinks
// Fix: FMT.remove() in each request's finally, or don't put app classes in ThreadLocals

See which jar a class came from with -Xlog:class+load. Other languages: .NET has AssemblyLoadContext with the same unloading problem; Node.js caches modules by path.

Finding leaked loaders and reading bytecode
  • After a few redeploys, jcmd <pid> VM.classloader_stats shows how many loaders exist and each one's metaspace. Heap dump → MAT → find the old WebappClassLoader → Path to GC Roots to see who holds it.
  • Usual culprits: a static map in a JDK or shared-library class holding app objects, ThreadLocals on the server's thread pool, app-created threads not stopped on undeploy, JDBC drivers self-registering with DriverManager.
  • A method's bytecode has offsets on the left, exactly what the PC holds; jumps (if_icmple, goto) just assign the PC. this is local slot 0 of an instance method.
  • The JIT's escape analysis can skip allocating objects that don't escape a method: "objects always live on the heap" is true semantically, not always in the implementation. Remember that when reading benchmarks.
  • Real RSS also includes OS thread stacks, direct buffers and GC structures: see virtual memory and the JVM in containers.

4. Working with AI

Hand to AI: reading -Xlog:class+load to say which jar a class came from, reading mvn dependency:tree for duplicate jars, explaining javap bytecode.

Check in AI-written code:

  • No unbounded static map holding per-request objects.
  • Every ThreadLocal.set has a remove() in finally.
  • Threads and executors created by the app are stopped on shutdown.
  • No jar duplicated across two loader levels (the app and the server's shared folder).

5. Exercises

Exercise 1: Read a NoClassDefFoundError

Production logs: the first call to PricingRules shows ExceptionInInitializerError caused by NumberFormatException: For input string: ""; every later call shows NoClassDefFoundError: Could not initialize class PricingRules. The AI suggests "add the missing jar to the classpath". Do you agree?

Solution to Exercise 1

No. No jar is missing: NoClassDefFoundError: Could not initialize class means PricingRules's <clinit> once threw, and the class is permanently broken in that loader. The root is the first line: static final int MAX = Integer.parseInt(System.getenv("PRICING_MAX")) with an empty environment variable.

Fix: validate configuration at startup with a clear message (Spring @ConfigurationProperties + @Validated), not by parsing in static. To find the root cause, always look for the first occurrence in the log.

Exercise 2: Read a metaspace-after-redeploy incident

On every Tomcat redeploy metaspace grows 80 MB and never shrinks. VM.classloader_stats shows 6 ParallelWebappClassLoaders. A heap dump shows the old loader held by Thread "pool-3-thread-1" through a ThreadLocal. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.

Solution to Exercise 2
  • Diagnosis: the app created a pool-3 executor and never shut it down on undeploy; its thread lives on, holding a ThreadLocal with an app object, so the old loader and all its classes can't be collected.
  • 15 minutes: restart Tomcat fully (instead of redeploying) to free metaspace.
  • Root fix: shut the executor down in @PreDestroy, or use a Spring-managed bean; ThreadLocal.remove() in finally. Better still: deploy as a fresh container instead of hot redeploying.

Summary

  • Stacks are per thread; heap, metaspace and code cache are shared.
  • static field values live on the heap; metaspace holds class metadata.
  • <clinit> runs once and is thread-safe; if it throws, the class is broken for good.
  • A class is identified by name + loader; same name, different loader means different types.
  • A loader is collected only when nothing references its classes.

Read more: Garbage collectors: G1, ZGC and OutOfMemoryError.


Self-compiled notes from official documentation and hands-on practice.

Practice interview questions on this topic

All JVM questions →

Loading comments…
Next on the roadmapGarbage collection in the JVM: G1, ZGC, reading GC logs and diagnosing OutOfMemoryError