How does Metaspace trigger a memory overflow?

The following two parameters specifically set the Metaspace range size:

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

The Metaspace area is limited to 512MB:

So in the JVM, Metaspace ranges are fixed in size, such as 512 megabytes. What happens once the JVM keeps loading lots of classes and Metaspace fills up?

When the Metaspace section is Full, the Full GC will attempt to reclaim classes in the Metaspace section:

So once Metaspace is Full, the Full GC is triggered and the classes in Metaspace are reclaimed.

What kind of classes are recycled?

Conditions are demanding, including but not limited to:

  • The classloader for this class is first recycled
  • All object instances of this class are recycled

So, once your Metaspace is full, you may not be able to recycle many of its classes. What happens if it doesn’t, and the JVM is still trying to load classes into Metaspace?

Once you try to reclaim classes in Metaspace, you still don’t have much space, and you have to cram more classes into Metaspace, causing an overflow of memory. The Metaspace area is running out of memory. Once the memory runs out, the JVM can no longer run and the system may crash.

When does Metaspace run out of memory?

Metaspace rarely runs out of memory. If it does, it is usually because:

  • Many engineers don’t understand how the JVM works and use the default parameters for Metaspace when they go live. As a result, the default Metaspace range might be only a few tens of megabytes. For a larger system that has many classes of its own and relies on many external JAR packages with many classes, a few tens of megabytes of Metaspace could easily be insufficient

    Experienced engineers tend to set the Metaspace size for their online systems, and a recommended value of 512MB is generally adequate.

  • A lot of people write systems that dynamically generate classes like Cglib, but if you don’t have control in your code and you generate too many classes, it’s easy to fill up Metaspace and run out of memory

conclusion

Allocating the Metaspace area properly, while avoiding unrestricted dynamic class generation, is generally safe and does not trigger memory overflow.