Programming Search⌘K

Conceptcore

Garbage collection

Also called GC, automatic memory management, tracing garbage collection.

Garbage collection frees the memory of objects that the program can no longer reach. The program allocates objects but never frees them, and the runtime finds the dead ones.

Applies to
core-languages

Idea

A program makes objects on the heap all the time: strings, lists, records, closures. Each object uses memory until something frees it. With manual memory management, the programmer frees each object. A free that comes too early gives a dangling pointer, and a free that never comes gives a leak. Garbage collection gives this work to the runtime. The program allocates objects and never frees them. The runtime finds the objects that the program can no longer use and frees their memory.

The runtime cannot know which objects the program will use in the future. It uses a safe approximation: an object that no chain of references reaches from the running program is garbage, because no code can ever touch it again. The two main methods are reference counting and tracing.12 CPython uses both. Reference counting frees most objects at once, and a tracing pass finds groups of objects that refer to each other in a cycle.8 In this run, the automatic cycle pass is off, so the cycle stays in memory until gc.collect() runs.

import gc
import weakref


class Item:
    def __init__(self):
        self.peer = None


gc.disable()  # no automatic cycle collection during this demo

single = Item()
single_probe = weakref.ref(single)
del single
print("single freed at once:", single_probe() is None)

a, b = Item(), Item()
a.peer, b.peer = b, a
cycle_probe = weakref.ref(a)
del a, b
print("cycle freed by del:", cycle_probe() is None)
gc.collect()
print("cycle freed by gc:", cycle_probe() is None)
Output
single freed at once: True
cycle freed by del: False
cycle freed by gc: True

A weak reference (weakref.ref) lets the program look at an object without keeping it alive.11 The probe returns None after the object is freed.

See it run

  1. DROP(x) ▷ reference counting: one reference to x goes away
  2. 1count(x) ← count(x) − 1
  3. 2if count(x) = 0 then
  4. 3for each reference from x to an object y do DROP(y)
  5. 4free x
  6. COLLECT() ▷ tracing: mark from the roots, then sweep
  7. 5colour each object of the heap white
  8. 6for each root r do
  9. 7if r refers to a white object y then colour y grey
  10. 8while some object is grey do
  11. 9take a grey object x
  12. 10for each reference from x to an object y do
  13. 11if y is white then colour y grey
  14. 12colour x black ▷ no black object refers to a white object
  15. 13for each object x of the heap do ▷ the sweep
  16. 14if x is white then free x
  17. 15else colour x white ▷ ready for the next collection
0 / 0
Use your own input

Type the input as JSON, in the same form as a preset.

How it works

The heap is a directed graph. Each object is a node, and each reference from one object to another is an edge. The roots are the references that the program holds directly: local variables in the active stack frames, global variables, and CPU registers. An object is reachable when a path of edges leads to it from a root. A collector frees only unreachable objects. A reachable object can still be useless to the program, and the collector keeps it. So garbage collection removes dangling pointers, but it does not remove all leaks.

roots                       heap

local   order   ---------> Order ---------> Customer
global  cache   ---------> Cache

                           Item a <-------> Item b

Order, Customer and Cache are reachable. Item a and Item b refer to each other, but no path from a root leads to them, so both are garbage.

Reference counting stores in each object the number of references to it. Each copy of a reference adds one, and each removal subtracts one. When the count reaches zero, the object is freed, and the counts of the objects it refers to go down in turn.2 Memory comes back at once and in small steps. In the diagram, Item a and Item b each have a count of 1, from each other, so reference counting alone never frees them.

Tracing starts from the roots and follows every reference. The mark phase marks each object that it reaches. The sweep phase walks the whole heap and frees each unmarked object.1 Cycles are no problem, because only reachability counts. Tracing collectors differ in what they do with the live objects:

