Lesson · Garbage Collection & References
GC basics: reachable in, reusable out
16 min readBasics
The object-lifecycle lesson settled what makes an object unreachable. This one covers what the collector does with that: a contract, two ways to find garbage, three phases to remove it, and the moment when every thread has to stop.
The contract: reachable in, reusable out
The hard part is already settled: an object is alive while any chain of strong references from a GC root can reach it, and a Java leak is memory still reachable that no longer serves a purpose. The object-lifecycle lesson owns that picture.
This lesson starts on the other side of the line. Given a heap full of unreachable objects, what does the collector actually do, and what does it promise? The promise is deliberately weak: memory held by unreachable objects becomes reusable eventually. Not immediately, not at a scheduled moment, and with no commitment at all about resources.
The root set is small on purpose: the stack frames of live threads, static fields of loaded classes, JNI handles, and live class loaders. Everything alive is reachable from there, and everything the collector can free is not.
Reachability decides what can be freed; roots are where the search starts.
Tracing, not counting
Two strategies exist for finding garbage. Reference counting keeps a count per object and frees it when the count hits zero. Tracing, which Java uses, walks outward from the roots and treats everything unmarked as garbage.
The choice has consequences worth knowing before any log appears. Tracing does not care about cycles at all, because a cycle with no root path is simply never reached. Its cost is proportional to what survives, since the walk only visits reachable objects, and it needs a moment when the graph is not changing, which is what the next two sections are about.
Reference counting frees memory more promptly and spreads the work over every pointer write, but a cycle of two objects that only point at each other survives it forever unless a second collector hunts cycles down.
Tracing pays in proportion to what survives; reference counting pays on every pointer write.
Mark, sweep, compact
A classic collection of the old region runs in three phases, and each one leaves a different bill. Mark walks from the roots and tags everything reachable. Sweep then reclaims every unmarked slot in place.
Sweeping is cheap per object but leaves a patchwork: the free space is scattered in holes of different sizes. That is what the third phase fixes. Compact slides the survivors together and updates every reference that pointed at a moved object, so the free space becomes one contiguous block again.
The payoff is on the allocation side. With one free block, satisfying an allocation is bumping a pointer. With a patchwork, the allocator has to search for a hole big enough, and it can fail while plenty of memory is free in pieces it cannot use.
| Phase | Job | Bill it leaves |
|---|---|---|
| Mark | tag everything reachable from the roots | time proportional to the live set |
| Sweep | free every unmarked slot, in place | free space becomes a patchwork of holes |
| Compact | slide survivors together, fix up references | moving cost now, pointer-bump allocation after |
Compaction is what makes allocation cheap: the collector pays the moving cost so the allocator does not.
Roots, reachability, and the three phases
everything alive is reachable from a root; nothing else survivesRoot set
Small on purpose. The collector never asks who references an object; it asks whether a chain from here reaches it.
Reachable graph
AppState (static) → cfg
worker stack → sessions → byte[]
handler stack → orders → payload
a ↔ b: a cycle with no path from any root
Any chain keeps an object alive. A cycle keeps nothing alive, because tracing starts at the roots.
What the collector concludes
reachable → kept
marked, then copied or left in place for the next cycle
no root path → reclaimable
swept away, or simply left behind by a copying collection
Deciding is the cheap half. The next three phases are what turn the decision into usable memory.
mark
one region, eight slotsreachable objects are tagged, walking out from the roots
sweep
one region, eight slotsunmarked slots are reclaimed in place: the free space is now a patchwork
compact
one region, eight slotssurvivors slide together, references are updated, one free block remains
Mark and sweep make memory available. Compact makes it contiguous, which is what lets the allocator satisfy a request with a pointer bump instead of a search through holes.
The generational hypothesis
Two observations organize nearly every production collector. Most objects die young (temporaries, request state, builders). And an object that has already survived several collections is likely to keep surviving.
So the heap is split. A young region is collected often and cheaply, because almost everything in it is already garbage; the survivors are copied out and the rest of the region is declared free at once. The old region is collected rarely and expensively, because most of what is in it is alive and marking it all costs time.
The hypothesis is a bet, and promotion is its receipt: an object that survives enough young cycles moves to the old region and stops being scanned on every young cycle. heap-layout opens up the spaces and the aging rules; gc-collectors covers the collectors that implement them.
Most objects die young; a survivor is worth betting on, which is exactly why promotion exists.
Stop the world, at a safepoint
To trust the root set, the collector has to read every stack. That is only safe at a safepoint, a point where a thread's state is fully described and its stack can be scanned. So the VM asks every thread to stop, and each thread notices at a poll site: HotSpot inserts safepoint poll instructions into compiled code, typically at method returns and loop back-edges.
The wait for the last thread is time-to-safepoint, and it is charged to the same pause as the collection itself. A pause is therefore two numbers: how long the collector worked, and how long it waited for the threads to park. In logs, the second one shows up as stopping threads took.
- A young region fills and an allocation cannot be satisfied: the VM requests a safepoint.
- Threads park as they reach their next poll. In this window the application is frozen but the collector has not started.
- The last thread arrives, and only then does the collector read the root set and begin marking.
- Marking copies or tags what is reachable; the pause you measure contains the parking wait plus this work.
- Threads resume at the end of the pause. A collection that took 30 ms with 150 ms of parking has a 180 ms pause, and the flag is not the culprit.
- Every thread must arrive: one late thread delays the whole collection, so the world stops for as long as the slowest participant takes.
- Poll sites are deliberate: returns and loop back-edges, which is why a long running compiled loop is usually still checked in.
- The classic stragglers: a loop whose poll was optimized away, native code holding a raw pointer in a JNI critical section, and anything that cannot get back to the VM promptly.
- Handshakes narrow the blast radius: thread-local handshakes (JEP 312, JDK 10) let the VM stop a single thread for some operations, but a whole-heap collection still needs everyone.
GC stops the world at safepoints: where your threads are standing matters as much as what the collector has to do.
GC basics · young cycle then full cycle
Young region
collected often, by copying
Old region
collected rarely, by mark-sweep-compact
Start of a young cycle: the young region holds what was allocated since the last collection. Two temporaries and a two-object cycle are already unreachable, while a session and the cached config are reachable from the running threads.
Throughput, latency, footprint
Three goals compete, and every collector chooses which one it defends. Throughput is the fraction of time spent doing work rather than collecting. Latency is the worst pause, usually judged at a high percentile. Footprint is the memory the collector itself costs, on top of what the program asked for.
You cannot maximize all three, and the trade is real rather than decorative: a bigger heap means fewer collections but a larger footprint; concurrent collection shortens pauses but gives up throughput and costs memory for the collector's own bookkeeping. gc-collectors maps collectors onto these goals; the point here is that tuning starts by naming the goal.
| Goal | Measured as | Bought by |
|---|---|---|
| Throughput | application time divided by application plus collection time | fewer, larger collections and a larger heap |
| Latency | the worst pause, often at a high percentile | concurrent work, smaller regions, short pauses |
| Footprint | heap plus the collector's own overhead | smaller heaps, less concurrency, more collections |
Pick the goal you will be judged on; the other two are the budget you pay for it.
Triggers and hints
Collecting is not scheduled by time and not caused by an object dying. The trigger is allocation: an allocation cannot be satisfied from the current space, so the collector runs to make room. That single sentence explains most GC log frequency.
System.gc() is a hint. Most JVMs honour it with a full or concurrent cycle, which means the JVM that ignores it under load and the JVM that obeys it in a loop both exist; -XX:+DisableExplicitGC removes it from consideration entirely. Correct code never depends on when a collection happens, and libraries that call it for you are a debugging anecdote waiting to happen.
Collection runs because an allocation needed room, not because something died.
Reading a pause in one pass
When a pause shows up in the next lesson's logs, these are the questions in the order that narrows fastest.
- Which region? A young cycle is frequent and cheap because it copies mostly garbage; an old or full cycle is rarer and costs what the live set costs (heap-layout has the spaces).
- Which phases? Copying for the young region, mark then sweep then compact for the old one. The phase names tell you what dominates the time.
- How much of the pause was parking? If stopping threads dominated, hunt the thread that reached no poll, not the collector.
- What triggered it? Allocation failure is the normal answer; an explicit System.gc() in the code or a fullness threshold is a different story.
- Which goal is being defended? Throughput, latency or footprint. Then a collector and its flags have something to optimize for (gc-collectors).
A pause has three parts: parking the threads, doing the work, resuming. Name the biggest one before touching a flag.
Half the pause may not be the collection
A safepoint log line reads: Total time for which application threads were stopped: 0.208 s, Stopping threads took: 0.181 s. The collector worked for about 27 ms and waited 181 ms for one thread to reach a poll, so the real finding is that thread, not the collector. Before tuning anything, split the pause into parking and work, then chase whichever half is actually large.
Interview angles
What does the garbage collector actually guarantee?+
Memory held by unreachable objects becomes reusable at some later point: eventually, not immediately, and with no commitment about timing. It never promises anything about files, sockets or locks, which is why resources need close() rather than collection.
Common misconception: That collection happens when an object becomes unreachable. It happens when an allocation needs room, using whatever is unreachable at that moment.
Why does Java trace instead of reference counting?+
Tracing marks everything reachable from the roots and reclaims the rest, so cycles need no special handling and the cost follows the live set rather than pointer traffic. Reference counting reclaims more promptly but pays on every write and still needs a separate cycle collector.
Follow-up: What does that cost you in practice?
What are mark, sweep and compact, and why is compaction worth its cost?+
Mark tags what is reachable, sweep frees the unmarked slots in place, and compact slides survivors together and fixes references. Compaction turns fragmented holes into one free block, which is what keeps allocation a pointer bump instead of a search.
The moving cost lands in the pause, which is why collectors that chase the lowest latency use different techniques (region remapping, concurrent relocation) instead of a full compact under a stop-the-world pause. gc-collectors has the menu.
What is a safepoint, and why does time to safepoint matter?+
A safepoint is a point in execution where a thread's state is fully described, which is the only state in which its stack can be scanned. The collector cannot start until every thread parks, so the wait for the last one is part of the pause and appears in logs as stopping threads took.
# in a safepoint log line # Total time for which application threads were stopped: 0.208 s, Stopping threads took: 0.181 s
Common misconception: That the pause belongs entirely to the collector. Parking time is charged to the same pause, and a single late thread can dominate it.
What is the generational hypothesis, and what does it buy?+
Most objects die young, and an object that has survived a few collections is likely to keep surviving. Splitting the heap lets frequent cheap collections target the young region while rare expensive ones target the old region.
Follow-up: What happens to an object that survives the young collections?
Does System.gc() force a collection?+
No. It is a hint that most JVMs honour with a full or concurrent cycle, and -XX:+DisableExplicitGC removes even that. No correct program makes a decision that depends on it.
Common misconception: That System.gc() is fine in tests and harmless in production. In production it is a pause request that a library can issue for you at the worst moment.