Fix Java OutOfMemoryError: Java heap space
Java heap space error occurs when the JVM runs out of memory in the heap. This guide covers causes, diagnostics, and step-by-step fixes including increasing heap size and optimizing code.
Symptoms
When a Java application runs out of heap memory, you will see the following error in the console or log files:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap spaceAdditional symptoms include sudden application crashes, unresponsive behavior, and excessive garbage collection (GC) activity. The application may slow down significantly before the error occurs.
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 free 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 retained, preventing GC from reclaiming memory (e.g., static collections, unclosed resources, listeners).
- Large data processing: Loading huge files, datasets, or images into memory at once.
- Inefficient data structures: Using memory-heavy structures like
HashMapwith too many entries orStringconcatenation in loops. - Too many threads: Each thread has its own stack, but also may consume heap via thread-local objects.
Step-by-Step Fix
Step 1: Increase Heap Size
Modify JVM startup parameters to allocate more memory. Use the -Xms (initial heap) and -Xmx (maximum heap) flags. For example, to set initial heap to 512MB and max to 2GB:
java -Xms512m -Xmx2g -jar your-application.jarFor server environments, you can also set these via environment variables (e.g., JAVA_OPTS). Ensure the system has enough physical RAM.
Step 2: Enable Heap Dump on OutOfMemoryError
Add the following JVM option to automatically generate a heap dump when the error occurs:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/to/dumpsThis will create a .hprof file that can be analyzed with tools like Eclipse MAT or VisualVM.
Step 3: Analyze Heap Dump
Open the heap dump in a memory analyzer. Look for:
- Largest objects and their retention paths.
- Unusually large collections or arrays.
- Objects that should have been garbage collected but are still referenced (e.g., via static fields).
Identify the root cause (e.g., a cache that never evicts entries) and fix the code.
Step 4: Optimize Code
- Use streaming APIs: For large files, process line by line instead of loading entire file into memory.
- Avoid memory leaks: Close database connections, streams, and remove listeners when no longer needed.
- Use efficient data structures: Prefer
ArrayListoverLinkedListfor indexed access, use primitive arrays orStringBuilderfor string concatenation. - Limit object creation: Reuse objects where possible, especially in loops.
Step 5: Tune Garbage Collection
Choose an appropriate GC algorithm. For high-throughput applications, use the G1 garbage collector:
-XX:+UseG1GC -XX:MaxGCPauseMillis=200Monitor GC logs with -Xlog:gc* to see if GC is the bottleneck.
Alternative Fixes
- Increase swap space: If physical RAM is limited, increase swap. However, this may degrade performance.
- Use 64-bit JVM: 32-bit JVMs have a maximum heap size of ~4GB. Switch to 64-bit for larger heaps.
- Reduce thread stack size: Use
-Xss256kto reduce per-thread memory, freeing more heap. - Profile with VisualVM: Monitor live heap usage and identify memory spikes.
Prevention
- Set appropriate heap limits: Always specify
-Xmsand-Xmxin production scripts. - Automate heap dump analysis: Integrate heap dump analysis into CI/CD pipelines.
- Code reviews: Check for common memory leak patterns (e.g., static collections, inner classes, unclosed resources).
- Load testing: Simulate peak loads to ensure heap size is adequate.
- Monitor regularly: Use tools like JConsole or Prometheus + Grafana to track heap usage over time.
By following these steps, you can resolve the Java heap space error and prevent it from recurring. Always start with increasing heap size, then investigate memory leaks if the problem persists.
Was this solution helpful?