Method When memory comes back Frees cycles Moves objects Main cost
Reference counting when the count of an object reaches zero2 no no a count update at each copy of a reference
Mark-sweep at each collection1 yes no the sweep visits the whole heap; free memory becomes fragmented
Copying at each collection; live objects move to an empty space3 yes yes half of the space is empty; the work grows with the live data, not with the garbage
Mark-compact at each collection yes yes extra passes to slide objects together and fix every pointer to them
Generational often for young objects, rarely for old ones56 yes usually a record of the old objects that point to young ones

A generational collector divides the heap by age. Most objects die soon after they are made, so a collection of the young part frees much memory for little work. The collector must also know about references from old objects into the young part. It keeps them in a remembered set, which code that the compiler adds to each pointer store (a write barrier) keeps up to date.618

A concurrent collector marks objects while the program runs, so the program changes the graph during the trace. The usual model colours each object white (not reached yet), grey (reached, but its references not yet scanned) or black (reached and scanned). The collector is correct when no black object points to a white object, because then every white object that is left at the end is garbage. A write barrier keeps this invariant when the program stores a pointer.4

The pseudocode shows a mark-sweep collection with the three colours. DROP is the reference counting update, for comparison. The scene below runs both on small heaps.

  1. DROP(x) ▷ reference counting: one reference to x goes away
  2. 1count(x) ← count(x) − 1
  3. 2if count(x) = 0 then
  4. 3for each reference from x to an object y do DROP(y)
  5. 4free x
  6. COLLECT() ▷ tracing: mark from the roots, then sweep
  7. 5colour each object of the heap white
  8. 6for each root r do
  9. 7if r refers to a white object y then colour y grey
  10. 8while some object is grey do
  11. 9take a grey object x
  12. 10for each reference from x to an object y do
  13. 11if y is white then colour y grey
  14. 12colour x black ▷ no black object refers to a white object
  15. 13for each object x of the heap do ▷ the sweep
  16. 14if x is white then free x
  17. 15else colour x white ▷ ready for the next collection

CPython finds cycles with a variant of tracing that does not need the roots. For each container object in the generation that it collects, it copies the reference count and then subtracts each reference that comes from inside the set. An object with a count above zero after this step has a reference from outside, so it is reachable. Everything that these objects reach is reachable too. The rest is a group of objects that refer only to each other, and the collector frees them.8 A collection of the youngest generation starts when the number of allocations minus deallocations passes the first threshold.7

import gc

print(gc.get_threshold())
Output
(2000, 10, 10)

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaNative
CAbsentThe standard library has malloc and free and no collector. Alternative: Free each object by hand, use an arena, or link the Boehm-Demers-Weiser conservative collector.
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustStandard library
KotlinNative
SQLDoes not applyThe database engine manages storage, and a query has no object references.
BashDoes not applyThe shell manages its own strings and arrays, and a script has no references to objects.
PowerShellNative
HTMLDoes not applyMarkup has no objects; the DOM belongs to the JavaScript engine.
CSSDoes not applyStyle rules have no objects.
Regular expressionsDoes not applyA pattern has no objects.

The example files show the same test in each language with a collector: make two objects that refer to each other, drop the references, ask for a collection, and check through a weak reference that the pair is gone. The Rust and C++ files show that reference counting alone leaks the cycle.

Language Verdict Collector
Python native CPython: reference counting, plus a tracing cycle collector with three generations; the free-threaded build scans the whole heap at each collection8
JavaScript native tracing; the specification defines only which objects the program can still observe, not the algorithm15
TypeScript native the collector of the JavaScript engine that runs the output
Java native HotSpot: G1 (generational, region-based, mostly concurrent, moves objects) on server-class machines and Serial on small ones; JEP 523 makes G1 the default everywhere; ZGC and Parallel are options171822
C# native .NET: generational (0, 1, 2), mark and compact; large objects are swept3132
Go native concurrent mark-sweep that does not move objects26
Kotlin native the JVM collector on Kotlin/JVM; on Kotlin/Native, a concurrent mark and sweep collector without generations39
PowerShell native the .NET collector, as for C#
Rust stdlib no collector; ownership frees each value at the end of its scope; Rc and Arc count references37
C++ stdlib no collector; std::shared_ptr counts owners36
C absent malloc and free by hand
Bash n/a the shell manages its own strings and arrays; a script has no references to objects
SQL n/a the database engine manages storage; a query has no object references
Regex n/a a pattern has no objects
HTML/CSS n/a markup and style have no objects; the DOM belongs to the JavaScript engine

