Video in progress

Strong Junior ⚙️ JVM and memory

What causes OutOfMemoryError: Metaspace?

When the room for class metadata runs out: when the MaxMetaspaceSize limit is reached or the OS doesn't give more memory. Often the cause is classes being generated endlessly or ClassLoaders that were never released.

📖 Answer

An ordinary Spring Boot service fits comfortably in 100-200 MB of Metaspace. If it keeps growing without stopping, classes are being loaded but not unloaded.

A class is unloaded only when nobody references the ClassLoader that loaded it. The usual culprits:

  • redeploying an application to a server (hot redeploy): some thread or static reference holds the old application's ClassLoader, and with each deploy Metaspace fills with new classes;
  • generating classes at runtime: a new proxy on every call, recompiling a Groovy script each time, generating with CGLIB/ByteBuddy without a cache;
  • misuse of libraries that are based on reflection.

To check:

jcmd 12345 VM.metaspace          # overall state
jcmd 12345 VM.classloader_stats  # how many classes each loader has loaded
jstat -gc 12345 1000             # the MU column is Metaspace usage

If the number of classes (jcmd <pid> GC.class_histogram or LoadedClassCount in JMX) keeps growing over time, it is certainly a leak.

Rushing to remove MaxMetaspaceSize is not a solution: an unbounded Metaspace eats the container until the OOM killer.