Video in progress
A Spring application's heap slowly fills up over a few days and ends in OutOfMemoryError. How do you analyze it?
I take a heap dump (or let it be written automatically on OOM) and use Eclipse MAT's "dominator tree" and "leak suspects" to see who holds the memory and who references it. In Spring applications it's usually an unbounded cache, a ThreadLocal, a static collection, a huge persistence context or a queue that never drains.
📖 Answer
Gather evidence first:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps
You can also take one from a running application: jcmd <pid> GC.heap_dump /tmp/h.hprof. If you compare two dumps taken at different times, you can see clearly what keeps growing.
Look at the metrics too: if jvm.memory.used (old gen) keeps creeping up even after each full GC, that's a real leak. If it's high but flat, the heap is just small.
Common causes in Spring applications:
@Cacheablewith the defaultConcurrentMapCache: no TTL and no size limit;- a
static Mapused as a "cache" whose keys are always new; - a ThreadLocal not cleared in
finally(pool threads live forever); - 1 million entities loaded in a single transaction: the persistence context holds them all;
- an
@Asyncexecutor with an unbounded queue; if the consumer is slow, it just keeps growing; - a new
RestClient/ObjectMappercreated on every request and added to some list; - unbounded tags in Micrometer.
One catch: sometimes the problem isn't in the heap at all. The number of threads, direct buffers (Netty) and metaspace (classes reloaded on every deploy) also eat memory. For that, -XX:NativeMemoryTracking=summary and jcmd VM.native_memory help.
After you fix the cause, add a metric and an alert (for example on old gen usage after GC), otherwise you'll hear about it from users again next time.
Sign up to mark studied questions and save your progress.