java runtime_error ai_generated true

java.lang.OutOfMemoryError: Metaspace

ID: java/outofmemoryerror-metaspace

Also available as: JSON · Markdown
80%Fix Rate
85%Confidence
60Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
17 active

Root Cause

OutOfMemoryError: Metaspace is thrown when the JVM runs out of native memory allocated for class metadata. This typically occurs due to classloader leaks, excessive dynamic class generation (e.g., via reflection proxies, CGLIB, Groovy scripts), or too many classes being loaded in the application.

generic

Workarounds

  1. 82% success Identify and fix the classloader leak using JVM diagnostic tools
    1. Add -verbose:class to JVM args to log class loading/unloading. 2. Monitor Metaspace usage with 'jstat -gc <pid>'. 3. Take a heap dump and analyze classloader instances in Eclipse MAT — look for duplicate classloaders or classloaders with unexpectedly many loaded classes. 4. Common culprits: ThreadLocal values holding references to webapp classloaders, JDBC driver registration not cleaned up on undeploy, logging frameworks caching classloader references. 5. Fix by properly cleaning up resources in servlet context listeners or @PreDestroy methods.
  2. 78% success Reduce dynamic class generation by using method handles or interface-based proxies instead of CGLIB/byte-code generation
    1. If using Spring, prefer JDK dynamic proxies (interface-based) over CGLIB proxies: set spring.aop.proxy-target-class=false. 2. If using Groovy/scripting, cache compiled scripts instead of recompiling on each invocation. 3. For reflection-heavy code, use java.lang.invoke.MethodHandle instead of Method.invoke() — MethodHandles use less Metaspace. 4. Set -XX:MaxMetaspaceSize to a reasonable limit (e.g., 256m-512m) so leaks surface quickly rather than consuming all system memory.

Dead Ends

Common approaches that don't work:

  1. Increasing -XX:MaxMetaspaceSize without investigating the classloader leak 65% fail

    If the root cause is a classloader leak (common in application server redeployments or dynamic scripting), increasing Metaspace only delays the inevitable. Leaked classloaders prevent their classes from being unloaded, and Metaspace will eventually fill regardless of size.

  2. Restarting the application on a schedule to avoid the OOM 75% fail

    Scheduled restarts are an operational band-aid. They cause downtime, data loss in in-flight requests, and do not address the underlying leak. As the application grows or traffic increases, the restart interval shrinks until restarts become impractical.

Error Chain

Leads to:
Preceded by:
Frequently confused with: