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 insufficient heap allocation, memory leaks, or excessive data processing. Solutions involve increasing heap size, optimizing code, and profiling memory usage.

Symptoms

The application crashes with the error message java.lang.OutOfMemoryError: Java heap space. This typically appears in server logs, console output, or stack traces. The application may become unresponsive, slow, or fail to allocate new objects. In web applications, users may see HTTP 500 errors or timeouts.

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 is often too small for production workloads.
  • Memory leak: Objects are unintentionally held by references and never garbage collected (e.g., static collections, listeners, caches).
  • Excessive data processing: Loading large files, datasets, or images into memory at once.
  • Too many threads: Each thread has its own stack, but thread creation can also consume heap.
  • Improper JVM tuning: Incorrect ratios between young and old generation.

Step-by-step Fix

1. Increase the Heap Size

Add JVM arguments to increase the maximum heap size. For example, to set the heap to 2GB:

-Xms512m -Xmx2g
  • -Xms: Initial heap size
  • -Xmx: Maximum heap size

Set these in your application startup script, IDE run configuration, or server environment (e.g., JAVA_OPTS for Tomcat).

2. Generate a Heap Dump

Add the following JVM arguments to automatically create a heap dump when OutOfMemoryError occurs:

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

Reproduce the error to generate the dump file.

3. Analyze the Heap Dump

Use tools like Eclipse Memory Analyzer (MAT), VisualVM, or JProfiler to open the .hprof file. Look for:

  • Large object sizes (e.g., byte arrays, collections)
  • Unreferenced objects accumulating in memory
  • Thread stacks holding references

4. 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 listeners or observers when objects are disposed

5. Optimize Code

Reduce memory footprint by:

  • Processing data in streams instead of loading entire files
  • Using primitive types instead of wrapper objects
  • Reusing objects with object pools
  • Limiting collection sizes

Alternative Fixes

  • Switch garbage collector: Try G1GC (-XX:+UseG1GC) for better heap management.
  • Reduce thread count: Use thread pools instead of creating new threads per task.
  • Increase swap space: Not recommended as it affects performance.
  • Upgrade hardware: Add more RAM if the system is memory-constrained.

Prevention

  • Monitor heap usage with tools like JConsole, VisualVM, or Prometheus/Grafana.
  • Set heap dump on OOM in production to capture root cause.
  • Perform load testing to determine appropriate heap size.
  • Use code reviews and static analysis to catch memory leaks early.
  • Implement proper logging to track memory-intensive operations.

Example: Spring Boot Application

For a Spring Boot app, set JVM arguments in application.properties or command line:

java -Xms512m -Xmx2g -XX:+HeapDumpOnOutOfMemoryError -jar myapp.jar

Common Pitfalls

  • Setting heap too large can cause swapping and degrade performance.
  • Ignoring memory leaks after increasing heap only delays the issue.
  • Not testing with realistic data volumes.

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

Was this solution helpful?