C has no collector in the standard. Programs free memory by hand, use arenas that free many objects at once, or link the Boehm-Demers-Weiser collector. That library is a conservative collector: it treats any word that looks like a heap address as a pointer.40 C++11 added a minimal interface for such collectors (std::declare_reachable and related functions). The authors of the removal paper knew of no implementation of its strict mode, and C++23 removed the interface.35

Rust and C++ free memory at known points instead. A value is dropped (Rust) or destroyed (C++) at the end of the scope of its owner. Shared ownership uses a reference count. A cycle of Rc or shared_ptr values never reaches a count of zero, so it leaks. A weak pointer (rc::Weak, std::weak_ptr) does not add to the count, and it breaks the cycle.3738

PythonGitHub
import gc
import weakref


class Item:
    def __init__(self):
        self.peer = None


def make_cycle():
    a, b = Item(), Item()
    a.peer, b.peer = b, a
    probe = weakref.ref(a)
    print("alive while referenced:", probe() is not None)
    return probe


probe = make_cycle()
print("unreachable objects found:", gc.collect())
print("collected after gc:", probe() is None)
Output
alive while referenced: True
unreachable objects found: 2
collected after gc: True
  • Verdict: native. CPython frees most objects by reference counting, at the moment the last reference goes away. A tracing cycle collector frees groups of objects that refer to each other.
  • gc.collect() runs a full collection at once and returns the number of unreachable objects that it found. Here they are the two Item objects.
  • Only container objects (lists, dicts, instances of most classes) are tracked by the cycle collector. gc.is_tracked tells whether an object is.
  • weakref.ref gives a reference that does not keep the object alive. The free-threaded build uses the same model, but each collection scans the whole heap.
#include <memory>
#include <print>

struct Item {
    std::shared_ptr<Item> strong_peer;
    std::weak_ptr<Item> weak_peer;
};

// Make a pair a -> b -> a and return a weak probe to a.
std::weak_ptr<Item> pair(bool back_link_is_weak) {
    auto a = std::make_shared<Item>();
    auto b = std::make_shared<Item>();
    a->strong_peer = b;
    if (back_link_is_weak) {
        b->weak_peer = a;
    } else {
        b->strong_peer = a;
    }
    return a;
}

int main() {
    std::weak_ptr<Item> leaked = pair(false);
    std::println("strong cycle freed: {}", leaked.expired());
    std::println("weak back link freed: {}", pair(true).expired());
    // Break the cycle by hand, or LeakSanitizer reports it at exit.
    if (auto a = leaked.lock()) {
        a->strong_peer.reset();
    }
    std::println("freed after manual break: {}", leaked.expired());
}
Output
strong cycle freed: false
weak back link freed: true
freed after manual break: true
  • Verdict: stdlib. C++ has no collector. std::shared_ptr counts the owners of an object and destroys it when the last owner goes away.
  • A cycle of shared_ptr values never reaches a count of zero, so it leaks. std::weak_ptr observes an object without owning it, and expired() tells whether the object is gone.
  • C++11 added an interface for garbage collectors, but C++23 removed it.
JavaGitHub
import java.lang.ref.WeakReference;

public class Main {
    static class Item {
        Item peer;
    }

    public static void main(String[] args) {
        Item a = new Item();
        Item b = new Item();
        a.peer = b;
        b.peer = a;
        WeakReference<Item> probe = new WeakReference<>(a);
        System.out.println("alive while referenced: " + (probe.get() != null));
        a = null;
        b = null;
        System.gc();
        System.out.println("collected after gc: " + (probe.get() == null));
    }
}
Output
alive while referenced: true
collected after gc: true
  • Verdict: native. The JVM has a tracing collector. On server-class machines HotSpot selects G1, a generational collector that copies live objects out of the regions that it collects.
  • System.gc() only suggests a collection. In this run HotSpot collected the pair, but the API does not promise that.
  • WeakReference.get() returns null after the collector clears the reference.
  • Use try-with-resources to close files and sockets. Finalization is deprecated for removal.
