java.lang.OutOfMemoryError: Java heap space

Fix Java OutOfMemoryError: Java heap space

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

Java heap space OutOfMemoryError occurs when the JVM cannot allocate more objects in the heap. This guide covers symptoms, root causes, and step-by-step fixes including increasing heap size and memory leak detection.

Symptoms

When a Java application runs out of heap space, you will typically see the following error in the console or log files:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

Additional symptoms include:

  • Application freezes or crashes unexpectedly
  • Extremely slow performance due to excessive garbage collection (GC)
  • Error messages like java.lang.OutOfMemoryError: GC overhead limit exceeded may precede the heap space error
  • For web applications, HTTP 500 errors or blank pages

Root Causes

The JVM heap is the memory area where all object instances and arrays are allocated. The error occurs when the heap reaches its maximum size and no more objects can be allocated. Common causes include:

  1. Insufficient heap size – The default heap size (often 256MB) is too small for the application's workload.
  2. Memory leak – Objects are unintentionally held in memory (e.g., static collections, listeners not unregistered), preventing garbage collection.
  3. Large data sets – Loading huge files, database results, or in-memory caches without proper streaming or pagination.
  4. Excessive object creation – Inefficient code creating many short-lived objects, causing frequent GC but not enough freed space.
  5. Fragmentation – In rare cases, heap fragmentation prevents allocation of contiguous blocks even if total free memory is sufficient.

Step-by-Step Fix

1. Increase JVM Heap Size

Set the initial (-Xms) and maximum (-Xmx) heap size. For a server with 8GB RAM, a typical setting is:

java -Xms512m -Xmx4g -jar myapp.jar

For Tomcat, edit CATALINA_OPTS in setenv.sh:

export CATALINA_OPTS="-Xms512m -Xmx4g"

For Eclipse, edit eclipse.ini:

-Xms256m
-Xmx1024m

Note: Do not set -Xmx larger than available physical RAM to avoid swapping.

2. Generate a Heap Dump for Analysis

Add JVM flags to capture heap dump on OOM:

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

When the error occurs, a .hprof file is created. Analyze it with tools like Eclipse MAT (Memory Analyzer) or VisualVM.

3. Analyze Memory Leak with Eclipse MAT

  1. Open the heap dump in Eclipse MAT.
  2. Run the Leak Suspects Report (found under Reports menu).
  3. Look for objects with high retained heap sizes, especially collections (HashMap, ArrayList) that keep growing.
  4. Inspect the GC root paths to identify what holds references to these objects.
  5. Fix the code: nullify references, use weak references, or clear collections when no longer needed.

4. Optimize Garbage Collection

Choose the right GC algorithm based on your application:

GC TypeFlagBest For
G1 GC (default since Java 9)-XX:+UseG1GCLarge heaps, low pause times
Parallel GC-XX:+UseParallelGCHigh throughput, batch processing
ZGC (Java 11+)-XX:+UseZGCVery large heaps, sub-millisecond pauses

5. Reduce Object Allocation

  • Use StringBuilder instead of string concatenation in loops.
  • Stream large files instead of reading entire content into memory.
  • Use primitive collections (e.g., Trove, Eclipse Collections) to reduce overhead.
  • Reuse objects with object pools if creation is expensive.

Alternative Fixes

  1. Increase swap space – Not recommended as it degrades performance, but can buy time.
  2. Distribute workload – Use multiple JVM instances or microservices to spread memory usage.
  3. Reduce data retention – Implement pagination in database queries, limit result sets.
  4. Use off-heap storage – For caches, consider technologies like Redis or Ehcache with off-heap store.

Prevention

  • Monitor heap usage with tools like JConsole, VisualVM, or Grafana/Prometheus with JMX exporter.
  • Set up alerts when heap usage exceeds 80% of maximum.
  • Conduct regular code reviews to spot potential memory leaks (e.g., unclosed resources, static collections).
  • Use static analysis tools (FindBugs, SonarQube) to detect memory issues early.
  • Load test your application with realistic data volumes before production deployment.
  • Keep Java and libraries updated to benefit from GC improvements.

By following these steps, you can effectively diagnose and resolve the Java heap space OutOfMemoryError, ensuring your applications run reliably under load.

Was this solution helpful?