Sub topic 8
Metaspace and Class Metadata
This chapter assumes you know what the heap is, how GC roots make objects reachable, and how to run java and jcmd from a terminal. It covers where the JVM stores class definitions, how that area grows and shrinks, and how to diagnose OutOfMemoryError: Metaspace.
What class metadata is
When the JVM loads a class, it parses the .class bytes into an internal runtime form. That form includes:
- the constant pool
- field and method descriptors
- the bytecode of each method
- annotations
- the method tables used for virtual dispatch
- data the JIT compiler and interpreter use, such as method counters
This is class metadata. It is not the same as the java.lang.Class object your code sees. The two halves live in different places:
| Item | Location | Managed by |
|---|---|---|
| `java.lang.Class` object (the "mirror") | Java heap | Garbage collector like any other object |
| Static field values | Inside the mirror, on the heap | Garbage collector |
| Interned strings | Java heap (since JDK 7) | Garbage collector |
| Method bytecode, constant pool, field and method structures | Metaspace (native memory) | Metaspace allocator, freed on class unloading |
| Compiled JIT code | Code cache (native memory) | The JIT compiler and sweeper |
Each mirror points to its metadata, and the metadata points back to the mirror. A class is therefore split across the heap and native memory. This split explains most metaspace behavior.
Metaspace versus PermGen
Before JDK 8, class metadata lived in the permanent generation (PermGen). PermGen was part of the Java heap, had a fixed maximum (-XX:MaxPermSize), and was collected together with the old generation. Sizing it was a common chore, and OutOfMemoryError: PermGen space was a common failure.
JDK 8 removed PermGen and introduced Metaspace. Metaspace is allocated from native memory, outside the heap. By default it can grow until the operating system refuses more memory. Because it is no longer part of the heap, -Xmx does not limit it. -XX:MaxMetaspaceSize does.
How metaspace allocates memory
Metaspace is organized per class loader. Each loader gets its own arena. The arena takes chunks of memory from the virtual space as its classes are loaded. The JVM does not free a class's metadata one class at a time. It frees the whole arena at once, when the class loader that owns it is unloaded.
This has three consequences:
- Loading a class costs metaspace, and nothing short of unloading its loader gives that memory back to the JVM.
- A loader that loads few classes can still hold a minimum-size chunk. Programs that create thousands of tiny loaders can use more metaspace than the class count suggests.
- Freed chunks can be reused by other loaders. Returning memory to the operating system is more conservative and depends on fragmentation.
Compressed class space
On 64-bit JVMs, -XX:+UseCompressedClassPointers is on by default. The JVM stores the main per-class structure (the Klass) in a separate region called the compressed class space. Object headers can then refer to it with a 32-bit value instead of a 64-bit pointer. This saves heap memory on every object.
The compressed class space is reserved up front. Its size is set by -XX:CompressedClassSpaceSize, which defaults to 1 GB. Method bytecode, constant pools, and other data go in the non-class part of metaspace. Because the two parts have separate limits, you can see two different error messages. They appear under "Understanding the failure" below.
Flags that control metaspace
| Flag | Meaning | Default |
|---|---|---|
| `-XX:MetaspaceSize=<size>` | Metaspace usage at which the first GC for class unloading is triggered. It is not a minimum or initial reservation. | About 21 MB (platform dependent) |
| `-XX:MaxMetaspaceSize=<size>` | Hard limit on metaspace. | Unlimited |
| `-XX:MinMetaspaceFreeRatio=<n>` | After a GC, grow the threshold if free space is below this percentage. | 40 |
| `-XX:MaxMetaspaceFreeRatio=<n>` | After a GC, shrink the threshold if free space is above this percentage. | 70 |
| `-XX:CompressedClassSpaceSize=<size>` | Size of the compressed class space. | 1 GB |
The JVM treats MetaspaceSize as a high-water mark. When usage crosses it, the JVM starts a collection so that unreachable class loaders can be unloaded. After that collection, the JVM adjusts the mark using the free-ratio flags. The GC log labels these collections "Metadata GC Threshold".
An application that loads many classes at startup, such as a large framework, can trigger several of these early collections as the mark rises step by step. Raising -XX:MetaspaceSize to a value near your normal steady-state usage avoids them. It does not change the maximum.
When classes are unloaded
A class is unloaded only when its defining class loader becomes unreachable. The JVM can free metadata for a single class only if all of the following hold:
- No instance of the class is reachable.
- The class's
Classobject is not reachable. - The class loader that defined it is not reachable.
Because the mirror references the loader, and the loader references every class it defined, they are collected as a group. Classes loaded by the bootstrap, platform, and application loaders are effectively never unloaded, because those loaders live as long as the JVM.
Only loaders you create can have their classes unloaded. Examples include the per-application loaders in a servlet container, plugin systems, OSGi bundles, and code that generates classes at runtime.
Observing metaspace from Java
The JVM exposes metaspace through memory pool beans. This program prints their usage:
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
public class PoolInfo {
public static void main(String[] args) {
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
String name = pool.getName();
if (name.contains("Metaspace") || name.contains("Compressed Class")) {
MemoryUsage u = pool.getUsage();
String max = u.getMax() < 0 ? "unlimited" : (u.getMax() / 1024) + " KB";
System.out.println(name + ": used=" + u.getUsed() / 1024
+ " KB, committed=" + u.getCommitted() / 1024
+ " KB, max=" + max);
}
}
}
}On a default JVM, "Metaspace" reports a max of unlimited and "Compressed Class Space" reports a max near 1 GB. Run it again with -XX:MaxMetaspaceSize=64m and the first line changes.
Reproducing a class loader leak
The next program defines the same class again and again, each time in a new class loader. With no argument, it drops each class right away. With the argument keep, it holds the Class objects in a list, which keeps every loader reachable.
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class MetaspaceLeak {
static class Payload { }
static class IsolatedLoader extends ClassLoader {
IsolatedLoader() {
super(null); // parent is the bootstrap loader, so nothing is shared
}
Class<?> define(String name) throws Exception {
String resource = name.replace('.', '/') + ".class";
try (InputStream in = MetaspaceLeak.class.getClassLoader()
.getResourceAsStream(resource)) {
byte[] bytes = in.readAllBytes();
return defineClass(name, bytes, 0, bytes.length);
}
}
}
public static void main(String[] args) throws Exception {
boolean keep = args.length > 0 && args[0].equals("keep");
List<Class<?>> held = new ArrayList<>();
String name = Payload.class.getName();
for (int i = 1; i <= 200_000; i++) {
Class<?> c = new IsolatedLoader().define(name);
if (keep) {
held.add(c);
}
if (i % 20_000 == 0) {
System.out.println("Defined " + i + " classes");
}
}
System.out.println("Done");
}
}Compile it, then run both variants with a small limit:
javac MetaspaceLeak.java
java -XX:MaxMetaspaceSize=32m -Xlog:gc MetaspaceLeak
java -XX:MaxMetaspaceSize=32m -Xlog:gc MetaspaceLeak keepThe first run finishes. The GC log shows collections whose cause is "Metadata GC Threshold", and each one unloads the abandoned loaders. The second run stops with java.lang.OutOfMemoryError: Metaspace, because every loader stays reachable through the Class object that held references.
Nothing in the second program looks like a leak at first glance. It is just a list of classes. The problem is that a Class object keeps its entire loader, and the loader's whole arena, alive.
Common causes of metaspace growth
- Redeploying in an application server. The old application's class loader should become garbage after undeploy. If something outside the application still references it, the old classes stay and each redeploy adds another copy. Typical holders are a static field in a shared library, a
ThreadLocalvalue on a server thread, a JDBC driver registered withDriverManager, a shutdown hook, and a thread the application started and never stopped. - Runtime class generation. Proxy and bytecode libraries create classes on the fly. If your code generates a new class for each request, or creates a new proxy factory each time instead of reusing one, metaspace grows without bound.
- Reflection and lambdas. Reflective calls can generate accessor classes after a threshold of invocations. Lambdas create classes at first use. These are bounded in normal code. They only become a problem when combined with a loader that never unloads.
- Too small a limit. A large application can legitimately need hundreds of megabytes of class metadata. A low
MaxMetaspaceSizethen fails a healthy program.
Understanding the failure
When metaspace runs out, the JVM first runs a collection to try to unload classes. If that frees too little, it throws OutOfMemoryError with one of two messages:
java.lang.OutOfMemoryError: Metaspacemeans the non-class part of metaspace hitMaxMetaspaceSize, or native memory ran out.java.lang.OutOfMemoryError: Compressed class spacemeans the compressed class space is full. This can happen with a very large number of loaded classes even when plenty of non-class metaspace is free. Increase-XX:CompressedClassSpaceSizeor fix the class count.
The heap is not the problem in either case, so raising -Xmx does not help.
Diagnosing metaspace problems
Start with the tools you already know, then add a few that target class loading:
# Metaspace and class space lines in the heap summary
jcmd <pid> GC.heap_info
# Per-loader breakdown of metaspace usage (JDK 11 and later)
jcmd <pid> VM.metaspace
# Number of classes and size per class loader
jcmd <pid> VM.classloader_stats
# Log every class load and unload
java -Xlog:class+load,class+unload=info MyApp
# Track native memory by category, including class metadata
java -XX:NativeMemoryTracking=summary MyApp
jcmd <pid> VM.native_memory summaryVM.classloader_stats is usually the fastest route to the cause. Many loaders with the same name, or a loader count that rises with each redeploy, points straight at the leak. To find what holds a loader, take a heap dump with -XX:+HeapDumpOnOutOfMemoryError. The dump contains the ClassLoader and Class objects, which are on the heap, and a heap analyzer can show the reference path from a GC root to each one. The dump does not contain the metaspace contents themselves.
Key points
- Class metadata lives in Metaspace, which is native memory. The
Classobject and static fields live on the heap. -Xmxdoes not limit metaspace.-XX:MaxMetaspaceSizedoes, and it is unlimited by default.-XX:MetaspaceSizeis a GC trigger threshold, not an initial size or a cap.- Metadata is freed per class loader, and only when the loader, its classes, and their instances are all unreachable.
- Class loader leaks, not heap leaks, cause most
OutOfMemoryError: Metaspacefailures.
Exercise
A service runs in a container with a 1 GB memory limit and -Xmx512m. After several hot redeploys, the container is killed by the operating system, and the logs show no OutOfMemoryError. What is the likely cause, and which flag would turn the silent kill into a diagnosable Java error?
Show answer
Each redeploy probably leaves the old application's class loader reachable, so its classes stay in metaspace. Metaspace is native memory outside -Xmx and is unlimited by default, so total process memory grows until the container limit is hit and the operating system kills the process. Setting -XX:MaxMetaspaceSize (for example 256m) makes the JVM throw OutOfMemoryError: Metaspace at that limit instead, which gives a stack trace and lets you inspect the leak with jcmd <pid> VM.classloader_stats.
Exercise
In the MetaspaceLeak program, why does the run without keep succeed while the run with keep fails, even though both define exactly the same number of classes?
Show answer
Without keep, nothing references the Class object or its IsolatedLoader after each iteration, so both become unreachable. When used metaspace crosses the threshold, a collection unloads those loaders and frees their arenas. With keep, the list holds every Class object, each Class object references its loader, and the loader owns the metaspace arena. No loader becomes unreachable, so nothing can be unloaded and metaspace reaches MaxMetaspaceSize.