Card 03/ 09

ConceptDifficulty: Intermediate1 min

What Keeps an Object Alive

You never free anything in Java, and the heap does not fill up. Something is deciding what to remove, and the rule it uses is worth knowing exactly.

The collector does not look for objects that are finished with. It looks for objects that can still be reached, starting from a fixed set of roots, and everything it does not reach is removed.

Where the collector starts looking
RootExample
Local variables in every live stack framerows inside a method that is still running
Static fieldsA cache held in a static Map
References held by running threadsThe object a thread is working on
Reachable objects survive; an unreferenced chain is collected whole

Order and Customer survive because a path from a root reaches both. Receipt and Address point at each other's world and nothing points at them, so both go — reachability is about paths from roots, not about how many references exist.

So the question to ask about any object is never "am I finished with it" but "does anything still hold a path to it". Those two come apart exactly where memory leaks live.