Skip to content
javahacks.dev
JVM & Performance

Fix Java Metaspace OutOfMemoryError and Class Loader Leaks

Fix OutOfMemoryError Metaspace by finding out whether the limit is too low, classes are generated without bound or a class loader leaks across redeploys.

7 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the OpenJDK, Apache Maven, Spring and Gradle logos.
Text
Exception in thread "main" java.lang.OutOfMemoryError: Metaspace

This error is not about the heap. Metaspace is the native memory region where the JVM keeps class metadata: method bytecode, constant pools, field layouts. It grows as classes load and shrinks only when a class loader becomes unreachable and the garbage collector unloads everything it defined. So the error comes down to one of two stories. Either the application legitimately needs more class metadata than the limit allows, or classes keep piling up because something holds on to them or keeps producing new ones. The second story is the common one, and raising the limit only delays it.

This post reproduces the error on purpose with real numbers, then goes through the checks in the order that finds the cause fastest. The lab ran on JDK 17.0.1, and the diagnostic commands are the same in Java 25.

Reproduce it with a leak you can see

Metaspace is released when a class loader is collected. This program defeats that by keeping every loader reachable in a list, which is exactly what a leaked redeploy looks like:

src/main/java/dev/javahacks/meta/Meta.javajava
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class Meta {
    public static void main(String[] args) throws Exception {
        URL[] urls = { Paths.get(System.getProperty("user.dir")).toUri().toURL() };
        List<ClassLoader> keep = new ArrayList<>();
        try {
            while (true) {
                URLClassLoader loader = new URLClassLoader(urls, null);  // no parent: loads its own Leaf
                Class.forName("Leaf", true, loader);
                keep.add(loader);                                        // the leak: loader stays reachable
            }
        } catch (OutOfMemoryError e) {
            int loaded = keep.size();
            keep.clear();
            System.out.println(e.getMessage());
            System.out.println(loaded);
        }
    }
}

Leaf is a one-line class sitting in the working directory. Every iteration defines a fresh copy of it in a fresh loader. Run it with a 32 MB metaspace cap:

Shell
javac -XDstringConcat=inline Meta.java Leaf.java
java -XX:MaxMetaspaceSize=32m Meta
Text
Metaspace
5359

After 5,359 loaders the JVM refused to allocate more metadata and threw. The -XDstringConcat=inline flag keeps the catch block from needing a new invokedynamic call site, which itself needs metaspace; without it the handler fails with the same error before it can print. That is a small version of why you cannot clean up gracefully after this error: the code that tries to react also needs the resource that ran out.

Turn on the GC log and you see the JVM trying everything before giving up:

Text
[0.237s][info][gc] GC(0) Pause Young (Concurrent Start) (Metadata GC Threshold) 26M->14M(520M)
[0.340s][info][gc] GC(3) Pause Full (Metadata GC Threshold) 20M->20M(80M) 12.613ms

Metadata GC Threshold means the collection was triggered by metaspace pressure and not by heap pressure. A full GC that reclaims nothing (20M before, 20M after) is the signature of a leak: the loaders are alive, so there is nothing to unload.

Step 1: is there a limit at all?

By default MaxMetaspaceSize is unlimited, so the JVM keeps growing until the operating system or the container stops it. If the error appears, someone set the flag. Check what the process runs with:

Shell
jcmd <pid> VM.flags | tr ' ' '\n' | grep -i metaspace
java -XX:MaxMetaspaceSize=32m -XX:+PrintFlagsFinal -version | grep -E 'MaxMetaspaceSize|MetaspaceSize |CompressedClassSpaceSize'
Text
   size_t CompressedClassSpaceSize     = 29360128      {product} {ergonomic}
   size_t MaxMetaspaceSize             = 33554432      {product} {command line}
   size_t MetaspaceSize                = 22020096      {product} {default}

MetaspaceSize is not a limit. It is the threshold at which the first metaspace-triggered collection happens, 21 MB by default here. CompressedClassSpaceSize is a separate region for class pointers, 1 GB reserved by default, and OutOfMemoryError: Compressed class space is the sibling error when that one fills. If the process died with no limit set, it ran out of native memory and the cause is closer to a container being OOM-killed.

Step 2: see who holds the space

Do not guess. jcmd lists metaspace per class loader on a running JVM:

