Video in progress
On prod the heap slowly grows and ends in an OOM after a few days, and the suspicion is on collections. How do you run the investigation?
First I confirm the growth is a real leak using the old gen level after a Full GC in the GC log, then I take two heap dumps some time apart and compare the dominator tree and the diff in MAT. The culprit is usually a Map in a static or singleton, a listener list, or a ThreadLocal.
📖 Answer
-
Is it a leak or just a big working set? I look at the graph of memory remaining after GC (the live set). If the low point of the sawtooth rises day after day, it is a leak. If it stays at the same level, the heap is too small, or the load has grown.
-
Collecting data. An automatic dump on OOM:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps
But an OOM dump is big, and taking it stops the service. A better way is to take two dumps a few hours apart on a pod that has been taken out of traffic, or the cheaper jcmd <pid> GC.class_histogram several times and compare which class's count is growing.
- Analysis in MAT:
- The dominator tree shows which single object holds the most memory. Often a
ConcurrentHashMaporHashMapcomes out on top; - "Path to GC roots" shows who holds it: a static field, a Spring singleton bean, a thread;
- Look at the keys inside the Map: what are they? If they are session ids, request ids or timestamps, they are never removed.
Typical culprits:
- a plain Map used as a cache, without eviction;
- listener lists that have
registerbut nounregister; - objects whose key-affecting field was changed: they stay in the Map and are never removed;
- a
ThreadLocal<Map<...>>in thread pool threads that never getsremove(); - big objects held through
subListorString.substring(old JDKs).
- After the fix, prevent a regression: caches are created only through a shared, bounded component, and their size is in metrics. An alert on the old gen live set warns you several days before the OOM.
Sign up to mark studied questions and save your progress.