Fix Java OutOfMemoryError: Java heap space
Java heap space OutOfMemoryError occurs when the JVM cannot allocate more objects in the heap. This guide covers symptoms, root causes, and step-by-step fixes including increasing heap size and memory leak detection.
Symptoms
When a Java application runs out of heap space, you will typically see the following error in the console or log files:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap spaceAdditional symptoms include:
- Application freezes or crashes unexpectedly
- Extremely slow performance due to excessive garbage collection (GC)
- Error messages like
java.lang.OutOfMemoryError: GC overhead limit exceededmay precede the heap space error - For web applications, HTTP 500 errors or blank pages
Root Causes
The JVM heap is the memory area where all object instances and arrays are allocated. The error occurs when the heap reaches its maximum size and no more objects can be allocated. Common causes include:
- Insufficient heap size – The default heap size (often 256MB) is too small for the application's workload.
- Memory leak – Objects are unintentionally held in memory (e.g., static collections, listeners not unregistered), preventing garbage collection.
- Large data sets – Loading huge files, database results, or in-memory caches without proper streaming or pagination.
- Excessive object creation – Inefficient code creating many short-lived objects, causing frequent GC but not enough freed space.
- Fragmentation – In rare cases, heap fragmentation prevents allocation of contiguous blocks even if total free memory is sufficient.
Step-by-Step Fix
1. Increase JVM Heap Size
Set the initial (-Xms) and maximum (-Xmx) heap size. For a server with 8GB RAM, a typical setting is:
java -Xms512m -Xmx4g -jar myapp.jarFor Tomcat, edit CATALINA_OPTS in setenv.sh:
export CATALINA_OPTS="-Xms512m -Xmx4g"For Eclipse, edit eclipse.ini:
-Xms256m
-Xmx1024mNote: Do not set -Xmx larger than available physical RAM to avoid swapping.
2. Generate a Heap Dump for Analysis
Add JVM flags to capture heap dump on OOM:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/to/dumpsWhen the error occurs, a .hprof file is created. Analyze it with tools like Eclipse MAT (Memory Analyzer) or VisualVM.
3. Analyze Memory Leak with Eclipse MAT
- Open the heap dump in Eclipse MAT.
- Run the Leak Suspects Report (found under Reports menu).
- Look for objects with high retained heap sizes, especially collections (HashMap, ArrayList) that keep growing.
- Inspect the GC root paths to identify what holds references to these objects.
- Fix the code: nullify references, use weak references, or clear collections when no longer needed.
4. Optimize Garbage Collection
Choose the right GC algorithm based on your application:
| GC Type | Flag | Best For |
|---|---|---|
| G1 GC (default since Java 9) | -XX:+UseG1GC | Large heaps, low pause times |
| Parallel GC | -XX:+UseParallelGC | High throughput, batch processing |
| ZGC (Java 11+) | -XX:+UseZGC | Very large heaps, sub-millisecond pauses |
5. Reduce Object Allocation
- Use
StringBuilderinstead of string concatenation in loops. - Stream large files instead of reading entire content into memory.
- Use primitive collections (e.g., Trove, Eclipse Collections) to reduce overhead.
- Reuse objects with object pools if creation is expensive.
Alternative Fixes
- Increase swap space – Not recommended as it degrades performance, but can buy time.
- Distribute workload – Use multiple JVM instances or microservices to spread memory usage.
- Reduce data retention – Implement pagination in database queries, limit result sets.
- Use off-heap storage – For caches, consider technologies like Redis or Ehcache with off-heap store.
Prevention
- Monitor heap usage with tools like JConsole, VisualVM, or Grafana/Prometheus with JMX exporter.
- Set up alerts when heap usage exceeds 80% of maximum.
- Conduct regular code reviews to spot potential memory leaks (e.g., unclosed resources, static collections).
- Use static analysis tools (FindBugs, SonarQube) to detect memory issues early.
- Load test your application with realistic data volumes before production deployment.
- Keep Java and libraries updated to benefit from GC improvements.
By following these steps, you can effectively diagnose and resolve the Java heap space OutOfMemoryError, ensuring your applications run reliably under load.
Was this solution helpful?