Fixing Java OutOfMemoryError: Java heap space
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:
- Insufficient heap size: Default heap (e.g., 256MB) is too small for the application’s workload.
- Memory leak: Objects are unintentionally held in memory (e.g., static collections, unclosed resources).
- Excessive data processing: Loading large datasets (e.g., huge files, database results) into memory.
- Improper garbage collection: Long-lived objects or inefficient GC tuning.
- 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.jarAdjust 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.hprofAnalyze 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
WeakReferenceorSoftReferencefor caches. - Close resources (streams, connections) in
finallyblocks 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=200Alternative Fixes
- Reduce heap usage: Lower
-Xmxif the error occurs due to GC overhead (e.g., withGC 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
-Xmsand-Xmxbased 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.,
ArrayListvsLinkedList). - 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?