Card 03/ 09
Garbage Collection and Reachability
You never free anything, the heap does not fill up, and the rule deciding what goes is exact.
The garbage collector keeps every object that can be reached by following references from a fixed set of starting points, called roots, such as the local variables of running methods and static fields. Everything it cannot reach is removed, whether or not your code has finished with it.
You never free anything in Java, and the heap (the memory where Java keeps every object) does not fill up. Something is deciding what to remove, and it does not look for objects that are finished with. It starts from the roots:
| Root | Example |
|---|---|
| Local variables in every live stack frame (the space for one running method call) | rows inside a method that is still running |
| Static fields | A cache held in a static Map |
| References held by running threads (paths of execution) | 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.
The collector runs when the JVM decides it is worth it, usually when the heap is filling, so an unreachable object is eligible for removal rather than removed at once.
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.
← → move through sections and cards