TL;DR
A running program creates objects, which are pieces of memory holding data, and links them to each other with references. Once the program has no path left to an object, the object cannot be used again, so its memory is garbage. A garbage collector is part of the language runtime. It finds the objects the program can still reach, and it returns everything else to the allocator.
The programmer never writes a line to free memory. The cost is that the collector must do its work while the program runs, and that cost is what most of this lesson is about.
Where you'll see it: in the runtimes of Java, Go, C#, JavaScript and Python, where almost every object is created and dropped without the programmer tracking its lifetime.
This lesson describes how programs manage memory. It is not advice for any particular system.
Intuition
A house with rooms nobody can enter
Picture a building. Each room is an object. A door from one room to another is a reference. Some rooms are "in use" because the people who live there hold a key that lets them in: the variables the program is actively holding are the keys. A room that no key opens, and that no room with a key can reach through a chain of doors, is empty and forgotten. Nobody can ever go in again.
A garbage collector is a caretaker who walks through the building from the keys outward, marks every room reached, and then clears the unmarked ones. Clearing a room means giving its space back to the building.
The important detail is that reachability is decided by the chain of references, not by the programmer's intent. A program that forgets it still has a reference keeps the object alive, and this is one of the main ways memory use grows in practice.
The math
Objects as a graph
The heap is the region of memory where a program's objects live. The call stack is the separate region holding the variables of the functions currently running. Let the heap be a directed graph, as defined in Graph. Each vertex is an object. Each directed edge means object holds a reference to object . A set of special vertices, called the roots, are the objects held directly by the running program: variables on the call stack, global variables, and registers.
An object is reachable if there is a directed path in the heap graph starting from some root . Reachable objects are live. All other objects are garbage.
Here is a root and is the object we are testing. A path is a chain of references, each one pointing to the next object. Reachability is the one question a collector must answer correctly. If it wrongly frees a reachable object, the program crashes or silently corrupts data. If it wrongly keeps a garbage object, memory is wasted.
Mark and sweep
The simplest correct method is mark and sweep. It works in two phases.
- Mark phase. For every root, mark the object it points to and push it onto a stack.
- While the stack is not empty, pop an object, and for each object it references that is not yet marked, mark it and push it.
- Sweep phase. Walk through every object in the heap. If it is unmarked, return its memory to the free list. If it is marked, clear the mark so the next collection starts fresh.
The mark phase is a graph search from the roots, so it visits each live object once. Its cost grows with the number of live objects and the references among them. The sweep phase walks the whole heap, so its cost grows with the heap size, live or not. A collector can therefore be expensive even when most of the heap is garbage, because sweeping touches it all.
flowchart LR R1[Root: variable a] --> A[Object A] R2[Root: variable b] --> B[Object B] A --> C[Object C] B --> C D[Object D] --> E[Object E] E --> D F[Object F]
In this heap, , and are live. and point to each other, and has no incoming edge. Both groups are garbage, because no root can reach them. The cycle is a case that simple counting cannot handle, as the next sections show.
Cost in terms of steps
Let be the number of live objects and the total number of objects in the heap. Mark does roughly visits plus one visit per reference. Sweep does visits. The total per collection is roughly plus the references, so a collector that runs often on a large, mostly-live heap pays for both.
Worked examples
Example 1: a tiny heap by hand
Take the diagram above with roots and . Work through one collection.
- Mark (reached from root ). Push .
- Pop . It references . Mark . Push .
- Pop . It references nothing, and the stack is empty.
- Mark (reached from root ). Push .
- Pop . It references , which is already marked, so skip it.
- Sweep: , , are marked, so keep them and clear their marks. , , are unmarked, so free them.
- Count: 3 live objects, 6 objects in the heap. The mark phase visited 3 objects and followed 2 references that led to new objects. The sweep visited 6 objects.
Interpretation: the cycle was freed even though each object is referenced by the other. Reachability from the roots is what counts, not whether a reference exists.
Example 2: why reference counting leaks cycles
Reference counting is the main alternative. Each object stores how many references point to it, and it is freed when that count drops to zero. Take two objects that refer to each other, and . Start with a root pointing to , and pointing to , and pointing back to .
- Initially, has count 2: one from the root and one from . has count 1, from .
- The program drops the root. now has count 1, from .
- Nothing outside the pair can reach or , so both are garbage.
- Their counts never reach zero. waits for to release it, and waits for .
- A pure counting scheme therefore leaks both objects for the rest of the run.
- A tracing collector, such as mark and sweep, finds that no root reaches or , and frees both.
Interpretation: counting is cheap and frees memory immediately when a count drops to zero, but it cannot see cycles. Many runtimes that count references add a tracing pass to catch cycles.
Example 3: a realistic service heap
A web service keeps a cache of 200,000 recent responses. Each response is an object, and the heap holds 1,000,000 objects in total, of which 200,000 are live in the cache and 800,000 are request-time garbage. These numbers are illustrative, chosen to show the arithmetic, and are not measurements of any system.
- Mark: visit the 200,000 live objects. If each one holds about 3 references, that is about 600,000 reference checks.
- Sweep: visit all 1,000,000 objects in the heap, freeing the 800,000 garbage ones.
- Total visits: about steps.
- If the heap grows to 4,000,000 objects with the same 200,000 live, the mark work stays the same and the sweep work quadruples.
- Shrinking the garbage a collector must sweep, by freeing short-lived objects early, reduces the sweep cost without changing the live set.
Interpretation: the cost of a collection depends on both the live data and the heap size, so the design aim is often to make most collections touch only short-lived objects. That observation leads to generational collectors, covered in the history section.
Tradeoffs and failure modes
Garbage collection trades programmer effort for runtime cost, and the trade is not free.
| Situation | What goes wrong | Better choice |
|---|---|---|
| A latency-sensitive loop | A collection pauses the program for a time nobody controls | Use incremental or concurrent collectors, or allocate less |
| Many short-lived objects | Frequent collections of the young heap waste work on survivors | Generational collection, which collects new objects often and old ones rarely |
| Large heaps with mostly live data | Each full collection pays to mark everything live | Region-based or concurrent marking |
| Native resources such as file handles | Memory is reclaimed but the handle stays open until a collection runs | Explicit close or scoped resource blocks |
| Cycles in a counting scheme | Counts never reach zero, so memory leaks | Add a tracing pass to find cycles |
Common failure: a program keeps a reference it no longer needs, for example in a global list or a cache with no eviction. The collector behaves correctly and the memory still grows, because every object in that list is reachable. Garbage collection frees what is unreachable, not what is unused.
History
The idea appeared with John McCarthy's Lisp in 1960, which needed to reclaim the lists it built and had no programmer-visible way to free them. Reference counting was explored in the same early period, and it was used in languages where simplicity mattered more than cycles. Mark and sweep, the tracing approach used here, came from the same work on Lisp.
Later progress came from observations about how programs behave. In the 1980s David Ungar proposed the generational hypothesis: most objects die young, and those that survive a while tend to live a long time. Generational collectors use that fact to collect the young heap often and cheaply, and the old heap rarely. Most modern runtimes use a version of this idea, and it is a main reason garbage collection is practical for interactive programs.
Recap
A garbage collector treats the heap as a graph and asks which objects are reachable from the roots. Mark and sweep answers that by searching from the roots and then freeing the rest. The cost grows with the live data and the heap size, so runtimes try to collect young objects often and avoid sweeping the whole heap. Reference counting is an alternative that frees memory sooner, but it needs help to handle cycles. The graph and reachability ideas here come from Graph and the way programs use Virtual Memory.
Check yourself
QuestionWhat decides whether an object is garbage: whether the program still has a reference to it, or whether the program can still reach it from a root?Show answer
Reachability from a root decides it. An object is live when a chain of references leads to it from a root, such as a variable on the stack or a global. An object can be reachable through several paths, and the collector only needs one. An object that is not reachable is garbage even if other garbage objects still refer to it.
QuestionA heap has 500 objects, of which 120 are live. Using the step count from the math section, roughly how many objects does the sweep phase visit, and how many does the mark phase visit?Show answer
Sweep visits every object in the heap, so about 500. Mark visits the live objects, so about 120, plus one check per reference between them. The sweep cost is set by the heap size, and the mark cost is set by the live set.
QuestionWhy does plain reference counting leak two objects that refer only to each other?Show answer
Each object keeps a count from the other, so neither count can fall to zero. The pair is unreachable from the program, but each count still refers to the other. Counting only sees direct references, not whether a chain of them leads back to a root. Tracing from the roots does not have this problem.
QuestionA service has a cache that grows without limit, holding every response it has ever served. Why does a garbage collector not stop the memory from growing, and what would fix it?Show answer
Every cached response is still reachable through the cache, so the collector must keep it. Garbage collection frees only unreachable objects, so the growth is correct from the runtime's point of view. The fix is to change the program so the cache evicts entries (see Cache Eviction Policy), which removes the references and lets the collector reclaim them.