Shell
jcmd <pid> VM.classloader_stats | head
jcmd <pid> VM.metaspace | head -12
Text
ClassLoader         Parent              CLD*               Classes   ChunkSz   BlockSz  Type
0x0000000800c40b40  0x0000000000000000  0x00000001035e1130       1       768       161  java.net.URLClassLoader
0x0000000800c40b40  0x0000000000000000  0x00000001036b3e70       1       768       161  java.net.URLClassLoader
...
Total Usage - 2002 loaders, 2575 classes (549 shared):
       Both: 4004 chunks,     15.97 MB capacity,    12.29 MB ( 77%) committed,     2.94 MB ( 18%) used

That output is from the leak program held at 2,000 loaders. The two lines to read are the loader count and the type column. Two thousand identical URLClassLoader rows, one class each, is a leak: nothing legitimate creates that many. In a real service the rows say org.apache.catalina.loader.ParallelWebappClassLoader, or groovy.lang.GroovyClassLoader, or jdk.internal.reflect.DelegatingClassLoader, and the name points at the culprit.

Repeat it five minutes later under load. A count that only goes up is a leak. A count that goes up and down is healthy churn, and the limit may just be too low.

Cause 1: class loaders that stay reachable

A loader is collected only when nothing reachable refers to it, or to any class, or instance of a class, that it defined. The classic breakages:

  • Hot redeploys in an application server. A static field in a shared library, a ThreadLocal on a pooled thread, a JDBC driver registered with DriverManager, or a shutdown hook pins the old webapp's loader. After ten redeploys you have eleven copies of the application's classes. The fix is a clean shutdown listener, or restarting the container instead of redeploying. See ThreadLocal leaks.
  • A thread that outlives its owner. A non-daemon thread started by the webapp references its context class loader. The old loader lives as long as the thread does.
  • **A cache keyed by Class or holding instances from a plugin.** A static Map<Class<?>, X> in a parent loader holds every plugin class forever.

To confirm, take a heap dump and look for the loader's GC root. The path to the root names the static field or thread that pins it. Capturing and reading a heap dump shows how.

Cause 2: unbounded class generation

Some code writes classes at run time, and if it writes a new one each time instead of reusing, the count has no bound:

  • A scripting engine that compiles every evaluated script into a new class (Groovy, or any template engine that compiles to bytecode, called with a different script string each request).
  • A proxy library asked for a proxy class with a different configuration each time.
  • Reflection inflation: the JDK generates accessor classes after repeated reflective calls, normally a small, fixed number.
  • A bug that creates a new ClassLoader per request, the leak program above without the list.

The cure is to cache and reuse the compiled form. Compile a script once, keep the compiled object, and bind variables at call time:

java
// grows metaspace on every call: a new class per distinct script string
Object r = new GroovyShell().evaluate("price * " + rate);

// bounded: one compiled script, new bindings per call
Script script = shell.parse("price * rate");     // once, kept in a field
script.setBinding(new Binding(Map.of("price", p, "rate", rate)));
Object r = script.run();

Cause 3: the limit is genuinely too low

If the loader count is stable and the number of classes is plausible, the limit is just too small for a large application. A Spring Boot service with many libraries can need well over 100 MB of metaspace. Measure before you raise it:

Shell
jcmd <pid> VM.metaspace | grep -E 'Both:|Total Usage'

Set the cap at roughly 1.5 times the steady-state committed figure, and keep it set. A cap turns a leak into a fast, loud failure with a stack trace, while no cap turns it into a slow death by the kernel's OOM killer with no explanation. In a container, remember that metaspace counts against the memory limit alongside heap, thread stacks and direct buffers, see JVM memory areas.

Get the evidence when it fails

Make the next occurrence leave a record:

Shell
java -XX:MaxMetaspaceSize=256m \
     -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/log/app/ \
     -Xlog:gc*:file=/var/log/app/gc.log:time,uptime \
     -jar app.jar

HeapDumpOnOutOfMemoryError also fires for metaspace errors, and the dump is where the GC root of the leaked loader lives. Sibling errors have different fixes: heap exhaustion is a different region, and a thread that cannot be created is covered in Java threads.

Where this does not apply

If the message says Java heap space, GC overhead limit exceeded or unable to create native thread, this is the wrong post: those are separate regions with separate fixes. If the process is killed with no Java exception at all, look at the container limit first. The primary references are [jcmd](https://docs.oracle.com/en/java/javase/25/docs/specs/man/jcmd.html) and the JDK troubleshooting guide.

Also inDebugging
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.