using System.Runtime.CompilerServices;

WeakReference probe = MakeCycle();
GC.Collect();
Console.WriteLine($"collected after gc: {!probe.IsAlive}");

var item = new Item();
Console.Write($"generation: {GC.GetGeneration(item)}");
GC.Collect();
Console.Write($" {GC.GetGeneration(item)}");
GC.Collect();
Console.WriteLine($" {GC.GetGeneration(item)}");

// NoInlining keeps a and b in a frame that is gone before GC.Collect runs.
[MethodImpl(MethodImplOptions.NoInlining)]
static WeakReference MakeCycle()
{
    var a = new Item();
    var b = new Item { Peer = a };
    a.Peer = b;
    var probe = new WeakReference(a);
    Console.WriteLine($"alive while referenced: {probe.IsAlive}");
    return probe;
}

class Item
{
    public Item? Peer;
}
Output
alive while referenced: True
collected after gc: True
generation: 0 1 2
  • Verdict: native. The .NET collector is generational. A collection marks the live objects and compacts them, and the survivors of a collection move up one generation, from 0 to 1 and from 1 to 2.
  • The last line shows the promotion of one object that stays alive through two calls of GC.Collect().
  • [MethodImpl(MethodImplOptions.NoInlining)] keeps MakeCycle a real call, so its locals a and b are gone before GC.Collect() runs.
  • Release files and sockets with using, not with a finalizer.
JavaScriptGitHub
class Item {
  peer = null;
}

async function main() {
  let a = new Item();
  let b = new Item();
  a.peer = b;
  b.peer = a;
  const probe = new WeakRef(a);
  console.log("alive while referenced:", probe.deref() !== undefined);
  a = b = null;
  // A WeakRef target stays alive until the current job ends.
  await new Promise((resolve) => setTimeout(resolve, 0));
  globalThis.gc();
  console.log("collected after gc:", probe.deref() === undefined);
}

main();
Output
alive while referenced: true
collected after gc: true
  • Verdict: native. Every JavaScript engine has a tracing collector, so a cycle of objects is freed when no root reaches it. The specification does not fix the algorithm.
  • globalThis.gc is not part of the language. Node.js defines it only with the V8 flag --expose-gc, which this run uses.
  • The await on a timer ends the current job. A WeakRef keeps its target alive until the job that created it or read it ends, so a gc() call in the same job cannot free the target.
  • FinalizationRegistry can run a callback after a target is collected, but the specification makes this callback optional.
TypeScriptGitHub
// gc() exists only when the engine runs with --expose-gc.
declare function gc(): void;

class Item {
  peer: Item | null = null;
}

async function main(): Promise<void> {
  let a: Item | null = new Item();
  let b: Item | null = new Item();
  a.peer = b;
  b.peer = a;
  const probe = new WeakRef(a);
  console.log("alive while referenced:", probe.deref() !== undefined);
  a = b = null;
  // A WeakRef target stays alive until the current job ends.
  await new Promise((resolve) => setTimeout(resolve, 0));
  gc();
  console.log("collected after gc:", probe.deref() === undefined);
}

main();
Output
alive while referenced: true
collected after gc: true
  • Verdict: native. TypeScript compiles to JavaScript, so the collector is the one of the JavaScript engine.
  • gc exists only when Node.js starts with --expose-gc. The declare function line tells the type checker about it.
  • WeakRef<Item> is generic: deref() returns Item | undefined.
package main

import (
	"fmt"
	"runtime"
	"weak"
)

type item struct{ peer *item }

