Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java: java.lang.OutOfMemoryError: Metaspace

Class metadata lives outside the heap. Which limit was hit, how to find the classloader that grows, and why a container restart with exit code 137 is the same disease.

~5 min readJava
#Java#JVM#Memory#ClassLoader
3D diagram of a JVM block with a side compartment filling with class cubes and a detached loader chain, headline METASPACE

Introduction & Quick Summary

Symptom. A long-running JVM dies with:

java.lang.OutOfMemoryError: Metaspace

or, in a container, the process disappears and the pod reports exit code 137, with java.lang.OutOfMemoryError: Compressed class space in the log just before it.

Cause. Class metadata lives in Metaspace, native memory outside the Java heap, since PermGen was removed in Java 8. The error means the JVM could not allocate more class metadata: either -XX:MaxMetaspaceSize is set and reached, or the container's memory limit is exhausted by heap plus metaspace plus everything else. Unbounded growth means classes are being created and never unloaded, and the usual source is a new classloader per redeploy, per plugin, or per request, each holding its classes alive.

Fix. Confirm which limit was hit (jcmd <pid> VM.metaspace), find the loader that grows (jcmd GC.class_stats, jmap -clstats), then stop the creation or restart cleanly on deploy. Raising MaxMetaspaceSize buys time and is the right move only after you know the growth rate.

Core Mechanics, Signatures & Reproducible Setup

Every loaded class has a Klass structure in Metaspace and, with compressed class pointers (the default), an entry in the compressed class space capped separately by -XX:CompressedClassSpaceSize. Metaspace is reclaimed only when its classloader becomes unreachable and class unloading runs, which is why leaks are per-loader rather than per-class.

The flags that matter:

bash
# bounded metaspace, bounded class space, and a log that survives the crash java -XX:MaxMetaspaceSize=256m \ -XX:CompressedClassSpaceSize=128m \ -XX:+HeapDumpOnOutOfMemoryError \ -XX:HeapDumpPath=/var/dumps \ -Xlog:gc*,class+unload=info:file=/var/log/jvm-gc.log:time,uptime:filecount=5,filesize=20m \ -jar app.jar

Reproduce a leak with a classloader loop, which is what a redeploy or a plugin system does without meaning to:

