OutOfMemoryError in Java

OutOfMemoryError occurs when the JVM cannot allocate memory for new objects. It usually happens due to memory leaks, excessive object creation, or improper memory configuration.


1. Heap Space OutOfMemoryError

This occurs when the Java heap is full and no more objects can be allocated.


import java.util.*;

public class HeapOOM {

    public static void main(String[] args) {

        List list = new ArrayList<>();

        while(true){
            list.add(new int[1000000]);
        }

    }

}
Real-world example: Caching large datasets in memory without eviction strategy.
Solutions:
  • Increase heap size (-Xmx)
  • Use caching frameworks with eviction (LRU)
  • Avoid storing unnecessary objects

2. Metaspace OutOfMemoryError

Occurs when the JVM runs out of memory storing class metadata.


while(true){
    ClassLoader loader = new CustomClassLoader();
    loader.loadClass("ExampleClass");
}
Real-world example: Applications generating many dynamic classes (proxies, bytecode frameworks).
Solutions:
  • Increase metaspace size
  • Fix classloader leaks
  • Use proper class unloading

3. GC Overhead Limit Exceeded

This error occurs when JVM spends most of its time performing garbage collection but recovers very little memory.


Map map = new HashMap<>();

for(int i=0; i

Real-world example: Memory leak caused by continuously growing collections.

Soutions:
  • Identify memory leaks
  • Use profiling tools
  • Remove unused references

 


4. Direct Buffer Memory Error

Occurs when too much direct memory is allocated outside the heap.


ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024 * 1024);

Real-world example: High-performance systems using NIO buffers.

Solutions:
  • Limit direct memory usage
  • Use buffer pooling
  • Configure MaxDirectMemorySize


5. Unable to Create New Native Thread

Occurs when the system cannot create more threads.


while(true){
    new Thread(() -> {
        try{
            Thread.sleep(1000000);
        }catch(Exception e){}
    }).start();
}

Real-world example: Applications creating too many threads instead of using thread pools.

Solutions:

 

  • Use thread pools
  • Limit concurrent threads
  • Use virtual threads in modern Java


Real Production Troubleshooting Steps

 

  • Enable heap dumps
  • Analyze memory with profiling tools
  • Check object retention
  • Monitor GC behavior

Common tools used in production:

 

  • VisualVM
  • JProfiler
  • Eclipse MAT
  • GC logs


Quick Summary

 

  • Heap Space Error
  • Metaspace Error
  • GC Overhead Limit Exceeded
  • Direct Buffer Memory Error
  • Unable to Create Native Thread

Understanding these errors helps developers design scalable and memory-efficient applications.

0 comments

Leave a comment