java.lang.OutOfMemoryError: Java heap space

Fix Java OutOfMemoryError: Java heap space

Programming & Dev Tools Intermediate 👁 0 views 📅 May 25, 2026

This error occurs when the JVM runs out of heap memory. Increase heap size with -Xmx or optimize code to reduce memory usage.

Symptoms

Your Java application crashes with the error: java.lang.OutOfMemoryError: Java heap space. This typically happens during high load, large data processing, or memory-intensive operations. The application may become unresponsive or terminate unexpectedly.

Root Causes

  • Insufficient heap size allocated to the JVM
  • Memory leaks (objects not released for garbage collection)
  • Excessive data loading (e.g., large files, database results)
  • Improper use of caches or static collections
  • Fragmented heap due to inefficient allocation patterns

Step-by-step Fix

1. Increase Heap Size

Set maximum heap size using the -Xmx JVM argument. For example:

java -Xmx2g -jar myapp.jar

Set initial heap size with -Xms to reduce startup overhead:

java -Xms512m -Xmx4g -jar myapp.jar

2. Enable Heap Dump on OOM

Add the following JVM options to capture heap dumps for analysis:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/to/dump

3. Analyze Heap Dump

Use tools like Eclipse MAT or VisualVM to open the heap dump. Look for:

  • Large object graphs (e.g., huge collections)
  • Objects with unexpected retention (e.g., static references)
  • Thread stacks holding references

4. Optimize Code

  • Use streaming APIs instead of loading entire datasets into memory
  • Clear collections after use (e.g., list.clear())
  • Use weak references for caches where appropriate
  • Avoid creating unnecessary objects in loops

5. Tune Garbage Collection

Choose an appropriate GC algorithm:

-XX:+UseG1GC -XX:MaxGCPauseMillis=200

Alternative Fixes

  • Increase system RAM if the JVM cannot allocate the desired heap
  • Use 64-bit JVM for larger heap sizes (above 4GB)
  • Reduce thread stack size with -Xss if many threads are used
  • Implement pagination or batch processing for large data

Prevention

  • Monitor heap usage with JMX or tools like JConsole
  • Set alerts for high memory usage
  • Perform regular code reviews for memory leaks
  • Use profilers during development to detect memory issues early
  • Test with realistic data volumes in staging environments

By following these steps, you can resolve and prevent OutOfMemoryError: Java heap space in your Java applications.

Was this solution helpful?