Home › Categories › Concepts & Theory › Garbage Collection

Garbage Collection

From WikiTech, the encyclopedia of technology

Concept · Concepts & Theory · 5 min read · 982 words · Updated

Garbage Collection
Concept
Garbage Collection — article photograph or illustration
Image placeholderPlace the file shown below in the assets/articles folder
File: garbage-collection.webp
IntroducedLisp, circa 1959
FamiliesReference counting, tracing, generational
AlternativesManual, ownership (Rust), arenas

Garbage collection (GC) is a form of automatic memory management in which a runtime system identifies objects that a program can no longer reach and reclaims their memory.[2] Because the runtime does this work, the programmer does not call free or delete explicitly, which removes whole categories of bugs such as use-after-free errors and double frees.

The technique was invented for the Lisp language and described by John McCarthy in 1960.[1] It is now built into the runtimes of Java, C#, Go, JavaScript, Python and many other languages. Its main cost is that reclaiming memory consumes processor time and can pause the program, so much of the research on the subject concerns reducing those pauses.

History

McCarthy's 1960 paper on Lisp described a mark-and-sweep collector to recover list cells automatically. In the same year George Collins published reference counting as an alternative. Over the following decades researchers refined the idea: Cheney's 1970 algorithm made copying collection practical, and generational collectors, developed in the 1980s by Henry Lieberman, Carl Hewitt and David Ungar, exploited the observation that most objects die young.

Garbage collection moved from academic languages to the mainstream in the mid-1990s with Java, whose virtual machine made automatic memory management a default expectation for application developers.

Core idea: reachability

A collector begins from a set of roots, such as local variables on thread stacks, global variables and processor registers. Any object that can be reached by following references from a root is considered live. Everything else is garbage. This definition is conservative: an object that is reachable but will never be used again is still kept, which is why memory leaks remain possible even in managed languages, typically through forgotten references in caches or listeners.

Main families

Reference counting

Each object stores a count of the references pointing to it. When the count drops to zero, the object is freed at once. The strengths are prompt reclamation and predictable timing. The weaknesses are the cost of updating counts on every assignment and the inability to free reference cycles, where two objects point to each other. CPython uses reference counting as its primary mechanism and adds a separate cycle detector for the cycles.[4] Swift uses automatic reference counting at compile time.

Tracing collectors

Tracing collectors find live objects by traversing the object graph.

  • Mark and sweep marks every reachable object, then scans the heap and frees the unmarked ones. It leaves free space fragmented.
  • Mark and compact also slides live objects together to remove fragmentation.
  • Copying collectors split the heap into regions and copy live objects into a fresh one. Allocation then becomes a cheap pointer bump, and the cost depends on the amount of live data rather than the amount of garbage.

Generational collection

The weak generational hypothesis states that most objects die shortly after allocation. Generational collectors divide the heap into a young generation, collected frequently and cheaply, and an old generation, collected rarely. Objects that survive several young collections are promoted. A write barrier records references from old to young objects so that the young generation can be collected without scanning the whole heap.

Incremental, concurrent and parallel collection

To limit pauses, collectors may work in small increments, run alongside the application on other threads, or use several threads at once. Java's G1 collector became the default in JDK 9, and the low-pause ZGC reached production status in JDK 15. Go uses a concurrent tri-colour mark-and-sweep collector tuned for low latency, with a configurable balance between memory use and CPU time.[3]

Costs and trade-offs

Garbage collection trades some performance and memory for safety and productivity.

ConcernEffect
ThroughputCollector work takes CPU time, often a small share of the total
LatencyStop-the-world phases can pause the application
MemoryHeaps usually need headroom above the live size
PredictabilityTiming of reclamation is less deterministic than manual freeing
FinalisationRunning code when an object dies is unreliable and discouraged

For most business and web applications these costs are acceptable. They matter more in real-time systems, games with strict frame budgets, and very large heaps, where tuning the collector becomes a specialist task.

Alternatives

Manual management, as in C, gives complete control but makes memory errors the programmer's responsibility. C++ reduces the burden with RAII and smart pointers. Rust enforces ownership rules at compile time, so memory is freed at a point the compiler can determine, with no runtime collector. Region or arena allocation frees a whole group of objects at once, which suits request-scoped work in servers and compilers.

Common misconceptions

Garbage collection does not eliminate memory leaks; it only removes leaks caused by lost pointers. It also does not mean that programmers can ignore allocation: creating huge numbers of short-lived objects still increases collector work. Finally, a garbage-collected language is not inherently slow. Allocation in a copying collector can be faster than calling a general-purpose malloc, and well-tuned runtimes compete with native code on many workloads.

Choosing a collector, or deciding whether to use one at all, is therefore an engineering decision about latency, throughput and memory, and not a question of good versus bad design.

Editorial connections and engineering implications

Reachability, pauses and resource lifetime

Tracing garbage collectors begin from roots such as stack references and globals, then follow references to find reachable objects. Unreachable objects can be reclaimed. Generational collectors exploit the fact that many objects are short-lived; incremental and concurrent collectors spread work over time to reduce long pauses. Reference counting instead reclaims an object when its reference count reaches zero, although cycles require additional handling. CPython combines reference counting with a cyclic collector, while other runtimes use different strategies.

Garbage collection does not remove the need to manage files, sockets, transactions or locks. Those resources may need to be released at a precise point even if a wrapper object remains reachable. Explicit close operations and context managers provide deterministic cleanup. Tracing collection is productive for many application workloads, while ownership systems such as Rust make lifetimes explicit and manual allocation remains common in C. The right model depends on latency, memory limits and the complexity a team can maintain.

See also

  • C (programming language) – A general-purpose, statically typed systems programming language created at Bell Labs in the early 1970s.
  • C++ – A general-purpose, statically typed language that extends C with classes, templates and zero-overhead abstractions.
  • Rust – A compiled systems programming language that enforces memory safety through ownership and borrowing without a garbage collector.
  • JavaScript – The programming language that powers interactive web pages and a large ecosystem of browser, server and desktop software.
  • Python – A high-level, dynamically typed programming language that emphasises readability.
  • Big-O Notation – A notation describing how the resource use of an algorithm grows as the input size grows.
  • CAP Theorem – A result stating that a distributed data store cannot simultaneously guarantee consistency, availability and partition tolerance.
  • Event Loop – A programming construct that waits for and dispatches events or messages in a single thread of control.

References

  1. ↑ McCarthy (1960), Recursive functions of symbolic expressions and their computation by machine, Part I (doi.org)
  2. ↑ The Garbage Collection Handbook (gchandbook.org)
  3. ↑ Go documentation: A Guide to the Go Garbage Collector (go.dev)
  4. ↑ Python documentation: gc, the garbage collector interface (docs.python.org)