Card 03/ 09
All 9 cards
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.
| Root | Example |
|---|---|
| Local variables in every live stack frame | rows inside a method that is still running |
| Static fields | A cache held in a static Map |
| References held by running threads | The object a thread is working on |
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.