java.lang.OutOfMemoryError: Java heap space

Fix Java OutOfMemoryError: Java heap space

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

Learn how to diagnose and resolve the Java OutOfMemoryError for heap space. This guide covers root causes, step-by-step fixes, and prevention strategies for both development and production environments.

Symptoms

When a Java application runs out of heap memory, it throws the following error in the console or logs:

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

Additional symptoms include:

  • Application freezes or crashes unexpectedly.
  • High CPU usage due to excessive garbage collection (GC).
  • Slow response times and degraded performance.
  • In production, the application may stop serving requests or restart automatically.

Root Causes

The Java heap is the memory area where objects are allocated. The error occurs when the JVM cannot allocate an object because the heap is full and garbage collection cannot reclaim enough space. Common causes include:

  • Insufficient heap size: The default heap size (often 256MB or 512MB) is too small for the application's workload.
  • Memory leak: Objects are unintentionally held in memory (e.g., by static collections, listeners, or caches) and never garbage collected.
  • Large data processing: Loading huge files, datasets, or images into memory without streaming or batching.
  • Too many threads: Each thread consumes stack memory, but thread-local objects can also fill the heap.
  • Improper GC tuning: GC configuration may not match the application's allocation patterns, causing fragmentation or long pause times.

Step-by-Step Fix

Step 1: Increase Heap Size

Modify the JVM startup parameters to allocate more heap memory. For example:

java -Xms512m -Xmx2048m -jar myapp.jar
  • -Xms: Initial heap size (e.g., 512 MB).
  • -Xmx: Maximum heap size (e.g., 2048 MB).

Set -Xms equal to -Xmx to avoid resizing overhead. Monitor memory usage to find a suitable value.

Step 2: Generate and Analyze Heap Dump

Add the following JVM flags to capture a heap dump when the error occurs:

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

Analyze the dump using tools like Eclipse MAT or VisualVM:

  1. Open the .hprof file in Eclipse MAT.
  2. Run the Leak Suspects report to identify objects consuming the most memory.
  3. Look for unexpected large collections, class instances, or retained objects.

Step 3: Fix Memory Leaks

Common fixes include:

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

Step 4: Optimize Code and Data Handling

  • Process large files line by line instead of loading entire file into memory.
  • Use pagination for database queries.
  • Stream data with Java 8 Streams or reactive libraries.
  • Reduce object creation by reusing objects or using primitives where possible.

Step 5: Tune Garbage Collection

Choose the right GC algorithm based on application needs:

  • G1GC: Good for large heaps (>4GB) and low pause times. Use -XX:+UseG1GC.
  • Parallel GC: Best for throughput-oriented batch jobs. Use -XX:+UseParallelGC.
  • ZGC: Low-latency GC for very large heaps (experimental).

Additional tuning flags:

-XX:NewRatio=3 -XX:SurvivorRatio=8 -XX:+UseStringDeduplication

Alternative Fixes

  • Restart the application periodically to clear memory (temporary workaround).
  • Use a memory profiler in development (e.g., JProfiler, YourKit) to catch leaks early.
  • Reduce thread count or use a thread pool with bounded queue.
  • Switch to a 64-bit JVM to access larger heap sizes.

Prevention

  • Set realistic heap limits based on load testing and monitoring.
  • Implement automated heap dump analysis in CI/CD pipelines.
  • Use monitoring tools (Prometheus, Grafana) to track heap usage and GC activity.
  • Conduct regular code reviews focusing on memory management.
  • Enable GC logging (-Xlog:gc*) to detect trends early.

By following these steps, you can effectively resolve and prevent Java heap space errors, ensuring stable and performant applications.

Was this solution helpful?