func main() {
	a, b := &item{}, &item{}
	a.peer, b.peer = b, a
	probe := weak.Make(a)
	fmt.Println("alive while referenced:", probe.Value() != nil)
	a, b = nil, nil
	runtime.GC()
	fmt.Println("collected after gc:", probe.Value() == nil)
}
Output
alive while referenced: true
collected after gc: true
  • Verdict: native. The Go collector is a concurrent mark-sweep collector. It does not move objects.
  • runtime.GC() runs a full collection and blocks the caller until it ends.
  • weak.Make returns a weak.Pointer. Its Value method returns nil after the object has been collected.
  • GOGC sets how much the heap can grow between collections, and GOMEMLIMIT sets a soft limit on the total memory of the runtime.
RustGitHub
use std::cell::RefCell;
use std::rc::{Rc, Weak};

#[derive(Default)]
struct Item {
    strong_peer: RefCell<Option<Rc<Item>>>,
    weak_peer: RefCell<Weak<Item>>,
}

// Make a pair a -> b -> a and return a weak probe to a.
fn pair(back_link_is_weak: bool) -> Weak<Item> {
    let a = Rc::new(Item::default());
    let b = Rc::new(Item::default());
    *a.strong_peer.borrow_mut() = Some(Rc::clone(&b));
    if back_link_is_weak {
        *b.weak_peer.borrow_mut() = Rc::downgrade(&a);
    } else {
        *b.strong_peer.borrow_mut() = Some(Rc::clone(&a));
    }
    Rc::downgrade(&a)
}

fn main() {
    let leaked = pair(false);
    println!("strong cycle freed: {}", leaked.upgrade().is_none());
    println!("weak back link freed: {}", pair(true).upgrade().is_none());
    // Break the cycle by hand.
    if let Some(a) = leaked.upgrade() {
        a.strong_peer.borrow_mut().take();
    }
    println!("freed after manual break: {}", leaked.upgrade().is_none());
}
Output
strong cycle freed: false
weak back link freed: true
freed after manual break: true
  • Verdict: stdlib. Rust has no collector. Each value has one owner, and the value is dropped when its owner goes out of scope.
  • Rc adds shared ownership with a reference count. A cycle of Rc values keeps every count above zero, so the pair made by pair(false) leaks until the cycle is broken by hand.
  • Rc::downgrade makes a Weak pointer, which does not count as an owner. upgrade returns None once the value is gone.
  • Arc is the thread-safe form of Rc, with atomic counts. It has the same cycle problem.
KotlinGitHub
import java.lang.ref.WeakReference

class Item {
    var peer: Item? = null
}

fun makeCycle(): WeakReference<Item> {
    val a = Item()
    val b = Item()
    a.peer = b
    b.peer = a
    val probe = WeakReference(a)
    println("alive while referenced: ${probe.get() != null}")
    return probe
}

fun main() {
    val probe = makeCycle()
    System.gc()
    println("collected after gc: ${probe.get() == null}")
}
Output
alive while referenced: true
collected after gc: true
  • Verdict: native. Kotlin/JVM uses the collector of the JVM, so the rules of the Java example apply.
  • The cycle is made in a separate function. Its local variables are gone when System.gc() runs, so no stack slot keeps a alive.
  • Kotlin/Native has a collector of its own: a concurrent mark and sweep collector without generations.
PowerShellGitHub
class Item {
    [Item] $Peer
}

function New-Cycle {
    $a = [Item]::new()
    $b = [Item]::new()
    $a.Peer = $b
    $b.Peer = $a
    [WeakReference]::new($a)
}

