Fix Java OutOfMemoryError: Java heap space
Java throws OutOfMemoryError when heap memory is exhausted. Increase heap size with -Xmx flag or optimize memory usage to resolve this runtime error.
Symptoms
The application crashes with the error message java.lang.OutOfMemoryError: Java heap space. This typically occurs during operations that allocate large objects, process large datasets, or run for extended periods. Symptoms include sudden termination, unresponsive UI, or failed requests with this exception in logs.
Root Causes
- Insufficient heap size: The default heap size (often 256MB or 512MB) is too small for the application's workload.
- Memory leak: Objects are not being garbage collected because they are unintentionally held by references, causing heap to fill over time.
- Large data structures: Loading entire files, databases, or images into memory without streaming or batching.
- Fragmentation: Heap becomes fragmented, preventing allocation of large contiguous blocks even if total free space is adequate.
Step-by-step Fix
Step 1: Identify current heap settings
Run your application with -XX:+PrintFlagsFinal to see default heap sizes. Example: java -XX:+PrintFlagsFinal -version | grep HeapSize
Step 2: Increase heap size
Add JVM arguments -Xms (initial heap) and -Xmx (maximum heap). For example: java -Xms512m -Xmx4g -jar myapp.jar. Set -Xmx to 80% of physical RAM to leave room for OS and other processes.
Step 3: Verify the change
Use jconsole or jvisualvm to monitor heap usage. Confirm that the new limit is applied and that the error no longer occurs under normal load.
Step 4: Enable heap dump on OOM
Add -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/dump.hprof to capture heap dump for analysis.
Step 5: Analyze heap dump
Use tools like Eclipse MAT or VisualVM to open the .hprof file. Look for large objects, leak suspects, or high retention. Common patterns: ArrayList or HashMap holding too many entries, unclosed streams, or static collections.
Step 6: Optimize code
- Use streams instead of loading entire files into memory.
- Clear collections after use (
list.clear()). - Use weak references for caches.
- Close resources in
finallyor use try-with-resources.
Alternative Fixes
- Adjust garbage collection: Use
-XX:+UseG1GCfor large heaps, or-XX:+UseParallelGCfor throughput. - Reduce object size: Use primitive types instead of wrappers, avoid unnecessary object creation.
- Increase swap space: Temporary workaround but not recommended for production.
- Horizontal scaling: Distribute load across multiple JVMs using microservices or load balancers.
Prevention
- Conduct regular memory profiling during development.
- Set appropriate heap limits based on load testing.
- Implement circuit breakers to reject requests when memory is low.
- Monitor JVM metrics with tools like Prometheus + Grafana.
- Use
-Xmxas a safety cap, but also set-Xmsclose to-Xmxto avoid resizing overhead.
Example Configuration
java -Xms2g -Xmx4g -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/log/dump.hprof -jar app.jarThis sets initial heap to 2GB, max to 4GB, uses G1GC, and enables heap dumps. Adjust values based on your server's RAM.
Common Pitfalls
- Setting
-Xmxtoo high can cause swapping or OOM killer. - Ignoring memory leaks after increasing heap—this only delays the crash.
- Not testing with realistic data volumes during development.
By following these steps, you can resolve the OutOfMemoryError and build more resilient Java applications.
Was this solution helpful?