🧹 Garbage collection: cheat sheet
🎨 The analogyA playroom cleaner who only throws out toys nobody can reach any more, tidying the new-toy box most often.
🎓 The regular explanationHow the JVM frees memory for you. It finds objects that can no longer be reached from any variable and reclaims them, collecting short-lived objects often and long-lived ones rarely.
- Every toy that's tied, by a string, to the toy box rope is in use. The teddy is tied to the rope, and its hat is tied to the teddy.
- Someone cuts the balloon's string. Nothing ties it to the rope any more.
- 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 safe to throw away.
- The balloon goes in the bin, and its spot is free for the next new toy.
- New toys go into the just-used box. Most get played with once and forgotten.
- When the box is full, the cleaner tidies just that box. Nearly everything in it is already forgotten, so it's quick.
- A toy that keeps being played with, tidy after tidy, moves to the favourites shelf.
- The favourites shelf is tidied rarely. It takes longer, but it doesn't need doing often.
- The simplest way to tidy is to say "everybody freeze!", clean up, then let everyone carry on.
- A cleverer cleaner does most of the tidying while everyone keeps playing, and only asks for a freeze of a blink.
- The trade-off is that the cleaner takes some of everyone's time while tidying alongside them.
🧩 Key questions
- Which toys does the cleaner throw away?
- Toys nobody can reach by following strings from the toy box rope. Anything without a sticker can't be reached by anyone, so nobody has to say "I'm done".
- Why does the cleaner tidy the just-used box often?
- Because almost everything in it is already forgotten, so tidying is quick. Toys that survive several tidies move to the favourites shelf, which is tidied rarely.
- What do modern cleaners do differently?
- Tidy while everyone keeps playing, with only a blink of a freeze. "Everybody freeze" is easy, but nobody can play while it happens.