$probe = New-Cycle
"alive while referenced: $($probe.IsAlive)"
[GC]::Collect()
[GC]::WaitForPendingFinalizers()
"collected after gc: $(-not $probe.IsAlive)"
Output
alive while referenced: True
collected after gc: True
  • Verdict: native. PowerShell runs on .NET, so its objects and script classes are freed by the .NET collector.
  • [GC]::Collect() calls the .NET method directly. [GC]::WaitForPendingFinalizers() waits until the finalizers of the collected objects have run.
  • New-Cycle returns only the weak reference, so no variable of the script keeps $a or $b alive.
  • Conservative collection. The collector does not know which words are pointers, so it treats each word that could be one as a pointer. It can keep some garbage alive, and it cannot move objects. The Boehm collector for C works this way.40
  • Incremental and concurrent collection. The collector does its work in small steps between program steps (incremental), or on other threads while the program runs (concurrent). Both need a barrier to keep the colour invariant.4
  • Regions and evacuation. G1 divides the heap into equal regions. It collects the regions with the most garbage first and copies their live objects into empty regions.18
  • Weak references and finalization. A weak reference does not keep its target alive. Python has weakref, JavaScript has WeakRef and FinalizationRegistry, Java has java.lang.ref, and Go has the weak package.1113142430
  • Ownership. Rust decides at compile time where each value is freed. This needs no collector, but the program must state its ownership structure.
  • Arenas. A program allocates a group of objects in one region and frees the region in one step.
  • Closure keep the variables that they capture reachable, so a closure that stays alive keeps its captured objects alive.

Pitfalls

Reference counting leaks cycles

A reference count never reaches zero for objects in a cycle. Rust and C++ have no collector to find the cycle, so the memory leaks until the process exits (see the Rust and C++ examples). The fix is to make one direction of each cycle weak: a child points to its parent through Weak or std::weak_ptr.3738 CPython has a cycle collector, but code that calls gc.disable() leaves cycles in memory, as in the Idea.

A finalizer does not release a resource on time

A finalizer (__del__ in Python, finalize in Java, a FinalizationRegistry callback in JavaScript) runs when the collector frees the object. The collector decides when that is. In this run, two connections form a cycle, and their __del__ methods run only when the cycle collector runs.

This code runs but gives a wrong answer on purpose.

import gc


class Connection:
    def __init__(self, name):
        self.name = name
        self.peer = None

    def __del__(self):
        print("closed", self.name)


gc.disable()
a = Connection("a")
b = Connection("b")
a.peer, b.peer = b, a
del a, b
print("after del")
gc.collect()
print("after collect")
Output
after del
closed a
closed b
after collect

Python does not guarantee that __del__ runs for objects that still exist when the interpreter exits.10 Java deprecated finalization for removal because finalizers run late, on unknown threads, or not at all.25 The ECMAScript specification makes the cleanup job of a FinalizationRegistry optional.1415 Release a file, a socket or a lock with a scope that ends at a known point: with in Python, try-with-resources in Java, using in C#.1234

from contextlib import closing


class Connection:
    def __init__(self, name):
        self.name = name

    def close(self):
        print("closed", self.name)


with closing(Connection("a")) as conn:
    print("using", conn.name)
print("after with")
Output
using a
closed a
after with

A request for a collection is only a request

System.gc() in Java suggests a collection to the virtual machine.23 GC.Collect() in .NET forces a blocking collection of all generations, so every managed thread waits for it.3331 runtime.GC() in Go runs a collection and blocks the caller until it ends, and it can block the whole program.29 JavaScript has no standard way to start a collection; globalThis.gc exists only when Node.js or V8 starts with --expose-gc. The examples on this page call these functions to show a result. Production code should not depend on them, because each call can cost a full collection.

A JavaScript WeakRef keeps its target alive until the job ends

When a script creates a WeakRef or reads its target, the engine keeps the target alive until the current synchronous run of code ends.16 So a collection in the same job cannot free the target.

This code runs but gives a wrong answer on purpose.

let target = { name: "report" };
const probe = new WeakRef(target);
target = null;
globalThis.gc();
console.log("collected in the same job:", probe.deref() === undefined);
Output
collected in the same job: false

The JavaScript example waits for a timer before it calls gc(), so the job has ended and the target can go.

Reachable is not the same as used

A collector frees only unreachable objects. An object in a global cache, in a list of event handlers, or in the variables of a live closure stays in memory even when the program never reads it again. Remove entries that the program no longer needs, give caches a size limit, or hold the values through weak references, for example in weakref.WeakValueDictionary.11

