Back to results for “Design Patterns in Java”
JavaScript › Memory Management & Garbage Collection

How does mark-and-sweep garbage collection actually determine which objects are reachable?

Advanced

Answer

The collector starts from a set of 'roots' (global objects, currently executing call stack, active closures) and traverses every reference reachable from them, marking each visited object as live; anything left unmarked after this traversal is unreachable garbage and gets swept (freed).
// Roots -> traversal example (conceptual)
// window -> app -> currentUser -> profile (all marked reachable)
// an object with zero incoming references from any root is swept
Real-world example Explaining why two objects that only reference EACH OTHER, but nothing else references them, are still correctly collected (unlike naive reference counting).

Common follow-ups: Why does mark-and-sweep handle circular references correctly, unlike simple reference counting?