The Plain Picture#
Three ways to clean a messy room:
Sweep: throw away the rubbish and leave everything else where it is. Fast, but the free spaces are scattered — a big new box may not fit anywhere.
Compact: throw away the rubbish, then push everything you keep to one side, so all free space is one big block. Slower, tidier.
Copy: carry everything you keep into a second, empty room, then declare the first room empty. Fast when you keep little; needs a spare room.
The Real Names#
| Algorithm | Steps | Good | Bad | Used for |
|---|---|---|---|---|
| mark–sweep | mark live objects; free the rest in place | no moving | fragmentation: free memory in scattered holes | (older) old-generation collectors |
| mark–compact | mark; slide live objects together | no fragmentation, no spare space | moving objects and fixing every reference to them is expensive | old generation |
| copying | copy live objects to a fresh area | very fast when few survive; no fragmentation | needs spare space; expensive when many survive | young generation (Ch 6) |
Stop-the-world (STW): while a collector moves objects or examines roots, it must stop all application threads — otherwise threads would read references to objects that are being moved. Every STW pause is a moment when no request is served (Part 0's problem 1: 800 ms spikes = long pauses).
Concurrent collection: modern collectors do most of their marking (and even compaction) while application threads keep running, keeping STW pauses very short. It's hard, because the application keeps changing references during marking; collectors use barriers — small pieces of code the JIT inserts around reference reads/writes — to track those changes. The trade-off: some CPU overhead and throughput for much shorter pauses.
Two goals that pull against each other:
Throughput — the percentage of time spent running the application rather than collecting (batch jobs care).
Latency — the length of individual pauses (APIs care: pauses show up as slow requests at the high percentiles — "p99 latency", Scalability Basics (coming soon)).
Check yourself
4 questionsMark–sweep vs mark–compact vs copying — one downside each?
Show answerHide answer
Mark–sweep: fragmentation. Mark–compact: expensive moving and reference updating. Copying: needs spare space and is slow when many objects survive.
What is a stop-the-world pause, and why is it needed?
Show answerHide answer
All application threads are paused so the collector can safely examine and move objects without references changing underneath it.
What do concurrent collectors do differently, and what do they pay for it?
Show answerHide answer
They do most work while the application runs, keeping pauses short; they pay with CPU overhead (barriers, GC threads) and some throughput.
Throughput vs latency — which does an API server usually care about more?
Show answerHide answer
Latency (short pauses), because pauses directly become slow requests.