October 5, 2022

Robotic Notes

All technology News

Chaos Engineering – Metaspace OutOfMemoryError – Java Code Geeks

2 min read

The JVM memory has the following regions:

a. Young generation

b. Old generation

° C. Metaspace

e. Other region

When you encounter “java.lang.OutOfMemoryError: Metaspace”, it indicates that the Metaspace region of the JVM memory is getting full. Metaspace is the region where metadata details that are required to run your application are stored. In short, they contain class definitions and method definitions of your application. To learn more about what is stored in each of the JVM memory areas, you can refer to this video. In this post, let’s discuss how java.lang.OutOfMemoryError: Metaspace can be simulated.

Simulate java.lang.OutOfMemoryError: metaspace

To simulate “java.lang.OutOfMemoryError: Metaspace”, we wrote this program:

public class MetaspaceLeakProgram 
   public static void main(String[] args) throws Exception 
      ClassPool classPool = ClassPool.getDefault();

      while (true) 
         // Keep creating classes dynamically!
         String className = "com.buggyapp.MetaspaceObject" + UUID.randomUUID();

This program uses the “ClassPool” object from the javassist open source library. This “ClassPool” object can create new classes at runtime. Please review the above program carefully. If you notice, this program keeps creating new classes. Below are sample class names generated by this program:


Whenever a new class is created, its corresponding class metadata definitions are created in the JVM’s metaspace area. As metadata definitions are created in Metaspace, their size begins to grow. When the maximum metaspace size is reached, the application will experience ‘java.lang.OutOfMemoryError: Metaspace’

java.lang.OutOfMemoryError: Metaspace causes

A “java.lang.OutOfMemoryError: Metaspace” error occurs for two reasons:

a. The size of the metaspace region is under-distributed

b. Memory leak in metaspace region.

You can address #a by increasing the size of the Metaspace region. You can do this by passing the JVM argument ‘-XX:Maximum metaspace size‘.

To address #b you need to do proper troubleshooting. Here is a post that describes how to fix a memory leak in the Metaspace region.


Source link