Cost

  • Memory per object. In the default CPython build, an object of a type that can form cycles carries a header for the cycle collector. A plain object() is 16 bytes and is not tracked. An empty list is 40 bytes plus a 16-byte header, 56 bytes in all. sys.getsizeof includes this header and __sizeof__ does not.741
import gc
import sys

orders = []
print(sys.getsizeof(object()), gc.is_tracked(object()))
print(orders.__sizeof__(), sys.getsizeof(orders), gc.is_tracked(orders))
Output
16 False
40 56 True
  • Heap headroom. A tracing collector lets garbage build up between collections, so the heap is larger than the live data. Go sets the heap target to the live heap plus (live heap + GC roots) × GOGC / 100. With the default GOGC of 100, a program with 10 MiB of live data and few roots gets a target of about 20 MiB. The minimum target is 4 MiB.26 GOMEMLIMIT sets a soft limit on total memory; it has no limit by default.27
  • CPU time. The Go collector uses 25% of the CPU while it marks. When the program is near its memory limit, Go caps the collector at about 50% of the CPU, and lets memory pass the limit instead of spending more.2627
  • Pauses. G1 aims at a maximum pause of 200 ms by default (-XX:MaxGCPauseMillis).18 ZGC was designed for pauses under 10 ms, and it later moved stack scanning out of the pauses to spend less than 1 ms in them.1920 A .NET collection suspends all managed threads except the thread that started it.31 The free-threaded CPython build pauses the other threads during each collection.8
  • Large objects. .NET puts an object of 85,000 bytes or more on the large object heap. That heap is collected only with generation 2, and it is swept, not compacted, unless the program asks for compaction.32
  • Reference counts. Each copy and each drop of a reference changes a count. Rc changes it with plain operations, so it is cheap but cannot go to another thread; Arc uses atomic operations.37 Several threads can copy the same shared_ptr owner group without a data race, so its count also needs atomic updates.36

History

  • 1960. John McCarthy described the first garbage collector, for LISP. When the free-storage list was empty, the system marked every cell reachable from the program and put the other cells back on the list.1
  • 1960. George Collins described reference counts for list cells, so that a cell could be erased when nothing referred to it.2
  • 1970. C. J. Cheney published a copying collector that copies the live cells into a second space and scans them as a queue, with no recursion and no stack.3
  • 1978. Dijkstra, Lamport, Martin, Scholten and Steffens described a collector that runs at the same time as the program, with the white, grey and black marking that concurrent collectors still use.4
  • 1983 and 1984. Lieberman and Hewitt proposed dividing the heap by object age. Ungar's generation scavenging collected only the young objects and kept a remembered set of old objects that point to young ones.56
  • 2018. JDK 11 added ZGC, a concurrent collector with a pause goal of 10 ms.19
  • 2021. P2186R2 removed the garbage collection support of C++11 from C++23.35
  • 2025. JDK 24 removed the non-generational mode of ZGC, so ZGC is always generational.21
  • 2026. Go 1.26 made the Green Tea collector the default. It marks and scans small objects with better locality, and its release notes expect 10 to 40% less collector overhead in programs that use the collector heavily.28 Python 3.14.5 went back to the generational cycle collector of Python 3.13, after the incremental collector of Python 3.14.0 to 3.14.4 used too much memory in some production programs.9

References

  1. John McCarthy, Recursive functions of symbolic expressions and their computation by machine, Part I, Communications of the ACM 3(4), 1960, section 4c, the free-storage list and the reclamation cycle
  2. George E. Collins, A method for overlapping and erasure of lists, Communications of the ACM 3(12), 1960, the reference count of each list cell and erasure when the count reaches zero
  3. C. J. Cheney, A nonrecursive list compacting algorithm, Communications of the ACM 13(11), 1970, the copying algorithm that scans the copied cells as a queue
  4. Edsger W. Dijkstra, Leslie Lamport, A. J. Martin, C. S. Scholten and E. F. M. Steffens, On-the-fly garbage collection, an exercise in cooperation, Communications of the ACM 21(11), 1978, the white, grey and black marking of nodes and the invariant that no black node points to a white node
  5. Henry Lieberman and Carl Hewitt, A real-time garbage collector based on the lifetimes of objects, Communications of the ACM 26(6), 1983, the division of the heap into regions by object age
  6. David Ungar, Generation Scavenging, a non-disruptive high performance storage reclamation algorithm, ACM SIGSOFT/SIGPLAN Software Engineering Symposium on Practical Software Development Environments, 1984, the copying of young objects only, and the remembered set of old objects that point to young ones
  7. The Python Standard Library, gc, Garbage Collector interface, Python 3.15, gc.collect, gc.disable, gc.get_threshold, gc.set_threshold, gc.is_tracked
  8. CPython InternalDocs, Garbage collector design, Identifying reference cycles; Optimization, generations; GC for the free-threaded build
  9. What's New In Python 3.15, Improved modules, gc
  10. The Python Language Reference, Data model, Python 3.14, Basic customization, object.__del__
  11. The Python Standard Library, weakref, Weak references, Python 3.14, the introduction, weakref.ref and WeakValueDictionary
  12. The Python Language Reference, Compound statements, Python 3.14, 8.5 The with statement
  13. ECMA-262, ECMAScript 2026 Language Specification, 26.1 WeakRef Objects
  14. ECMA-262, ECMAScript 2026 Language Specification, 26.2 FinalizationRegistry Objects
  15. ECMA-262, ECMAScript 2026 Language Specification, 9.9.2 Liveness and 9.9.3 Execution
  16. ECMA-262, ECMAScript 2026 Language Specification, 9.10 ClearKeptObjects and 9.11 AddToKeptObjects
  17. Java SE 25 HotSpot Virtual Machine Garbage Collection Tuning Guide, 2 Ergonomics, Garbage Collector, Heap, and Runtime Compiler Default Selection
  18. Java SE 25 HotSpot Virtual Machine Garbage Collection Tuning Guide, 7 Garbage-First (G1) Garbage Collector, Basic Concepts, Remembered Set, and Table 7-1 (MaxGCPauseMillis)
  19. JEP 333: ZGC: A Scalable Low-Latency Garbage Collector (Experimental), Goals
  20. JEP 376: ZGC: Concurrent Thread-Stack Processing, Summary and Goals
  21. JEP 490: ZGC: Remove the Non-Generational Mode, Summary
  22. JEP 523: Make G1 the Default Garbage Collector in All Environments, Summary
  23. Java SE 25 API, java.lang.System, gc()
  24. Java SE 25 API, java.lang.ref.WeakReference, class description
  25. JEP 421: Deprecate Finalization for Removal, Summary and Motivation
  26. A Guide to the Go Garbage Collector, Tracing garbage collection; GOGC; Latency
  27. A Guide to the Go Garbage Collector, Memory limit
  28. Go 1.26 Release Notes, Runtime, New garbage collector
  29. Go standard library, package runtime, func GC, func AddCleanup, func SetFinalizer
  30. Go standard library, package weak, type Pointer, func Make
  31. .NET documentation, Fundamentals of garbage collection, Generations; What happens during a garbage collection
  32. .NET documentation, The large object heap on Windows systems, How an object ends up on the LOH; When is a large object collected
  33. .NET API, GC.Collect Method, Remarks
  34. C# language reference, using keyword, the using statement
  35. P2186R2: Removing Garbage Collection Support, Abstract and Wording
  36. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [util.smartptr.shared], class template shared_ptr
  37. The Rust Standard Library, module std::rc, module documentation, the paragraphs on cycles and Weak
  38. The Rust Standard Library, struct std::rc::Weak, struct description
  39. Kotlin documentation, Kotlin/Native memory management, Garbage collector
  40. A garbage collector for C and C++ (Boehm, Demers, Weiser), the project page
  41. The Python Standard Library, sys, Python 3.15, sys.getsizeof

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV1 static frames
  • V2 needs the oracle check V03, line-trace agreement V06, the counter check V07 and the budgets V08 (10.8.2)
WritingW4 complete
  • a review of the text: no review record reviews/TMWNW7/text.yaml