Metaspace Explained: Sizing, Tuning, and Errors

Java applications are known for handling complex business logic and large-scale systems. As you dig deeper into Java, you’ll meet terms like “heap,” “stack,” and “Metaspace.” Heap and stack come up constantly; Metaspace usually stays mysterious—until a memory error forces you to learn it. This post covers what Metaspace is, why Java 8 introduced it, how class unloading actually works, and how to tune and diagnose it in production.

What Is Java Metaspace?

Metaspace is the region where the JVM stores class metadata at runtime: class structures, method bytecode, field descriptors, constant pools, annotations, and the class loader references that keep them alive. It replaced the older Permanent Generation (PermGen) in Java 8.

Two properties matter most:

  • It holds class definitions, not object data. Instances of your classes still live in the heap. Metaspace describes the shape of the class, not the objects created from it.
  • It lives in native memory, outside the Java heap. Metaspace is allocated from the process’s native memory, not from -Xmx. That means raising the heap does nothing for a Metaspace problem, and setting -Xmx does not cap Metaspace.

Why Java Introduced Metaspace

Before Java 8, class metadata lived in PermGen, a fixed-size region inside the heap. PermGen had two painful properties: you had to guess its size up front (-XX:MaxPermSize), and a wrong guess produced java.lang.OutOfMemoryError: PermGen space at a random moment—often during class loading under load. Redeploying a web app without a JVM restart frequently triggered it, because the old class loader and its classes were never reclaimed.

Metaspace fixed these issues:

  • It grows on demand using native memory. The default maximum is limited only by available RAM, not by a heap setting.
  • Class metadata can be unloaded when the class loader that defined it becomes unreachable, provided the collector runs a full GC that supports class unloading.
  • Configuration is optional. Defaults work for most applications. You cap the size only when you need a hard ceiling.

How Metaspace Works

When your application starts, the JVM loads every class it needs and stores metadata for each in Metaspace. As more classes load—through frameworks that generate classes at runtime (Spring proxies, Hibernate enhancers, JSON libraries, scripting engines)—Metaspace grows to accommodate them.

Three behaviors to understand:

  • Growth is lazy and incremental. Metaspace grabs native memory in chunks as new classes appear, and never shrinks the reserved arena back to the OS. Freed memory is reused for future classes, so a peak value stays visible in monitoring even after classes are unloaded.
  • Class unloading requires a full GC. G1, Parallel, and Serial all unload classes during a full GC, but a young-only collection does not. An application that never triggers a full GC—common with a well-tuned G1—can hold onto unreachable class loaders for hours.
  • Exhaustion throws OutOfMemoryError: Metaspace. If Metaspace cannot expand because it hit -XX:MaxMetaspaceSize (or the OS ran out of memory), you get this error, and no amount of heap tuning will help.

Metaspace vs Heap vs PermGen

Metaspace, heap, and PermGen compared
Property Metaspace Heap PermGen (pre-Java 8)
Stores Class metadata Java objects and arrays Class metadata and interned strings
Memory area Native (off-heap) Reserved by the JVM Inside the heap
Size limit Unlimited by default; capped by -XX:MaxMetaspaceSize Capped by -Xmx Capped by -XX:MaxPermSize
Class unloading Yes, on full GC when the loader is unreachable Not applicable Yes, but unreliable in practice

Tuning Metaspace

Most applications never need to touch these flags. When you do, know what each one means:

  • -XX:MaxMetaspaceSize=512m caps Metaspace. Without this, the JVM will keep asking the OS for more native memory and can trigger the OS OOM killer instead of a Java exception—which is worse, because the JVM dies without a stack trace.
  • -XX:MetaspaceSize=128m is not an initial allocation. It sets the first high-water mark that triggers a full GC to attempt class unloading. Setting it higher delays the first unloading cycle; setting it too high wastes memory but does not cause an error.
  • -XX:CompressedClassSpaceSize=1g caps the compressed class space (a virtual reservation inside Metaspace used for compressed oops). The default is 1 GB; unless you get OutOfMemoryError: Compressed class space, leave it alone.

A safe production baseline for a mid-size service:

-XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m

Watch the actual peak for a week before setting these. A cap that is too tight turns a memory issue into an outage; a cap that is too loose is the same as having no cap.

Diagnosing OutOfMemoryError: Metaspace

If you hit this error, the question is almost never “Metaspace is too small.” It is usually “something is loading classes forever.” Common causes:

  • Class loader leaks in application servers. Every redeploy creates a new web app class loader, and the old one stays reachable through a lingering reference—often a ThreadLocal, a JDBC driver registered with DriverManager, or a shutdown hook. Each leak adds a full set of class metadata.
  • Runtime code generation without caching. Frameworks like Groovy, SpEL, or JAXB can generate a new class for every unique expression evaluated.
  • Reflection-heavy frameworks building proxies per request.

Three tools that will tell you exactly what is happening:

# Current Metaspace usage and the number of loaded classes
jcmd <pid> VM.metaspace

# Metaspace capacity and committed size over time
jstat -gcmetacapacity <pid> 1s

# Track native memory allocations by category
java -XX:NativeMemoryTracking=summary ...
jcmd <pid> VM.native_memory summary

If jcmd VM.metaspace shows a steadily rising class count with no drops after a full GC, you have a leak. If it shows high usage that drops on full GC, you simply need a larger cap or more frequent full GCs—which is a symptom, not a fix.

To confirm a full GC does not release metadata, force one and check again:

jcmd <pid> GC.run
jcmd <pid> VM.metaspace

If the numbers do not move, the classes are still reachable—find the reference, do not raise the cap.

Best Practices

  • Avoid class loader leaks. Null out ThreadLocal values on shutdown, deregister JDBC drivers, and clear static caches in a ServletContextListener or @PreDestroy method. This matters most for applications that redeploy without restarting the JVM.
  • Set MaxMetaspaceSize, not MetaspaceSize, as your safety net. The cap catches runaway class loading early instead of letting the OS kill the process.
  • Monitor class count, not just Metaspace size. A rising LoadedClassCount after a full GC is the earliest signal of a leak. Both JVisualVM and Java Flight Recorder expose it.
  • Do not raise the cap as the first response. If the class count keeps growing, a larger cap only buys time. Fix the reference that keeps the loader alive.
  • Remember Metaspace lives outside the heap. -Xmx2g plus -XX:MaxMetaspaceSize=512m plus code cache plus thread stacks plus direct buffers is your real footprint. Size your container limit accordingly, or the pod gets OOM-killed while the JVM reports plenty of free heap.

In Simple Terms

Think of Metaspace as the filing cabinet where the JVM keeps every class it has loaded. Your actual objects live in a different cabinet—the heap. As more classes load, the cabinet grows, and the JVM occasionally empties a drawer that nothing references anymore. But the cabinet lives in the building’s storage (native memory), not in the room you budgeted for the heap. If you never let anyone empty it, or you keep adding new cabinets without removing old ones, the building runs out of space—and the error you see is OutOfMemoryError: Metaspace, not a heap error. Monitor the cabinet, unload what you no longer need, and set a size limit so a leak fails fast instead of taking down the whole process.

Conclusion

Metaspace is a cleaner design than PermGen—it grows when needed, supports class unloading, and needs almost no tuning. The trade-offs are that it uses native memory you might not be watching, and it can grow without limit if a class loader leaks. Set -XX:MaxMetaspaceSize as a safety net, watch the loaded class count in production, and when you hit an OutOfMemoryError, investigate the cause before you raise the cap.

Comments