Metaspace OOM: Top 3 Causes & Fixes
The `java.lang.OutOfMemoryError: Metaspace` error, which replaced `PermGen space` in Java 8, is primarily caused by classloader leaks from hot deployments, excessive dynamic class generation via reflection or scripting, or an insufficient maximum Metaspace size configured with `-XX:MaxMetaspaceSize`.
The top 3
- Top Fix: MaxMetaspaceSize Adjustments: The most common Metaspace OOM cause is an under-allocated size. Increase the JVM's maximum Metaspace via `-XX:MaxMetaspaceSize=<size>` (e.g., `512m`) as a primary solution. While Metaspace auto-grows, setting an explicit, larger cap prevents exhaustion from normal application growth.
- Dynamic Class Loading: Identify Bloat Sources: Excessive dynamic class creation (e.g., using Java Reflection, Groovy scripting, or large third-party libraries) or numerous class loaders can rapidly consume Metaspace. Diagnose by enabling `-verbose:class` (Java 8 and below) or `-XX:ClassLoadFile=<filename>` (Java 9+) to log loaded classes and identify the culprits.
- Metaspace Memory Leaks: Deep Dive with Heap Dumps: True Metaspace memory leaks, though rarer, occur when class definitions are not garbage collected due to lingering references, often caused by custom class loaders or application design flaws. This requires capturing a heap dump (e.g., with `-XX:+HeapDumpOnOutOfMemoryError`) and analyzing it with tools like HeapHero or Eclipse MAT to pinpoint the leaking objects and class loaders.
Sources
Open the full topic