java.lang.OutOfMemoryError: Java heap space
Fixing Java OutOfMemoryError: Java heap space
Java throws OutOfMemoryError when the heap is full. This guide covers causes, step-by-step fixes, and prevention for Java heap space errors.
Symptoms
The application crashes with the error: java.lang.OutOfMemoryError: Java heap space. This may occur during object creation, data processing, or after prolonged runtime. The JVM stops and the application becomes unresponsive.
Root Causes
- Insufficient heap size allocated via JVM options (e.g.,
-Xmxtoo low). - Memory leaks: objects held by static collections, listeners, or caches not cleared.
- Large data sets loaded entirely into memory (e.g., huge files, database results).
- Infinite loops or recursion creating excessive objects.
- Fragmentation or inefficient garbage collection.
Step-by-step Fix
- Increase heap size: Add JVM arguments:
-Xms512m -Xmx2g(adjust values based on available RAM). For Tomcat, editCATALINA_OPTS; for command line:java -Xmx2g -jar app.jar. - Enable GC logging: Add
-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStampsto monitor garbage collection. - Generate heap dump on OOM: Use
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/dump.hprof. - Analyze heap dump: Use Eclipse MAT or VisualVM. Look for large objects, unexpected retention, or class instances that shouldn't persist.
- Fix memory leaks: Clear static collections, close resources (streams, connections), remove listeners, use weak references where appropriate.
- Optimize code: Stream large data instead of loading all at once. Use
StringBuilderover string concatenation in loops. Reuse objects.
Alternative Fixes
- Switch to a different garbage collector:
-XX:+UseG1GCor-XX:+UseParallelGCfor better throughput. - Reduce object size: Use primitives instead of wrappers, avoid unnecessary fields.
- Increase swap space or add more physical RAM to the server.
- If using containers, ensure container memory limits match JVM heap settings.
Prevention
- Monitor heap usage with tools like JConsole, VisualVM, or Prometheus + Grafana.
- Set appropriate
-Xmsand-Xmxbased on load testing. - Implement circuit breakers or backpressure to limit request load.
- Conduct regular code reviews for memory management.
- Use profiling during development to catch leaks early.
Example JVM Configuration
java -Xms1g -Xmx4g -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/log/heapdump.hprof -jar application.jarAdjust memory settings based on your environment. For production, start with -Xmx equal to 70-80% of container/VM memory, leaving room for OS and other processes.
Was this solution helpful?