Reachability & garbage collection
Nothing is freed because you stopped using it. It is freed because nothing can reach it.
Before you start
In C, you free memory yourself. In Java, the runtime does it — the **garbage collector** periodically scans the heap and reclaims objects nothing can still reach.
"Reach" is the key word. The GC starts from *roots* (local variables in running methods, static fields) and follows every reference. Anything it finds is alive. Anything it doesn't is garbage.
This lesson visualises reachability: watch objects get orphaned when the last reference to them is dropped, and see why holding a reference in a long-lived collection is the classic Java "memory leak".
Stack
GC roots: locals on any live frame, and static fieldsHeap
collected when unreachable, not when unusedTwo roots, two objects, both directly reachable.
Step 1 of 7. Collection starts from the roots. The collector does not track when you stop using a variable. It starts from a set of **GC roots** — local variables on live stack frames, and static fields — and follows every reference it can. Anything it reaches is live. Everything else is garbage, whatever your intentions were.
Step 01 / 07
Collection starts from the roots
The collector does not track when you stop using a variable. It starts from a set of **GC roots** — local variables on live stack frames, and static fields — and follows every reference it can.
Anything it reaches is live. Everything else is garbage, whatever your intentions were.
public class Main { static Node cache; // a GC root: static field public static void main(String[] args) { Node a = new Node("A"); Node b = new Node("B"); a.next = b; // b reachable through a cache = new Node("C"); b = null; // still reachable via a.next a = null; // now A and B are both garbage Node d = new Node("D"); d.self = d; // self-reference, still garbage d = null; }}