TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About · Labs · Cheat sheets · Learning paths

← Back to Garbage collection

🧹 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.
What can still be reached?Step 5 of 5
refref🪢Toy box rope🧸Teddymarked🎩Teddy's hatmarked🧹Cleaner
  1. 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.
  2. Someone cuts the balloon's string. Nothing ties it to the rope any more.
  3. The cleaner follows every string from the rope and puts a sticker on each toy it reaches.
  4. Anything without a sticker can't be reached by anyone, so it's safe to throw away.
  5. The balloon goes in the bin, and its spot is free for the next new toy.
New toys and old favouritesStep 4 of 4
Just-used box · emptiedr1key request object: r10t1key temp object: t11t2key temp object: t22t3key temp object: t33sessess4Favourites shelfsessess0123🏠Playroom🧹Cleaner
  1. New toys go into the just-used box. Most get played with once and forgotten.
  2. When the box is full, the cleaner tidies just that box. Nearly everything in it is already forgotten, so it's quick.
  3. A toy that keeps being played with, tidy after tidy, moves to the favourites shelf.
  4. The favourites shelf is tidied rarely. It takes longer, but it doesn't need doing often.
Stop and tidy, or tidy while playingStep 3 of 3
🧒Player 1running👧Player 2running🧹Cleanerconcurrent
  1. The simplest way to tidy is to say "everybody freeze!", clean up, then let everyone carry on.
  2. A cleverer cleaner does most of the tidying while everyone keeps playing, and only asks for a freeze of a blink.
  3. 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.