JVM Memory Regions and OutOfMemoryErrors Explained

JVM Memory Regions

In a nutshell, the JVM (Java Virtual Machine) has the following memory regions: Inspired from

JVM Memory Regions Diagram

Types of OutOfMemoryErrors

Understanding different types of OutOfMemoryErrors is crucial for effective JVM memory management. Here are the main types:

1. OutOfMemoryError: Java Heap Space

Occurs when more objects are created in the 'Heap' (i.e., Young and Old) region than the allocated memory limit (i.e., '-Xmx').

Common Causes:

  • Increase in Traffic Volume
  • Memory Leak due to Buggy Code

2. OutOfMemoryError: GC Overhead Limit Exceeded

Thrown when the Java process spends more than 98% of its time doing garbage collection and recovering less than 2% of the heap for five consecutive garbage collections.

Common Causes:

  • Increase in Traffic Volume
  • Memory Leak due to Buggy Code

3. OutOfMemoryError: Requested Array Size Exceeds VM Limit

Occurs when trying to create an array larger than the maximum size allowed by the JVM.

4. OutOfMemoryError: Metaspace

Thrown when the Metaspace region is filled with more class definitions and method definitions than the allocated limit (i.e., '-XX:MaxMetaspaceSize').

Common Causes:

  • Creating large number of dynamic classes
  • Loading large number of classes
  • Loading large number of class loaders

5. OutOfMemoryError: Meta Space

Similar to Metaspace error, but for Java versions before Java 8.

Common Causes:

  • Creating large number of dynamic classes
  • Loading large number of classes
  • Loading large number of class loaders

6. OutOfMemoryError: Unable to Create New Native Threads

Occurs when a large number of threads are created in the native memory region, exceeding the available RAM capacity.

Common Causes:

  • Thread Leak due to Buggy Code
  • Lack of RAM capacity
  • More processes in Memory
  • Kernel Limit exceeded

7. OutOfMemoryError: Direct Buffer Memory

Thrown when too many objects are created in the direct buffer region, exceeding the allocated limit (i.e., '-XX:MaxDirectMemorySize').

Common Causes:

  • Memory Leak due to Buggy code
  • High Rate of Allocation
  • Switching from Spring RestTemplate to WebClient

8. OutOfMemoryError: Kill Process or Sacrifice Child

Occurs when there's a lack of RAM capacity in the container/device, causing the kernel to terminate memory-consuming processes.

Common Causes:

  • More processes in the device
  • Initial and Max Heap size set to different values
  • Native Memory region growing

9. OutOfMemoryError: Reason Stack Trace with Native Method

Happens when the JVM can't allocate sufficient memory for the execution stack of a thread containing native method invocations.

Common Causes:

  • Heavy Usage of Native Methods
  • Recursive Native Method Calls