Skip to content
Optimal Lab

Operating systems · interactive

Garbage collection

A garbage collector frees objects your program can no longer reach. Reference counting frees things the moment nothing points at them, but misses cycles. Mark and sweep traces from the roots and frees everything it didn't reach.

rootusercartitemsprefsoldTaboldViewtmp

Filled: marked reachable. Dashed red: swept.

Mark and sweep starts from the roots: globals, the stack, registers.

Collector

step 1 of 7

Step 3 of 4

  1. 1

    Reachable means alive

    Anything you can get to from a root (globals, the stack) might still be used. Everything else is garbage.

    You can't leak what you can't reach… almost.

  2. 2

    Reference counting

    Free an object when its count hits zero. Immediate and predictable, but cycles keep each other alive.

    Swift, Rust's Rc; Python adds a cycle collector.

  3. 3

    Mark and sweep

    Mark everything reachable from the roots, then free the rest. Cycles aren't a problem.

    JavaScript, Java, Go, C#.

  4. 4

    Generations and pauses

    Most objects die young, so collectors scan new objects often and old ones rarely. Real leaks are objects still reachable: forgotten listeners, caches, globals.

    Heap snapshots find what holds them.

In production

Tools and technologies

Managed runtimes all trace the heap; some also count references.

Not tied to one language — use these names when you search docs or design a system.