Reachability and the Root Set
You'll learn: How a garbage collector decides which objects are still in use and which are safe to delete.
The Core Problem
When a program runs, it creates objects in memory. Some of those objects are actively being used, while others are forgotten leftovers. But how does a garbage collector tell them apart? It can't read your mind or understand your program's logic—it needs a systematic way to determine what's "alive" and what's "garbage."
The Root Set: Where Life Begins
The root set is the starting point for reachability analysis. It includes:
- Global variables: Variables accessible throughout the program
- Local variables on the stack: Currently active function parameters and variables
- CPU registers: Values temporarily held in processor registers
Think of these roots as the "known addresses" in your program—places where your code can directly reach right now.
Reachability: Following the Chain
An object is reachable (alive) if you can get to it by starting from the root set and following references. Imagine a web of interconnected objects: if there's a path of pointers from any root to an object, that object is reachable and therefore live.
An object is unreachable (garbage) if no such path exists. It's floating in memory with no way for your program to ever access it again.
The Web Analogy
Think of your program's memory like a city. The root set is the set of houses where people currently live. Streets (pointers) connect houses. A building is "alive" if someone can walk to it from an occupied house. Abandoned buildings with no roads leading to them? That's garbage—safe to demolish.
Key Takeaway: Objects reachable from the root set through any chain of references are live; all unreachable objects are garbage and can be safely reclaimed.