Toys on strings
In this playroom, every toy in use is tied by a string to the toy box rope, either directly or through another toy. The teddy is tied to the rope, and its hat is tied to the teddy.
The cleaner follows every string from the rope and puts a sticker on each toy it reaches. Anything without a sticker can't be reached by anyone, so it's thrown away. Nobody has to say "I'm done with this".
Reachability
Java has no free(). The garbage collector reclaims objects that are unreachable: not referenced, directly or
through other objects, from any GC root. Roots include local variables on every thread's stack, static fields,
and JNI references.
Collection starts by marking everything reachable from the roots; unmarked memory is reclaimed. Cycles aren't a problem: two objects pointing at each other but unreachable from a root are both collected.
A memory leak in Java is an object you no longer need but that is still reachable, like entries in a static map that nobody removes.
The just-used box
Most toys are played with once and forgotten. So new toys go into a just-used box, which the cleaner tidies often, and quickly, because almost everything there is already forgotten. Toys that survive several tidies move to the favourites shelf, which is tidied rarely.
Generations
The generational hypothesis: most objects die young. So the heap is split:
- Young generation: new objects are allocated in eden. Minor GCs collect it often; survivors are copied to survivor spaces, and after enough GCs, promoted.
- Old generation: long-lived objects, collected less often by major (or G1's mixed) collections.
Copying the few survivors is cheaper than scanning all the garbage, so minor GCs are fast.
Freezing while tidying
The easiest way to tidy is "everybody freeze!", but nobody can play while that happens. Modern cleaners tidy while everyone keeps playing, and only ask for a freeze of a blink.
Pauses and collectors
Stop-the-world pauses halt every application thread, which shows up as latency spikes.
| Collector | Aims for |
|---|---|
| G1 (default) | A balance, with a pause-time target (-XX:MaxGCPauseMillis=200) |
| ZGC / Shenandoah | Pauses under a millisecond, even on huge heaps |
| Parallel | Maximum throughput, for batch jobs |
Watch GC with -Xlog:gc or JDK Flight Recorder, and size the heap with -Xmx.