Learning path

Full curriculum

Full curriculum

Unit content

Automatic memory management and object reachability

A runtime with automatic memory management reclaims storage when the program can no longer use the objects stored there.

Many managed runtimes keep dynamically created objects in a heap: a pool of storage whose objects can outlive the function call that created them. The runtime must determine which of those objects can still affect future execution.

For tracing garbage collection, the key idea is reachability. The runtime starts from roots—references that are known to be immediately available to the running program, such as active local variables, global references and some runtime-held references—and follows references from object to object.

An object is reachable if some path of references leads to it from a root. Reachable objects must be retained. If no such path exists, the object is unreachable and its storage can eventually be reclaimed.

root ─→ A ─→ B

       C ↔ D

Here A and B are reachable. If nothing reachable refers to C or D, their cycle does not keep them alive: both are garbage.

This is why tracing collectors handle cycles naturally. By contrast, merely counting incoming references cannot by itself distinguish an unreachable cycle from a live structure.

A collector also needs to know which stored values should be interpreted as references. Precise collectors use information supplied by the language implementation, while conservative collectors may treat some machine words as possible references when their exact meaning is unavailable.

Reachability is a program-level liveness criterion, not the same task as allocating storage. An allocator finds space for objects; a garbage collector determines when managed objects are no longer reachable and can return their storage for reuse.