Video in progress
In monitoring, the heap level after each GC keeps rising from day to day. How do you confirm a leak on prod and find its source?
First I confirm that the post-GC heap (old gen) graph is a sawtooth, but its lower line keeps climbing. Then I take two class histograms or heap dumps a few hours apart and compare which classes' object counts are growing.
📖 Answer
The heap growing by itself is not a leak, because the GC may simply not have run yet. What matters is what remains after a GC. With Micrometer, don't watch the jvm_memory_used_bytes{area="heap"} graph. Watch jvm_gc_live_data_size_bytes, or the ->XXXM numbers in the GC log.
Once confirmed, the cheapest step is comparing histograms:
jcmd $PID GC.class_histogram > h1.txt
# wait 1-2 hours
jcmd $PID GC.class_histogram > h2.txt
Compare the instance count of the same class in both files. For example, if com.shop.SessionInfo went from 20 thousand to 900 thousand, you have found your suspect.
Then I take a heap dump and look at the path from that class to the GC root in MAT. The most common culprits in practice:
- a
static Mapcache with no bound, or a list kept "temporarily"; - a listener or callback that is registered and never removed;
- a
ThreadLocalthat wasn'tremove()d; - a Hibernate session or
EntityManagerholding thousands of entities in one big batch.
Important: before taking the dump, take the instance out of the load balancer. On a big heap, a dump stops the application for several seconds.
Sign up to mark studied questions and save your progress.