{
  "id": "garbage-collection",
  "title": "Garbage Collection",
  "lang": "en",
  "source_lang": "en",
  "summary": "Garbage collection automatically reclaims memory that a program can no longer access, balancing safety, execution speed, memory consumption, and responsiveness.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "Automatic garbage collection",
    "GC"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/garbage-collection/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/garbage-collection/",
      "json": "https://aiwiki.page/zh/garbage-collection.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "Garbage collection is a form of automatic memory management that identifies storage no longer accessible to a running program and makes that storage available for reuse. It usually operates on dynamically allocated objects in a program’s heap, rather than on files, persistent records, or physical waste. Garbage collection is a central component of many programming languages and their runtime systems, allowing programs to create interconnected objects without explicitly specifying when each object’s memory must be released.\n\nIts importance lies in separating the useful lifetime of an object from the programmer’s responsibility for deallocation. Correctly implemented garbage collection prevents entire classes of errors involving premature deallocation, including dangling references and repeated release of the same allocation. It does not, however, eliminate every memory-management problem: a program can retain objects unnecessarily, exhaust available memory, or fail to release resources outside the managed heap.\n\nGarbage collectors differ in how they identify unused objects, organize memory, and coordinate with application execution. Reference counting tracks changes to object references; tracing collectors discover objects reachable from designated starting points. Copying, compaction, generational organization, and concurrent execution refine these approaches. Their design involves trade-offs among processing overhead, memory requirements, pause duration, implementation complexity, and compatibility with native code."
    },
    {
      "heading": "Origins and historical development",
      "text": "Automatic storage reclamation became important as programming moved beyond fixed arrays and simple record layouts toward dynamically constructed lists, trees, and graphs. In these structures, several parts of a program may share an object, and its lifetime need not coincide with a particular procedure call. Explicitly deciding which component owns the object can become difficult, especially when objects form cycles or are passed through many layers of abstraction.\n\nJohn McCarthy introduced a garbage-collection method for Lisp, described in his 1960 paper “Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I.” Lisp programs represented symbolic expressions using linked structures whose storage requirements changed during execution. McCarthy’s collector traced accessible structures and reclaimed unused list cells, establishing the basic pattern later called mark-and-sweep. Also in 1960, George E. Collins published a reference-counting approach, illustrating that automatic reclamation could be organized around local reference updates rather than periodic tracing.\n\nSubsequent work addressed the costs of moving objects, traversing large heaps, and interrupting execution. Robert R. Fenichel and Jerome C. Yochelson described a copying approach in 1969. C. J. Cheney’s 1970 algorithm provided a particularly influential nonrecursive method for copying reachable objects, using the destination memory itself as a traversal queue. Instead of needing a separate stack proportional to graph depth, Cheney’s method maintained scan and allocation positions within the copied region.\n\nDuring the 1970s, researchers increasingly studied collection as a problem in concurrent computing. Edsger W. Dijkstra and collaborators published their on-the-fly garbage-collection work in 1978, showing how a collector and a running program could cooperate through carefully maintained invariants. Henry G. Baker’s 1978 work on list processing in real time developed an incremental copying approach. These contributions established that garbage collection need not always be a single uninterrupted traversal performed while the entire application is stopped.\n\nGenerational techniques became prominent through work including Henry Lieberman and Carl Hewitt’s 1983 paper and David Ungar’s 1984 work on generation scavenging. Their practical appeal came from exploiting observed object-lifetime patterns rather than treating every allocation identically. During the following decades, garbage collection became standard infrastructure in Java runtimes, JavaScript engines, the .NET runtime, and many other systems. Modern collectors combine ideas from several historical families: a runtime may use copying for young objects, marking for older objects, and concurrent processing to reduce interruptions."
    },
    {
      "heading": "Objects, roots, and reachability",
      "text": "The central abstraction of tracing collection is a directed graph. Heap objects are vertices, and references stored in those objects are edges. An object representing a tree node, for example, may contain references to its children, its parent, and auxiliary metadata. The collector does not need to understand the application-level meaning of these relationships; it needs to know which machine values represent references and where those references lead.\n\nTraversal begins from a set of roots. These commonly include references in global variables, active thread stacks, processor registers, runtime tables, and handles maintained for native code. If the heap objects form a set \\(V\\), references form an edge set \\(E\\), and directly referenced heap roots form a set \\(R\\), the reachable set is\n\n\\[L=\\{v\\in V\\mid \\text{a path from some }r\\in R\\text{ reaches }v\\}.\\]\n\nObjects in \\(V\\setminus L\\) are candidates for reclamation. A cycle does not defeat this definition: two objects that reference each other are still garbage if no path from a root reaches either one.\n\nReachability is a practical approximation to future usefulness, not a direct prediction of future execution. An object may remain reachable even though the program will never read it again. For example, a global collection may retain every request ever processed, or a callback registry may retain an object after its intended use has ended. The collector cannot normally distinguish these cases from deliberately preserved state. Determining exactly whether an arbitrary object will be used again would require reasoning about future program behavior and, in the general case, encounters limits associated with the halting problem.\n\nThe boundary between reachable and unreachable objects depends partly on implementation. A compiler can determine that a local reference is no longer needed before its source-level scope ends, allowing the object to become collectible earlier. Conversely, interpreter frames, native-call interfaces, or conservative stack scanning may keep an object alive longer. Debug builds and optimized builds can therefore exhibit different apparent object lifetimes without changing the program’s specified results.\n\nGarbage collection generally concerns heap storage, while stack frames usually follow procedure activation and return. The distinction is not absolute: closures can preserve variables beyond their original calls, and compilers can transform allocations. Through escape analysis, an implementation may establish that an object never escapes a local context, allocate it on the stack, or eliminate the allocation altogether. Such optimizations reduce collection work but are separate from discovering unreachable heap objects."
    },
    {
      "heading": "Reference counting and cyclic structures",
      "text": "Reference counting associates an object with a count of incoming owning references. Creating or copying an owning reference increases the count; removing or replacing one decreases it. When the count reaches zero, the object can be reclaimed. Releasing that object’s fields can reduce other counts to zero, producing a cascade of reclamation.\n\nThis approach distributes much of its work across normal program operations. It often releases acyclic structures soon after their final owning reference disappears, making memory usage relatively easy to relate to program behavior. It also avoids requiring a whole-heap traversal merely to identify a single newly unused object. Reference counting is used in several forms, including the principal reclamation mechanism in CPython and the compiler-inserted retain and release operations associated with automatic reference counting in Objective-C and Swift.\n\nIts defining limitation is cyclic ownership. Suppose object \\(A\\) owns a reference to \\(B\\), and \\(B\\) owns a reference to \\(A\\). After all external references disappear, both counts may remain positive even though neither object is accessible to the application. Larger cyclic graphs have the same problem. Some systems require programmers to break cycles using non-owning links; others supplement counting with a cycle detector. CPython, for example, combines reference counting with cyclic garbage collection for supported container objects.\n\nThe cost of counting is not confined to the count field itself. Assignments may require increments and decrements, adding memory traffic and interfering with optimization. In a multithreaded environment, updating shared reference counts can require atomic operations or other synchronization, potentially causing contention on a processor cache line. Implementations reduce these costs by eliminating redundant updates, distinguishing local from shared ownership, deferring some operations, or exploiting information supplied by the type system.\n\nPrompt reclamation also does not imply uniformly short execution times. Destroying one object can trigger the release of a large reachable ownership graph, so a single decrement may initiate substantial work. Implementations may defer or batch this work, but doing so weakens the simplicity of immediate reclamation. User-defined destruction code can further complicate timing, reentrancy, and error handling.\n\nTerminology varies across language communities. Some use “garbage collection” broadly enough to include reference counting; others reserve it mainly for tracing systems and describe counting separately. The underlying technical distinction is more useful than the label: counting derives reclamation from changes in ownership, whereas tracing derives it from reachability starting at roots. Hybrid systems can combine both forms of evidence."
    },
    {
      "heading": "Tracing, sweeping, copying, and compaction",
      "text": "A tracing collector discovers live objects by following references from roots. In the simplest stop-the-world form, application threads pause while the collector establishes a stable view of the object graph. The collector visits each reachable object, records that it is live, and inspects its reference fields. Traversal can use an explicit worklist, a stack, or specialized methods that temporarily encode traversal state within objects.\n\nIn mark-and-sweep collection, the marking phase records liveness, often in object headers or a separate bitmap. A subsequent sweep examines allocation areas and returns unmarked objects to free storage. With suitable representations, marking work is proportional to the live objects and references inspected, while sweeping is proportional to the allocation metadata or heap regions examined. The exact time complexity depends on the representation rather than on the algorithm’s name alone.\n\nMark-and-sweep can leave free memory divided into many gaps. This fragmentation may prevent a large allocation even when the sum of free space is sufficient. Size-segregated free lists, fixed-size allocation classes, and region-based layouts reduce the problem but do not eliminate every form of fragmentation. A mark-compact collector instead moves surviving objects together and repairs their references, making larger contiguous areas available. Compaction adds relocation work but can simplify later allocation.\n\nA copying collector moves reachable objects from one allocation area into another. In the classic semispace arrangement, the heap is divided into two spaces: allocation occurs in one, and collection copies survivors into the other before the roles reverse. A forwarding pointer or equivalent record ensures that an object reached through several paths is copied only once. Cheney’s algorithm scans copied objects in allocation order, appending newly discovered objects after those already copied until the scan pointer reaches the allocation pointer.\n\nCopying is especially attractive when only a small fraction of allocated objects survive. Unreachable objects require no individual sweep or destruction: the old space becomes reusable as a whole. Allocation into the destination can use a simple bump pointer, and copied objects are packed closely together. The principal costs are reserve space, movement of live data, and updating references. A conventional equal-sized semispace design reserves half its managed area as the copying destination, although more elaborate collectors do not have this exact requirement.\n\nMovement is possible only when references can be found and adjusted, or mediated through handles or barriers. Objects exposed to native code may need to be pinned so their addresses remain stable. Large objects are often treated separately because moving them is expensive. Consequently, a practical collector may combine copying, nonmoving mark-and-sweep, and selective compaction within different parts of one heap."
    },
    {
      "heading": "Generational and region-based collection",
      "text": "Generational collection exploits the empirical observation that many programs allocate numerous objects that become unreachable quickly. This pattern is often called the weak generational hypothesis. Temporary strings, intermediate expression objects, request-scoped records, and short-lived iterator state provide common examples. The observation is workload-dependent, not a universal property of programs.\n\nA generational heap divides objects by age or collection history. New objects usually enter a young generation or nursery. A minor collection concentrates on this area, copying or otherwise preserving its survivors while reclaiming the rest. Objects that survive enough collections, or meet other policy conditions, move into an older generation. Older regions are examined less frequently because repeatedly scanning long-lived data would waste work when most of it remains reachable.\n\nCollecting only young objects requires finding references into the young generation from outside it. An old object can acquire a reference to a new object after the old object’s own collection has finished. If the collector scanned only ordinary roots and young objects, it could miss this reference and reclaim a live object. A write barrier therefore records relevant reference stores. A common implementation uses a card table: a small metadata entry represents a larger memory area, and a reference store marks the corresponding card as needing examination.\n\nThe collector combines normal roots with remembered old-to-young references to establish the young generation’s incoming edges. It need not traverse the complete old generation during each minor collection. The remembered information can be coarse, such as dirty cards, or more precise, such as sets of locations or regions. Greater precision can reduce scanning but usually increases metadata requirements or barrier costs. Promotion and evacuation must also preserve these cross-generation relationships.\n\nRegion-based designs divide the heap into many independently managed areas rather than a few large contiguous generations. They can choose a collection set according to estimated reclaimable space, survival rates, and pause-time goals. A collector may evacuate selected regions and leave others untouched. Region organization and generational organization are compatible: some regions can hold young objects, while others hold older or unusually large objects.\n\nGenerational designs perform less well when most new objects survive, when applications repeatedly modify old-to-young references, or when promotion exceeds the older generation’s reclamation rate. A burst of long-lived allocations can quickly fill the nursery and transfer substantial work into later collections. Adaptive sizing attempts to respond to such changes, but it relies on measurements and predictions. Some collectors therefore use nongenerational designs, and others make generational policy only one component of a broader regional strategy."
    },
    {
      "heading": "Incremental, parallel, and concurrent execution",
      "text": "Collection introduces a scheduling problem as well as a graph problem. A stop-the-world collector halts application execution during some or all collection phases. A parallel collector uses several collector workers at once, often while application threads remain stopped. An incremental collector divides work into smaller portions interleaved with application execution. A concurrent collector performs substantial work while application threads continue running. These properties can coexist and should not be treated as interchangeable.\n\nThe application side of a collecting system is traditionally called the mutator because it changes the object graph. Concurrent tracing is difficult because the mutator can alter references after the collector has inspected an object. Without coordination, an object might become reachable through a path the collector never observes. Correctness therefore depends on barriers, synchronization, and a precisely defined treatment of allocations and reference updates during the collection cycle.\n\nThe tri-color abstraction describes this coordination. White objects have not yet been discovered, gray objects have been discovered but not fully scanned, and black objects have been scanned. In an incremental-update scheme, a barrier can preserve an invariant that prevents a black object from hiding an unrecorded reference to a white object. In a snapshot-at-the-beginning scheme, a deletion barrier records references that are overwritten, helping preserve the logical graph that existed when marking began. These are different strategies, not merely different names for the same barrier.\n\nConcurrent movement is more demanding than concurrent marking. While an object is being relocated, application threads may attempt to access its old address or update its fields. A read barrier or load barrier can detect and redirect references to moved objects. Other designs use forwarding information, controlled evacuation phases, or combinations of read and write barriers. Each choice shifts costs among ordinary object accesses, collection work, metadata, and synchronization.\n\nConcurrency reduces some pauses but does not make collection free. Collector threads compete with application threads for processor time, cache capacity, and memory bandwidth. There may still be brief stop-the-world phases to establish roots, coordinate thread states, complete marking, or perform operations that are difficult to make concurrent. If allocation proceeds faster than reclamation, application threads may have to assist the collector or wait for memory.\n\nReal-time collection adds stronger scheduling requirements. A real-time system may require bounded interference rather than merely good average latency. Meeting such requirements involves the collector, allocator, root-scanning strategy, mutator allocation rate, and available reserve memory. A collector with short typical pauses is not automatically suitable for hard real-time use: worst-case behavior and the assumptions under which bounds hold must also be established."
    },
    {
      "heading": "Runtime integration and memory representation",
      "text": "A collector must determine which values are references. In a precise collector, the runtime knows the pointer-bearing fields of each object and the locations of live references in execution state. Object layouts may be described by type metadata, while compiler-generated stack maps identify references at particular machine-code locations. This requires cooperation among the runtime, the compiler, and the virtual machine or execution environment.\n\nA conservative collector instead treats some machine words as possible pointers when their values resemble addresses into managed memory. This makes collection possible in environments where exact type information is unavailable, including some implementations supporting the C programming language and C++. The disadvantage is false retention: an integer or stale bit pattern can accidentally keep an object alive. An ambiguous reference also cannot generally be rewritten safely, constraining movement of the object it might identify.\n\nPrecise collection often coordinates threads at safepoints, execution locations where reference information and thread state are well defined. A thread may check a poll flag, encounter a protected memory access, or enter a runtime operation that permits collection. The delay before all required threads reach a suitable state can contribute to a pause. Some runtimes use more localized thread coordination or support inspection at a wider set of locations, but the underlying requirement remains a reliable account of references.\n\nAllocation mechanisms are designed together with collection. A bump-pointer allocator advances a pointer through a contiguous free area, making the common allocation path very short. Thread-local allocation buffers let threads allocate independently for a time without taking a global lock on every object. When a local buffer is exhausted, the runtime obtains another buffer or invokes a slower allocation path. Collectors that compact or evacuate memory naturally replenish contiguous areas suitable for this technique.\n\nObject representation influences space and speed. Headers may contain type information, lock state, age bits, or forwarding data; some collectors move part of this information into side tables. Compressed references can reduce pointer storage within a limited addressable heap range. Alignment affects both object size and the metadata bits available in addresses. These choices interact with the memory hierarchy, because the costs of tracing depend heavily on cache misses and memory bandwidth.\n\nForeign-function interfaces create an additional boundary. Native code may hold managed objects through registered handles, temporarily pin them, or explicitly report its roots. A pointer retained outside the collector’s visibility can become invalid if the object moves or is reclaimed. Conversely, excessive pinning can obstruct compaction and increase fragmentation. Coordination with native libraries is therefore a correctness requirement, not simply a performance optimization."
    },
    {
      "heading": "Language behavior, weak references, and external resources",
      "text": "Garbage collection affects language behavior when programs can observe reclamation indirectly. Ordinary strong references keep objects reachable. A weak reference allows a program to refer to an object without necessarily keeping it alive. Once the collector determines that the object is otherwise unreachable, the runtime may clear the weak reference or arrange a notification according to the language’s rules. Weak references are useful for associations that should not determine the lifetime of their targets, but they do not guarantee a particular reclamation time.\n\nWeak-key tables require special care. Suppose a table holds its key weakly but its value strongly, and the value refers back to the key. If the table’s value were traced unconditionally, that path could keep the key alive and defeat the weak-key intention. An ephemeron treats the value as reachable through the association only when the key is independently reachable. Processing interconnected ephemerons can require repeated propagation until no additional objects become reachable.\n\nFinalization permits a runtime to execute code associated with an otherwise unreachable object. It introduces complications beyond ordinary reclamation: finalizers may run late, execute in an unexpected order, access other objects whose state is changing, or make an object reachable again. This last behavior is called resurrection. Languages and runtimes differ in whether they permit it, how often a finalizer may execute, and what guarantees exist during shutdown.\n\nExternal resources demonstrate why garbage collection is not equivalent to general resource management. A tiny managed wrapper may own a large native allocation, an open file, a network connection, or a device resource. Heap pressure does not necessarily reflect the scarcity of that external resource. A collector may therefore have no reason to run at the moment the resource needs to be released, and process termination may occur without all finalization callbacks being executed.\n\nLanguages commonly provide structured cleanup independently of collection. Examples include try/finally, context managers, and disposal constructs. In C++, resource acquisition is initialization associates resource ownership with object lifetime and scope-based destruction; ownership-based systems offer other forms of deterministic release. These mechanisms can coexist with a collected heap, because releasing a resource and reclaiming its wrapper’s memory are separate events.\n\nThe separation matters for API design. An operation that closes a connection must define what happens to later method calls, outstanding callbacks, and other references to the wrapper. Garbage collection can ensure that the wrapper is not reclaimed while still reachable, but it does not automatically define whether the underlying connection remains valid. Resource state, object reachability, and ownership are related but distinct parts of a program’s semantics."
    },
    {
      "heading": "Performance, measurement, and workload behavior",
      "text": "Collector performance cannot be reduced to one number. Throughput measures useful work completed over time, while latency concerns delays experienced by individual operations. Other important quantities include maximum pause duration, pause distribution, allocation rate, live-set size, collection frequency, and total memory footprint. A configuration that improves throughput by using more memory may be unsuitable in a memory-constrained environment.\n\nAllocation rate places a direct demand on reclamation. If an application allocates at rate \\(a\\) bytes per second and a nursery can accept \\(N\\) bytes between collections, a simplified estimate of the collection interval is\n\n\\[T\\approx \\frac{N}{a}.\\]\n\nThis ignores surviving objects, thread-local buffer waste, early triggers, and adaptive resizing, but it captures a basic relationship: doubling allocation rate roughly halves the time available between nursery collections unless capacity or policy changes.\n\nLive data is equally important. A copying collector’s work depends heavily on how much data survives, while a marking collector must inspect reachable objects and their reference fields. For a simplified full-heap copying model, suppose \\(H\\) is usable allocation-space capacity and \\(L\\) is the live data remaining after collection. The ratio\n\n\\[\\frac{L}{H-L}\\]\n\nillustrates how much live data must be copied relative to the space available for subsequent allocation. As \\(L\\) approaches \\(H\\), collection becomes increasingly expensive per byte newly allocated. Real collectors add reserve requirements, regional choices, and other costs, so this is an explanatory model rather than a universal performance formula.\n\nMemory footprint extends beyond currently live objects. It includes unused heap capacity, object headers, alignment gaps, mark bitmaps, remembered sets, evacuation reserves, thread stacks, and native allocations. The amount of address space reserved from the operating system may differ greatly from committed or resident memory. Interaction with virtual memory matters because paging can turn a graph traversal into a large number of expensive memory faults.\n\nPause measurements must distinguish collector work from surrounding delays. Time to bring threads to safepoints, operating-system scheduling, page faults, and competition for processor resources can all influence observed interruption. In a request-serving system, a collection may delay many requests at once, affecting high-percentile latency more strongly than average latency. Benchmark results also depend on warm-up, just-in-time compilation, heap sizing, workload duration, and whether the test reaches a stable allocation pattern.\n\nMemory diagnostics therefore examine both allocation and retention. Allocation profiles reveal where objects are created; heap snapshots show which objects remain and how roots retain them. A leak in a collected language often consists of an unintended reachable path, such as a static map, event listener, cache entry, or unfinished asynchronous task. Repeated collections cannot reclaim that object until the retaining path disappears."
    },
    {
      "heading": "Correctness, safety, and implementation trade-offs",
      "text": "The fundamental safety requirement is that a collector must not reclaim an object that the application can still access through a valid reference. A separate progress goal is to reclaim unreachable objects eventually, subject to the collector’s guarantees. These properties are not identical: a collector that retains too much may be safe but ineffective, while one that reclaims reachable data is incorrect even if it uses little memory.\n\nCollector correctness depends on more than the tracing routine. Object layout descriptions, stack maps, barriers, synchronization, allocation initialization, and reference updates must all agree. A missing barrier can create a rare failure that appears only under a particular interleaving of mutation and collection. A mistaken stack map can cause either false retention or premature reclamation. Formal verification and invariant-based reasoning are consequently useful for examining collector components, especially concurrent algorithms.\n\nAutomatic reclamation reduces exposure to certain memory-safety failures, notably use-after-free and double deallocation within the managed object model. It does not by itself guarantee complete memory safety. Native extensions, unsafe language features, incorrectly implemented runtimes, and unchecked operations can bypass those protections. Bounds checking, type safety, and isolation mechanisms address other aspects of safe execution that garbage collection alone does not cover.\n\nAlternatives and complements make different trade-offs. Explicit allocation and deallocation offer direct control but place lifetime reasoning on the programmer. Region or arena allocation reclaims many objects together, often efficiently, but can retain individual dead objects until the whole region is released. Ownership and borrowing systems restrict how references are created and shared so that many lifetime properties can be checked statically. Reference counting accommodates dynamic shared ownership but adds update costs and requires a policy for cycles.\n\nCollection also interacts with distributed systems, where reachability may span processes. A local object can represent a remote reference, and reclaiming a distributed object may depend on messages, process failures, and delayed communication. Local heap collection cannot by itself establish global unreachability. Distributed reference counting, leases, and tracing protocols introduce assumptions about failure and communication that are absent from a single-process heap.\n\nNo collector simultaneously minimizes memory consumption, processor overhead, pause duration, implementation complexity, and constraints on object representation. A compact embedded runtime, an interactive web browser, a high-throughput server, and a hard real-time controller impose different requirements. Practical designs therefore select particular combinations of precision, movement, generations, barriers, and scheduling, with their behavior determined jointly by the runtime and the application’s allocation and sharing patterns."
    }
  ],
  "links": [
    "programming-language",
    "john-mccarthy",
    "concurrent-computing",
    "halting-problem",
    "compiler",
    "synchronization-computing",
    "cpu-cache",
    "time-complexity",
    "virtual-machine",
    "c-programming-language",
    "memory-hierarchy",
    "application-programming-interface",
    "operating-system",
    "virtual-memory",
    "formal-verification",
    "web-browser"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}