java.lang.OutOfMemoryError: Java heap space

Fixing 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. Common causes include memory leaks, insufficient heap allocation, or excessive data processing. Fixes involve increasing heap size, optimizing code, or profiling memory usage.

Symptoms

When a Java application encounters an OutOfMemoryError: Java heap space, it typically crashes with a stack trace. Symptoms include:

  • Application freezes or terminates unexpectedly.
  • Error message in logs: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space.
  • Gradual performance degradation before the crash.
  • High memory usage visible in system monitoring tools (e.g., top, Task Manager).

Root Causes

The error indicates the JVM cannot allocate more objects in the heap. Common causes:

  1. Insufficient heap size: Default heap (e.g., 256MB) is too small for the application’s workload.
  2. Memory leak: Objects are unintentionally held in memory (e.g., static collections, unclosed resources).
  3. Excessive data processing: Loading large datasets (e.g., huge files, database results) into memory.
  4. Improper garbage collection: Long-lived objects or inefficient GC tuning.
  5. Third-party libraries: Memory-intensive libraries without proper configuration.

Step-by-Step Fix

1. Increase JVM Heap Size

Set maximum heap size using -Xmx and initial heap with -Xms. Example:

java -Xms512m -Xmx2048m -jar myapp.jar

Adjust values based on available system memory. For production, set -Xms equal to -Xmx to avoid resizing overhead.

2. Generate Heap Dump

Add JVM flags to capture heap dump on OOM:

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

Analyze the dump with tools like Eclipse MAT or VisualVM to find memory leaks.

3. Profile Memory Usage

Use jconsole or jvisualvm (included in JDK) to monitor heap usage in real-time. Identify which objects consume memory.

4. Fix Memory Leaks

Common fixes:

  • Clear static collections when no longer needed.
  • Use WeakReference or SoftReference for caches.
  • Close resources (streams, connections) in finally blocks or use try-with-resources.
  • Remove unused listeners or callbacks.

5. Optimize Code

  • Process data in streams (e.g., Files.lines() instead of reading entire file).
  • Use pagination for database queries.
  • Avoid creating unnecessary objects (e.g., use StringBuilder).

6. Tune Garbage Collection

Choose appropriate GC algorithm (e.g., G1GC for large heaps):

-XX:+UseG1GC -XX:MaxGCPauseMillis=200

Alternative Fixes

  • Reduce heap usage: Lower -Xmx if the error occurs due to GC overhead (e.g., with GC overhead limit exceeded).
  • Use 64-bit JVM: Allows larger heap sizes (above 4GB).
  • Switch to native memory: For very large data, consider off-heap storage (e.g., java.nio.ByteBuffer).
  • Upgrade hardware: Add more RAM to the server.

Prevention

  • Set appropriate -Xms and -Xmx based on load testing.
  • Implement monitoring (e.g., JMX, Prometheus) to alert on high memory usage.
  • Conduct regular code reviews to catch memory leaks early.
  • Use memory-efficient data structures (e.g., ArrayList vs LinkedList).
  • Enable GC logs: -Xlog:gc* (Java 9+) for analysis.
  • Test with realistic data volumes in staging.

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

Was this solution helpful?