java
import java.net.*; public class LoaderLeak { public static void main(String[] args) throws Exception { URL url = new java.io.File("plugins/").toURI().toURL(); for (int i = 0; ; i++) { URLClassLoader loader = new URLClassLoader(new URL[]{url}); Class<?> c = Class.forName("plugin.Entry", true, loader); c.getDeclaredConstructor().newInstance(); if (i % 100 == 0) System.out.println("loaders: " + i); // loader is never closed and the instance above keeps a reference } } }

Run it with -XX:MaxMetaspaceSize=64m and the error arrives in seconds; run the same loop with loader.close() and no retained instance, and class unloading keeps the level flat.

Key Comparison Table

The OutOfMemoryError sub-messages name different memory areas and different fixes:

MessageAreaFirst thing to check
Java heap spaceHeapLive set vs -Xmx, heap dump
GC overhead limit exceededHeapAlmost-full heap, allocation rate
MetaspaceNative class metadataMaxMetaspaceSize, classloader count
Compressed class spaceNative, capped separatelyCompressedClassSpaceSize (default 1 GB)
Direct buffer memoryNative-XX:MaxDirectMemorySize, Netty/NIO buffers
unable to create native threadThread stacksulimit -u, thread count, -Xss
Requested array size exceeds VM limitHeapA single allocation larger than the heap

Metaspace-related flags and their real effect:

FlagDefaultEffect
-XX:MaxMetaspaceSizeunlimitedHard cap on class metadata; unlimited means "until native memory runs out"
-XX:MetaspaceSize~21 MB (platform dependent)First high-water mark that triggers a metaspace GC, not a cap
-XX:CompressedClassSpaceSize1 GBSeparate reservation for compressed class pointers
-XX:+UseCompressedClassPointerson for heaps under 32 GBTurning it off moves classes into Metaspace proper
-XX:MaxMetaspaceFreeRatio / MinMetaspaceFreeRatio70 / 40How aggressively metaspace is shrunk after a GC

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Finding out which limit was hit

Two commands answer the question before any code review:

bash
jcmd $(pgrep -f app.jar) VM.metaspace # Metaspace used 245120K, committed 249856K, reserved 1114112K # Non-class space: 12,5% used ... # Class space: 78,3% used ... # MaxMetaspaceSize: 256,00M jcmd $(pgrep -f app.jar) VM.metaspace summary

If used sits at MaxMetaspaceSize, the cap is the problem. If used grows steadily at a flat traffic load, it is a leak. Class space at its own cap with Metaspace left points at CompressedClassSpaceSize.

2. Counting classes per loader

jcmd <pid> GC.class_stats (with -XX:+UnlockDiagnosticVMOptions) prints class count and size by classloader name, and jmap -clstats <pid> gives the loader tree:

bash
jcmd $(pgrep -f app.jar) GC.class_stats | head -20
bash
jmap -clstats $(pgrep -f app.jar) | grep -E "class_loader|classes" | head -30

A healthy application loads tens of thousands of classes. Hundreds of thousands, or a count that rises every minute at constant traffic, is the signature of a loader created and never released.

3. The redeploy leak in a servlet container

Tomcat and similar containers reuse one JVM across deployments. A classloader is discarded only if nothing references it, and four references are almost always present:

  • a ThreadLocal value in a thread owned by the container,
  • a JDBC driver registered with DriverManager,
  • a shutdown hook registered by the application,
  • a timer or executor thread still running.
java
@WebListener public class CleanupListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent event) { Executors.newSingleThreadExecutor().shutdownNow(); // your own pools, not the container's Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); if (driver.getClass().getClassLoader() == getClass().getClassLoader()) { try { DriverManager.deregisterDriver(driver); } catch (SQLException ignored) { } } } } }

Where in-place redeploys are frequent and the leak is not worth fixing, a full JVM restart per deploy is the honest answer: metaspace is per process.

4. Dynamic code generation

Proxies, CGLIB subclasses, expression parsers, template engines and scripting runtimes all define classes at runtime. Two things turn that into an unbounded metaspace:

java
// Leak: a new enhancer and a new proxy class per request for (Request r : requests) { Enhancer e = new Enhancer(); e.setSuperclass(Handler.class); e.setCallback((MethodInterceptor) (o, m, a, p) -> m.invoke(this, a)); Handler h = (Handler) e.create(); // a new class every time } // Fix: proxy classes are per target type, so cache them private static final Class<?> PROXY = createProxyClass(Handler.class);

The second pattern is the same one Groovy and SpEL need: a class cache with an upper bound, or a shared ClassLoader for the script engine. -Xlog:class+load=info shows the generated names (Handler$$EnhancerByCGLIB$$...) and their rate.

5. Containers: heap, metaspace and the cgroup

In a pod with a 1 GiB limit, -XX:MaxRAMPercentage may already claim most of it for the heap, and metaspace plus thread stacks plus code cache then push the total over the limit. The kernel kills the process, so the log ends with exit code 137 rather than an OutOfMemoryError:

bash
# keep the heap inside the limit and reserve room for non-heap java -XX:MaxRAMPercentage=60 -XX:MaxMetaspaceSize=256m -XX:MaxDirectMemorySize=64m -jar app.jar
resources: limits: memory: "1Gi"

The mismatch to look for in a postmortem: MaxRAMPercentage=75 on a 1 GiB container with a metaspace-heavy stack, where the JVM never sees an OOM because the kernel acts first.

6. Verifying a fix

Class unloading is enabled by default, and the evidence that it works is a metaspace level that falls after a load spike, not a level that is merely lower:

bash
jstat -gcmetacapacity $(pgrep -f app.jar) 5s # MCMN MCMX MC CCSMN CCSMX CCSC

Alert on MC (metaspace capacity) against the cap rather than on the error, and keep -Xlog:class+unload=info in production: it makes the difference between "grew and stayed" and "grew and recovered" visible without a profiler.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Setting -XX:MaxMetaspaceSize=128m "to be safe". A framework-heavy stack needs more; the result is an OOM under normal load that looks exactly like a leak.
  • Confusing MetaspaceSize with MaxMetaspaceSize. The first is a high-water mark for GC, not a limit; setting it alone changes timing, not the ceiling.
  • Assuming a heap dump shows metaspace. A heap dump includes class metadata for analysis but not the native bytes; VM.metaspace and GC.class_stats are the direct measurements.
  • Raising the cap on every incident. Without a growth measurement, each bump is a smaller interval before the next page.
  • -XX:+PrintGCDetails. Removed in Java 9; unified logging (-Xlog:gc*) is the only form that still prints on a current JVM, and an old flag is silently ignored.
  • Loading a driver or library in a child loader and forgetting it. DriverManager, java.sql, and XML parsers keep static references that pin a loader after the application is undeployed.
  • Class.forName in a loop with initialize=true. Static initializers run per load, so a loader per call also runs side effects per call.
  • JIT and metaspace growth in very long runs. A JVM that never restarts accumulates compiled-code and metaspace state; scheduled restarts are legitimate for stacks with heavy dynamic dispatch.

Related tools. When the JVM is launched from a container or a systemd unit, paste the environment into the .env parser to see every JAVA_OPTS in effect — a duplicated -Xmx or a MaxRAMPercentage added by an operator overrides the one you think is running — and diff the working and failing launch scripts with the text diff tool.

Official references

primary documentation

The Java documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.