Open the .hprof in Eclipse MAT; the dominator tree shows the biggest retained object.
Usual leaks: unbounded caches/static maps, listeners never removed, ThreadLocals in pools.
In containers, size the heap with -XX:MaxRAMPercentage.
✦ Definition~90s read
What is java.lang.OutOfMemoryError?
java.lang.OutOfMemoryError: Java heap space is thrown when the JVM can't allocate an object because the heap (sized by -Xmx) is full of objects that are still reachable, even after garbage collection.
★
The heap is a cupboard.
Plain-English First
The heap is a cupboard. Garbage collection throws out what nobody uses. If something keeps everything it's ever given, like a cache with no limit, the cupboard fills no matter how often you clean it. A bigger cupboard just takes longer to fill.
The order service died every three days with Java heap space. Doubling -Xmx made it last six. The heap wasn't too small; a cache was growing forever.
Leak or Too Small?
Ignore the sawtooth; look at the low points right after each collection. If they rise over time, something is never freed. If they're flat, the heap is simply too small for the load.
gc.shBASH
1
2
jstat -gcutil <pid> 10s # watch O (old gen %) after each full GC
jcmd <pid> GC.heap_info
🎯 Key Takeaway
The floor after GC tells you which.
Capture a Heap Dump
Have the JVM dump the heap when it throws OutOfMemoryError, so you see exactly what filled it.
jvm.shBASH
1
2
3
4
5
6
7
java -Xmx2g \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/dumps \
-jar order-service.jar
# or on demand
jcmd <pid> GC.heap_dump /dumps/now.hprof
🎯 Key Takeaway
Always run production with dump-on-OOM.
Find the Leak in MAT
Open the .hprof in Eclipse MAT. The dominator tree lists objects by retained size; the leak is usually one collection holding most of the heap.