Lesson · Garbage Collection & References
GC debugging: logs, dumps, and the rising floor
18 min readDebugging Memory Problems
Memory climbs, the dashboard shows a sawtooth, and the box gets restarted on Fridays. Two artifacts separate a genuine leak from heavy allocation: a GC log that shows whether the floor is moving, and a heap dump whose dominator tree names what holds the memory.
Memory climbs until the weekly restart
The dashboard shows memory rising and falling all day, the alert fires by Thursday, and a restart resets it. Two very different stories produce that graph: the service allocates heavily and the collector is simply working, or a live set is growing and the collector is losing ground.
The difference is answerable from the outside with three artifacts, in order: the GC log, which shows whether the floor moves; a heap dump, which is the heap at one moment; and a dominator tree over that dump, which names the object holding everything else.
Sawtooth is healthy; a rising floor is a leak.
Diagnostic flow · memory that keeps climbing
each station answers a question the next one depends onSymptom
the dashboard, or the alert
Note the shape: peaks with a rising floor and peaks with a flat floor are different investigations.
GC logs
-Xlog:gc*
Frequency, pause durations, and the floor the heap returns to after every collection.
Heap dump
jcmd GC.heap_dump, or the OOM flags
The live heap at one moment, written to a file, costing a collection to take.
Dominator tree
Eclipse MAT · VisualVM
Retained sizes with the biggest holder first: what would be freed with each object.
Path to a root
MAT: Path to GC Roots, weak refs excluded
The chain that keeps it alive. Its second step is a field in your code, and that is where the fix goes.
The last station is the one that repairs something. Every station before it only earns the right to look at the next one, and the collector is the last suspect rather than the first.
First: the logs
Unified logging arrived with JDK 9 (JEP 158), so -Xlog:gc* is the modern spelling and -XX:+PrintGCDetails belongs to the pre-9 world. Each collection prints its cause, the occupancy before and after, and how long it took, which is enough to read three trends: how often the young region is emptied, how long the pauses are, and what floor the heap returns to.
java -Xlog:gc*:file=gc.log:time,uptime,pid:filecount=5,filesize=20M -jar app.jar [12.418s][info][gc] GC(214) Pause Young (Normal) (G1 Evacuation Pause) 512M->180M(2048M) 6.113ms [12.424s][info][safepoint] Total time for which application threads were stopped: 0.00642 s, Stopping threads took: 0.00058 s # ^ before -> after (capacity) ^ the pause ^ the parking wait inside it
| What you see | What it means | Next move |
|---|---|---|
| Young pauses every few seconds, each a few milliseconds | normal for an allocation-heavy service: the young region is being emptied on schedule | check the floor before touching anything |
| Pause durations growing with occupancy | there is more live data to mark or move on every cycle | watch the floor across full collections |
| to-space exhausted, or an evacuation failure | nowhere to copy survivors: the region was overfull (the wording is collector-specific; this one is G1's) | check retention first, then sizing |
| Full collections repeating, each leaving a higher floor | the live set grows between full collections: the leak signature | take a heap dump |
| Pauses dominated by Stopping threads took | the parking wait, not the collection, is the cost (gc-basics walks the safepoint side) | find the thread that reached no poll |
- Frequency is an allocation-rate meter: young cycles per minute tells you how fast the program creates garbage.
- Occupancy after the pause is the floor: the series of floors over hours is the trend that matters.
- Cause names are collector-specific: promotion failed describes the CMS era, and CMS was removed in JDK 14, so old tutorials and old logs do not always match your output.
The frequency of young collections is an allocation-rate meter; the pause durations are its price.
Sawtooth or rising floor
The young region fills and empties in a sawtooth, and the floor it returns to is the best estimate of the live set available without opening the process. A stable floor means the collector is winning: the memory is genuinely garbage, and the conversation moves to sizing and pacing.
A floor that rises across full collections means the live set grows: objects that should be garbage are still reachable. One honest caveat before calling it a leak: a bounded working set that is bigger today than yesterday (a warmer cache, more tenants) looks identical from the log. The dump is what separates growth with a purpose from growth that never stops.
The full collection is the calibration point: whatever survives it is the live set, and every other number is judged against it.
Take the dump
Once the logs say the floor moves, take the dump while the process is still healthy enough to answer. jcmd <pid> GC.heap_dump /tmp/heap.hprof writes an HPROF file of the live objects, and it collects first unless you pass -all, which is another way of saying it costs a pause. The legacy spelling is jmap -dump:live,format=b,file=/tmp/heap.hprof <pid>.
The dump you actually want is usually the one nobody had to attend. Configure the automatic pair at start-up so the file is written at the moment the heap runs out.
# manual, on a process that can afford the pause jcmd 4711 GC.heap_dump /tmp/heap.hprof # automatic, configured long before the incident java -Xmx2g -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps \ -XX:+ExitOnOutOfMemoryError -jar app.jar
- The path with a price: a heap dump collects, then writes the whole heap, so give it a disk with room and take it when the pause is affordable.
- The path that pays for itself:
-XX:+HeapDumpOnOutOfMemoryErrorplus-XX:HeapDumpPathcaptures the heap exactly when it is full. - The pairing:
-XX:+ExitOnOutOfMemoryErrorstops the process after the dump so a supervisor restarts a clean one: a dying process that keeps serving from a broken heap is worse than a restart. - The lighter alternative: JFR can dump a recording with path-to-gc-root information, which gives retaining paths without writing an HPROF file (jvm-tooling starts the recording).
An automatic dump is worth ten manual ones: it fires when the heap is actually full, not when someone finally attaches.
The dominator tree
Shallow size is the object itself. Retained size is everything that would be freed if that object went away, which is the number that matters when one structure holds most of the heap. It is computable because of a property the heap graph has: a dominator is an object that every path from the roots has to pass through, so the dominator owns everything it dominates.
Open the dump in Eclipse MAT or VisualVM and start from the dominator tree, sorted by retained size. Then take the biggest entry and ask for the path to GC roots with weak references excluded: that path is the answer, and its second or third step is a field in your code.
The dump answers what holds it, not who forgot it: naming the retaining field is the diagnosis, and the missing remove is the fix.
The classic leaks, by the root they hide behind
Almost every Java leak is a live root reaching something that no longer serves a purpose, so the fastest way to recognise one is to know which root each pattern hides behind.
- A static collection that only grows: the static field is the root. Bound it, evict from it, or hold the entries weakly.
- Listeners and callbacks never removed: the registry is the root and outlives the subscriber. Pair every add with a remove.
- ThreadLocal values on pooled threads: the pooled thread is the root, and it never ends. remove() in a finally block, as the threadlocal lesson shows.
- A class loader after a redeploy: the live loader is the root. One running thread, driver or static from the old deployment keeps every class and static of that deployment alive (class-loading covers the loading side).
- Direct buffers that are never released: the buffer object is the root, and the memory it controls sits outside the heap where no dump will show it.
- A queue with no bound: the producer is the root. A LinkedBlockingQueue without a capacity is effectively unbounded, so a slow consumer turns a queue into a leak with a friendly name (blocking-queues covers the backpressure side).
Every leak is something reachable that no longer serves a purpose; name the root, and the fix writes itself.
The OutOfMemoryError names the area
The message after the colon is not decoration. Each variant names a different pool, and the first move depends on which one ran out.
| Message tail | What ran out | First move |
|---|---|---|
| Java heap space | the heap, after collection could not satisfy an allocation | check the floor curve: a rising floor means a dump, a flat one means sizing |
| Metaspace | class metadata: too many classes, or too many loaders | inspect loaders with VM.metaspace and VM.classloader_stats; a redeploy loop shows here |
| Direct buffer memory | the NIO direct pool, bounded by -XX:MaxDirectMemorySize | BufferPoolMXBean for the size, and no heap dump will contain a byte of it |
| unable to create native thread | thread creation: thread count times stack size, or a process limit | count threads, check stack size and container process limits; virtual threads change the arithmetic |
| GC overhead limit exceeded | the collector is reclaiming almost nothing while consuming almost all the time | fix the fullness: the classic definition, documented for the parallel collector, is over 98 percent of time in collection for under 2 percent recovered |
- Metaspace has a sibling:
Compressed class spaceis the same story for the class-pointer area, and both point at loader growth. - A heap dump is not a memory dump: direct buffers, metaspace, thread stacks and native allocations are all outside it, so treat a healthy-looking dump beside a memory error as a sign you are looking in the wrong place (runtime-memory has the map).
- ExitOnOutOfMemoryError is a policy, not a fix: it stops a broken process from limping while the real repair happens elsewhere.
The message names the area that ran out: that is the first branch of the investigation, not the diagnosis.
The two timelines
The lab below plays two authored GC histories: a healthy sawtooth and a leaking floor, each with its collection marks. Read the floor series before you read the verdict, then switch to the heap dump view and follow the biggest retained set down to the field that keeps it alive.
The sizes in the dump are illustrative, and the shape is the lesson: the top of the dominator tree holds most of the heap, and the path to a GC root is short.
Read the floor series before the verdict, in the lab and in production.
GC forensics · authored logs and a dump
pick a run, then open the dumpheap used per sample (illustrative) · floor after each collection: 26 · 25 · 27 · 26 · 25, and the full cycle lands in the same place
marks: accent dot = young collection, amber dot = full collection, taller amber bars = pressure
Frequent young cycles, short pauses, and a floor that returns to the same place after every collection, including the full one. The collector is winning, so any work here is sizing, not a bug hunt.
Sizes and percentages here are authored to keep the shape readable. The reading order is the lesson: floor series first, dominator tree second, retaining field third.
The dump shows the heap, not the memory
An OutOfMemoryError names an area, and the heap dump contains only one of them. Direct buffers, metaspace, thread stacks and native allocations are invisible in the HPROF file, so a small dump beside a memory error is not good news, it is a boundary. Check BufferPoolMXBean for the direct pools and native memory tracking for the rest, then come back to the heap with the right question.
Interview angles
Walk me through diagnosing steadily growing memory in a live service.+
Start with logs: -Xlog:gc* shows whether the floor after each full collection is stable or rising, and how long the pauses are. If the floor rises, get a heap dump, ideally the one HeapDumpOnOutOfMemoryError already wrote, and read it in MAT from the dominator tree to the path to GC roots. Then fix the retaining path: bound the cache, remove the listener, clean the ThreadLocal.
Follow-up: What if the commit rate rises but the floor is flat?
How do you tell a leak from heavy allocation?+
By the floor, not the peaks. Heavy allocation makes frequent short young collections that return to the same floor, while a leak leaves a higher floor after each full collection. A stable floor moves the conversation to sizing and pacing; a moving floor moves it to the retaining path.
What is retained size, and why does it beat shallow size?+
Shallow size is the object itself; retained size is everything that would be freed with it, which is the number that matters when one structure holds most of the heap. The dominator tree can compute it because a dominator is an object every path from the roots must pass through.
Name the classic leak sources and the root each hides behind.+
Static collections behind their static field, listeners behind a registry that outlives them, ThreadLocal values behind pooled threads, and class loaders behind any reference from outside the deployment. Direct buffers hide behind a reachable buffer object while the memory itself sits outside the heap.
# the two shapes you will meet most often static final Map<Key, Value> CACHE = new HashMap<>(); // grows because nothing evicts ThreadLocal<Context> CTX = ...; // kept by the pooled thread, not by you
You get OutOfMemoryError: Metaspace on a long-running service. What do you look at?+
Class and loader growth: a redeploy loop, or a framework generating classes through proxies or script engines, can load without ever unloading. VM.metaspace and VM.classloader_stats show the loaders, and the fix is usually making the old deployment unreachable so its loader can be collected.
The heap dump looks healthy, yet the process dies with OutOfMemoryError. What now?+
The message is about an area the dump does not contain: direct buffers, metaspace, thread stacks or native memory. BufferPoolMXBean bounds the first, thread counting covers the third, and native memory tracking or the OS view covers the rest.
This is the same boundary that makes 'the dump is small' a bad sign rather than a good one. Read the message, pick the pool it names, and only then decide whether the heap is even the right place to look.