Quick revision
The short answer
First we confirm it is a real leak: heap occupancy after GC rising steadily day and night, not just a busy period. Then we compare class histograms taken hours apart to see which types grow, take a heap dump once the leak is large enough and follow the dominator tree and paths to GC roots to the code that holds the objects, or use JFR's old object samples for a lower-risk view. The usual causes are unbounded caches and maps, listeners never removed, ThreadLocal values and high-cardinality metrics, and the fix is verified only when post-GC occupancy stays flat for a full day.
What to remember
In this answer, we investigated a heap that grows 50 MB per hour. We confirmed the leak from heap occupancy after GC rising steadily day and night, compared class histograms hours apart to find the growing types, took a heap dump and used the dominator tree and paths to GC roots to find who holds them, or used JFR old object samples for a smaller, safer view. We went through the usual causes, unbounded caches, listeners, ThreadLocals and high-cardinality metrics, and verified the fix by seeing post-GC occupancy stay flat over a full day.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
First we confirm it is a real leak: heap occupancy after GC rising steadily day and night, not just a busy period. Then we compare class histograms taken hours apart to see which types grow, take a heap dump once the leak is large enough and follow the dominator tree and paths to GC roots to the code that holds the objects, or use JFR's old object samples for a lower-risk view. The usual causes are unbounded caches and maps, listeners never removed, ThreadLocal values and high-cardinality metrics, and the fix is verified only when post-GC occupancy stays flat for a full day.
Why this question is asked
A service that fails every three days is easy to keep alive with restarts, and that is exactly why such leaks survive for months. Each restart hides the problem, and nobody has time for a slow investigation. Interviewers ask this question to see whether we can investigate methodically, from the first signal to proof of the fix. In this answer, we will go through each of those steps with the commands and the reasoning, look at the usual causes, and finish with how to verify the fix.
1Confirm the Trend From GC Data
Heap use in a Java service always goes up and down. Objects are allocated, the heap fills, the collector frees the garbage, and the line drops again. The number that tells us about leaks is the occupancy right after a collection, because that is roughly the live set, the objects still reachable. If the live set grows steadily, something is holding on to objects.
So we look at GC logs or a metric such as heap used after GC over several days, not hours. A real leak of 50 MB per hour grows by about 1.2 GB a day and keeps growing at night, when traffic is low. A busy period, by contrast, raises occupancy during the day and drops back at night. With 3.6 GB of headroom, 50 MB per hour runs out in about 72 hours, which matches the three-day crash cycle and tells us the numbers are consistent.
2Compare Class Histograms Hours Apart
Before taking a full heap dump, we narrow the suspects cheaply. A class histogram lists, for each class, how many live instances exist and how many bytes they use. We take one now and another a few hours later and compare them. The classes whose counts grow steadily between the two are our suspects.
Notice that GC.class_histogram forces a full collection to count only live objects, so on a large heap it causes a pause of a second or more. We run it on one instance, ideally one we have taken out of the load balancer, or at a quiet time. Here about 3 million CartSnapshot objects and their HashMap nodes appeared in six hours, which points at a map of cart snapshots, but a histogram cannot tell us who holds it.
3Take a Heap Dump and Follow the References
A heap dump is a snapshot of every object and every reference between them. We take it when the leak has had time to grow, for example a day after a restart, so the leaking objects stand out clearly against the normal live set.
- GC root: class CartCacheloaded by the application class loader
- static field SNAPSHOTS
ConcurrentHashMap - 7.3 million HashMap nodesnever removed
- 7.2 million CartSnapshot objectsretained size about 2 GB
4 layers, from the top down. Step through them one at a time.
The dump is roughly the size of the live heap, here several gigabytes, and writing it pauses the JVM for seconds, so again we use an instance out of rotation and a disk with enough space. Then we open it in a tool such as Eclipse Memory Analyzer.
Two views do most of the work. The dominator tree lists the objects that keep the most memory alive: an object dominates another if every path from the GC roots to the second passes through the first, so removing it would free everything beneath. A leak usually shows as one collection retaining a large share of the heap, such as a ConcurrentHashMap retaining 2 GB. Then paths to GC roots, excluding weak and soft references, show the chain that keeps that collection reachable, for example a static field in a class called CartCache. That chain points at the line of code to fix.
4A Lower-Risk Alternative: JFR Old Object Samples
A heap dump of a large heap is slow, pauses the service and contains every customer's data. JFR offers a lighter alternative. Its old object sample event tracks a sample of allocated objects and keeps those that survive a long time, together with the stack trace where they were allocated. When we dump the recording with paths to GC roots enabled, JFR also records the reference chain that keeps each sampled object alive.
This is often enough to identify the leak without a heap dump at all: it shows both where the objects were created and who keeps them. Computing the paths to GC roots does cause a pause at dump time, so it is still best done on one instance, but the file is far smaller than a heap dump and contains much less data. Old object sampling with stack traces is enabled in the profile settings; check your recording's settings.
5The Usual Causes
Once we know which objects grow and who holds them, the cause is usually one of a few patterns. The most common is an unbounded cache or map: a map used as a cache with entries added per user, session or request and never evicted, as in our CartCache. Close behind are listeners or callbacks registered on a long-lived object and never removed, so each one keeps its whole object graph alive; ThreadLocal values never removed on pooled threads; and metrics with high-cardinality tags, where every new user id creates a meter that the registry keeps forever.
The fix follows the cause. For a cache, we use a real cache library with a maximum size and expiry, such as Caffeine, or remove entries when the session ends. For listeners we unregister them, for ThreadLocals we call remove() in finally, and for metrics we use bounded tags.
6Verifying the Fix
A leak fix is proven only by the same signal that found it. After deploying the fix, we watch heap occupancy after GC for at least a full day, covering the daily traffic peak and the quiet night. It should rise to a plateau and stay flat. We also repeat a class histogram a few hours apart and check that the suspect class no longer grows. And we keep an alert on post-GC occupancy rising over 24 hours, so a future leak is caught early.
- Post-GC heap rising day and nightGC logs or metrics
- Class histograms hours apartwhich types grow?
- Heap dump or JFR old object sampleson an instance out of rotation
- Dominator tree and path to GC rootswho holds the objects?
- Fix the causebounded cache, remove listener,
remove() - Post-GC heap flat for 24 hours?YesDone, keep the trend alertNoBack to the histograms
6 steps in order. Play them, or step through them one at a time.
7Follow-up questions
How do you take a heap dump in Kubernetes without losing the pod?
We remove the pod from the Service by changing a label, so it receives no traffic, then use kubectl exec to run jcmd and write to a volume, and kubectl cp or a sidecar to move the file to secure storage. Changing the label also makes the ReplicaSet start a replacement, so capacity is preserved.
8Conclusion
In this answer, we investigated a heap that grows 50 MB per hour. We confirmed the leak from heap occupancy after GC rising steadily day and night, compared class histograms hours apart to find the growing types, took a heap dump and used the dominator tree and paths to GC roots to find who holds them, or used JFR old object samples for a smaller, safer view. We went through the usual causes, unbounded caches, listeners, ThreadLocals and high-cardinality metrics, and verified the fix by seeing post-GC occupancy stay flat over a full day.
Open with
I would start by confirming it is a leak and not load: I look at heap used after GC in the GC logs or metrics over several days.
Then, if they want more
If it climbs about 50 megabytes an hour at night as well as during the day, that is a growing live set, and with roughly 3.6 gigabytes of headroom it matches failing every three days.
Next I narrow it cheaply with jcmd GC.class_histogram on one instance, a few hours apart, and compare which classes grow; that might show millions of new CartSnapshot objects and HashMap nodes. The histogram forces a full GC, so I take the instance out of rotation first.
Then, about a day after a restart, when the leak is big but not critical, I take a heap dump with jcmd GC.heap_dump, open it in Memory Analyzer, look at the dominator tree for the collection retaining most memory, and follow the path to GC roots, excluding weak references, to find the static field or bean holding it.
JFR's old object sample with path to GC roots is a lighter alternative that also shows the allocation site. The usual causes are unbounded caches or maps, listeners not removed, ThreadLocals and high-cardinality metric tags. After the fix, I only call it done when post-GC occupancy is flat for a full day, and I keep an alert on that trend.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Heap occupancy after GC grows by about 50 MB per hour in production, and the service...": https://scrivio-interview-library.netlify.app/java/jvm-diagnostics/8b453b9c28/