Garbage Collection Algorithms

Automatic memory management — reachability and roots, reference counting, mark-sweep, mark-compact, copying collectors, generational GC, tri-colour marking, incremental and concurrent collection, write barriers, and how real runtimes combine them.

Advanced 6 min readLesson 8 of 8 Interview Q&A

Garbage collection (GC) frees memory the program can no longer use, so programmers don't call free. It eliminates use-after-free and double-free bugs and most leaks, at the cost of CPU overhead, extra memory and (sometimes) pauses.

What is garbage?

An object is live if the program could still access it. Since that's undecidable in general, collectors use a conservative approximation: reachability. An object is live if it can be reached by following pointers from the roots:

  • Local variables and temporaries on thread stacks and in registers.
  • Global/static variables.
  • References held by the runtime (JNI handles, interned strings, class metadata).

Everything unreachable is garbage.

rootABCDE
Green: reachable from roots. Red: an unreachable cycle — garbage to a tracing GC, but leaked by naive reference counting

Reference counting

Each object stores a count of references to it; when the count drops to zero, free it immediately (and decrement everything it points to).

ProsCons
Memory reclaimed promptly and predictablyCan't collect cycles without extra machinery
No global pauses (mostly)Every pointer write updates counts — overhead, and atomic ops when multithreaded
Simple; deterministic destructorsFreeing a big structure cascades (a pause of its own)

Used by CPython (plus a cycle detector — Python memory), Swift/Objective-C (ARC), Rust's Rc/Arc (Smart pointers), C++ shared_ptr, and COM.

Tracing collectors

Tracing GCs periodically find live objects by traversing from the roots.

Mark-sweep

  1. Mark: traverse from the roots, setting a mark bit on each reachable object.
  2. Sweep: scan the whole heap; add unmarked objects to a free list.

Simple and handles cycles, but the heap becomes fragmented (free space scattered in small holes), allocation from free lists is slower, and sweeping is proportional to heap size.

Mark-compact

Mark, then slide live objects together to one end of the heap and update all pointers. No fragmentation, and allocation becomes a fast bump pointer (just increment a pointer). Compaction is expensive (multiple passes over the heap).

Copying (semispace) collection

Divide the heap into two halves. Allocate in one ("from-space"); when it fills, copy live objects to the other ("to-space"), compacting as you go, then swap roles. Cheney's algorithm does this with a breadth-first scan, using to-space itself as the queue.

Mark-sweepMark-compactCopying
Work proportional toHeap size (sweep)Live data + heapLive data only
FragmentationYesNoNo
AllocationFree listBump pointerBump pointer
Space overheadLowLow2× (half is idle)

Generational collection

The weak generational hypothesis: most objects die young (temporaries, iterators, request-scoped data). So split the heap:

Young generation (copying, frequent, fast)Old (mark-compact, rare)minor GC: copy survivorspromote after N GCsEdennew allocationsSurvivor spacesS0 / S1Old generationlong-lived objects
  • Minor GCs collect only the young generation, often and cheaply — a copying collector does work proportional to the (few) survivors.
  • Objects surviving several minor GCs are promoted to the old generation, collected rarely with mark-sweep or mark-compact.
  • Remembered sets / card tables track old → young pointers so minor GCs needn't scan the whole old generation. A write barrier (a few instructions added to each pointer store) records them.

Used by the JVM (JVM memory and GC), V8 (Scavenger + Mark-Compact), .NET and CPython's cycle collector.

Avoiding long pauses

A naive tracing GC stops the world — pausing all application threads while it runs. For large heaps that can take seconds. Modern collectors reduce pauses:

TechniqueIdea
IncrementalInterleave small slices of GC work with the program
ConcurrentGC threads mark (and even compact) while application threads run
ParallelUse many threads during pauses to finish faster
Region-basedDivide the heap into regions; collect the ones with the most garbage first (G1)

Tri-colour marking

Incremental and concurrent marking are described with three colours:

  • White: not yet seen (garbage if still white at the end).
  • Grey: reached, but its children not yet scanned.
  • Black: reached, and all children scanned.

Marking moves objects white → grey → black until no grey remain. The danger: while marking runs, the program (the mutator) might store a pointer to a white object into a black object and remove all other paths to it — the collector would never see it and would free a live object. Write barriers prevent this, either by greying the target when such a store happens (incremental update / Dijkstra) or by recording the overwritten pointer (snapshot-at-the-beginning / Yuasa, used by G1).

Concurrent compaction additionally needs read barriers or forwarding pointers so the program finds objects that were moved — the approach of the JVM's ZGC and Shenandoah, which keep pauses under a millisecond on terabyte heaps.

Real runtimes

RuntimeCollector
JVMG1 (default; regional, generational), ZGC and Shenandoah (concurrent compaction, sub-ms pauses), Parallel (throughput)
GoConcurrent, non-generational, non-moving tri-colour mark-sweep tuned for low latency (GOGC, GOMEMLIMIT)
V8Generational: parallel Scavenger for young objects; concurrent/incremental mark-compact (Orinoco) for old
.NETGenerational (gen 0/1/2 + large object heap), workstation and server modes
CPythonReference counting + generational cycle detector
SwiftARC (compiler-inserted reference counting), no tracing GC
Rust, C, C++No GC: ownership/RAII and manual management

Trade-offs

Every collector balances three goals — you can usually optimise two:

  • Throughput: total fraction of time not spent in GC.
  • Latency: maximum pause length.
  • Footprint: extra memory needed (GCs typically need 1.5–3× the live data to run efficiently).
Key takeaways
  • GC frees unreachable objects: reachability from roots (stacks, globals, runtime handles) approximates liveness.
  • Reference counting is prompt but leaks cycles and taxes every pointer write.
  • Mark-sweep fragments; mark-compact and copying collectors compact and allow bump-pointer allocation.
  • Generational GC exploits "most objects die young": frequent cheap young collections, rare old collections, write barriers for old → young pointers.
  • Tri-colour marking with write barriers enables incremental and concurrent collection; read barriers enable concurrent compaction (ZGC, Shenandoah).
  • Collectors trade throughput, latency and memory footprint.
Interview questions
QWhy do generational garbage collectors work well?medium

Because of the weak generational hypothesis: most objects die shortly after allocation. Allocating them in a small young generation and collecting it frequently with a copying collector costs time proportional only to the few survivors, so most garbage is reclaimed almost for free. Long-lived objects are promoted to an old generation that is collected rarely. A write barrier and card table record old-to-young pointers so a minor GC doesn't need to scan the old generation.

QHow does reference counting handle cycles?medium

By itself, it doesn't: objects in a cycle keep each other's counts above zero even when nothing outside points to them. Solutions are weak references for back-pointers (Swift weak/unowned, Rust Weak), or a supplementary cycle detector that periodically traces candidate objects, as CPython's gc module does.