java runtime_error ai_generated true

java.lang.OutOfMemoryError: Java heap space

ID: java/outofmemoryerror-heap

Also available as: JSON · Markdown
82%Fix Rate
88%Confidence
95Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
17 active

Root Cause

OutOfMemoryError: Java heap space is thrown when the JVM cannot allocate an object in the heap because the maximum heap size has been exhausted. This is caused by memory leaks, loading too much data into memory, or insufficient heap allocation for the workload.

generic

Workarounds

  1. 88% success Profile the application with a heap dump to identify memory leaks or large object allocations
    1. Add -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/heapdump.hprof to JVM args. 2. Reproduce the OOM. 3. Open the heap dump in Eclipse MAT or VisualVM. 4. Look at the 'Leak Suspects' report and 'Dominator Tree' to find which objects consume the most memory. 5. Trace the retention path to find the code holding references. 6. Fix the leak (close resources, remove from caches/collections, use WeakReferences).
  2. 85% success Use streaming or pagination for large data sets instead of loading everything into memory
    1. Replace List<T> queries with streaming approaches: use Java Stream API with database cursors, or paginated queries with LIMIT/OFFSET. 2. For file processing, use BufferedReader/InputStream line-by-line instead of reading entire files into Strings. 3. For collections, consider off-heap storage (MapDB, Chronicle Map) or disk-backed caches if the dataset is too large for heap. 4. Set appropriate -Xmx based on the actual working set size after optimization.

Dead Ends

Common approaches that don't work:

  1. Simply increasing -Xmx without investigating the root cause of high memory usage 60% fail

    Increasing heap size is a temporary band-aid. If the application has a memory leak, it will eventually consume any amount of heap. Larger heaps also cause longer GC pauses, potentially making the application less responsive. The real fix requires profiling memory usage to find leaks or excessive allocations.

  2. Calling System.gc() in code to try to force garbage collection 90% fail

    System.gc() is only a hint to the JVM — it may be ignored entirely. Even when it runs, it cannot collect objects that are still referenced. If the OOM is caused by a memory leak (objects still reachable), GC cannot help. It also introduces unpredictable pauses.

Error Chain

Leads to:
Preceded by:
Frequently confused with: