Fix Java OutOfMemoryError: Java heap space
The Java heap space OutOfMemoryError occurs when the JVM cannot allocate more objects. This guide covers increasing heap size, optimizing code, and using profiling tools.
Symptoms
The application throws java.lang.OutOfMemoryError: Java heap space during runtime. This may occur during object creation, data processing, or after prolonged operation. The JVM may crash or become unresponsive. In logs, you see repeated GC attempts and eventual failure.
Root Causes
- Insufficient heap size: The default heap (often 256MB or 512MB) is too small for the application's workload.
- Memory leak: Objects are unintentionally retained (e.g., uncleared collections, unclosed resources, static references).
- Excessive data loading: Loading large files, datasets, or images into memory without batching.
- Inefficient data structures: Using memory-heavy collections or creating many short-lived objects.
- Fragmentation: Large objects cause heap fragmentation, preventing allocation despite free space.
Step-by-Step Fix
1. Increase JVM Heap Size
Set -Xmx (maximum heap) and optionally -Xms (initial heap). Example for 2GB max:
java -Xms512m -Xmx2g -jar myapp.jarFor Tomcat, edit CATALINA_OPTS. For Maven, use MAVEN_OPTS. Adjust based on available RAM.
2. Enable GC Logging
Add flags to monitor garbage collection:
-XX:+PrintGCDetails -XX:+PrintGCTimeStamps -Xloggc:gc.logAnalyze gc.log for frequency, pause times, and heap usage patterns.
3. Generate a Heap Dump
Add -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/dump.hprof. When OOM occurs, a dump is created. Analyze with Eclipse MAT or VisualVM.
4. Analyze Heap Dump
Open the dump in Eclipse MAT. Use the Leak Suspects Report to find the largest objects and their GC roots. Look for:
- Collections (HashMap, ArrayList) holding too many entries.
- Threads with large stacks.
- Unclosed streams or connections.
5. Fix Memory Leaks
Common fixes:
- Clear collections after use:
list.clear(). - Use WeakHashMap or SoftReferences for caches.
- Close resources in finally blocks or use try-with-resources.
- Avoid static collections that grow indefinitely.
6. Optimize Code
- Process data in streams instead of loading all at once.
- Use primitive arrays instead of wrapper objects.
- Reuse objects with object pools.
- Increase batch size for database queries.
Alternative Fixes
- Use G1GC:
-XX:+UseG1GCfor better large heap management. - Reduce object size: Use
-XX:+UseCompressedOopsto compress object pointers. - Increase Metaspace: If OOM is in Metaspace, use
-XX:MaxMetaspaceSize=256m. - Switch to 64-bit JVM: Allows larger heap sizes.
Prevention
- Monitor heap usage with tools like JConsole, VisualVM, or Prometheus.
- Set memory limits in container environments (Docker:
--memory). - Perform load testing to identify memory thresholds.
- Use static code analysis (SonarQube) to detect potential leaks.
- Implement circuit breakers to prevent cascading failures.
- Regularly review GC logs for anomalies.
By following these steps, you can diagnose and resolve Java heap space errors, ensuring stable application performance.
Was this solution helpful?