Java: java.lang.OutOfMemoryError: Java heap space
Java heap space out of memory
Verified against JDK 21 docs (troubleshooting), Eclipse MAT guide, Stack Overflow #37335/java-heap-space · Updated April 2026
> quick_fix
The JVM hit its -Xmx (max heap) limit. Either your app genuinely needs more memory (raise -Xmx), or you have a memory leak (objects retained beyond their useful life). Capture a heap dump to tell the difference.
# Immediate workaround: raise heap to 4GB
java -Xmx4g -jar myapp.jar
# Better: enable heap dump on OOM
java -Xmx2g -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./heap.hprof -jar myapp.jar
# Analyse heap.hprof in Eclipse MAT or jvisualvmWhat causes this error
The JVM pre-allocates a fixed-size heap (controlled by -Xmx). When live objects plus unreachable-but-not-yet-collected objects fill the heap, the garbage collector runs. If even after GC there's not enough space to allocate the requested object, the JVM throws OutOfMemoryError: Java heap space and the app dies.
How to fix it
- 01
step 1
Raise -Xmx temporarily to confirm it's a sizing issue
If the app runs fine at 4GB but crashes at 2GB, you probably just need a bigger heap. If it crashes at any -Xmx you give it, you have a leak.
- 02
step 2
Enable automatic heap dump on OOM
Add -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./heap.hprof. When the next OOM happens, you'll have a snapshot to analyse.
- 03
step 3
Analyse the heap dump
Open heap.hprof in Eclipse Memory Analyzer (MAT). The Leak Suspects report tells you which class is holding the most memory and why.
- 04
step 4
Common leak patterns
Static collections that grow forever (HashMap<String, Something> caches). Thread locals not cleared. Stream+collect piping huge files into memory. Listener lists not unregistered.
- 05
step 5
For genuine size needs, tune the GC
Use G1GC or ZGC for heaps > 4GB. G1GC is default on JDK 9+; ZGC is pauseless and scales to TBs.
# ZGC for low-pause, large-heap apps java -XX:+UseZGC -Xmx16g -jar myapp.jar
Frequently asked questions
What's the difference between OutOfMemoryError: Java heap space and Metaspace?
Heap space = your objects (String, MyClass instances). Metaspace = class metadata (class definitions, method bytecode). Different memory regions, different fixes. This page covers heap space only.
Does adding memory always fix OutOfMemoryError?
No. If you have a leak, adding memory just delays the crash. Leak must be found in the heap dump.
What heap size should I give my app?
Start with -Xmx2g for typical web apps. Monitor peak usage via JMX. Set -Xmx to peak + 30% headroom.