Garbage collection

Also known as: GC

On this page 7

Garbage collection (GC) is a form of automatic memory management in which the language runtime identifies heap objects that a program can no longer reach and reclaims the memory they occupy. In programming, it removes the need to free memory by hand, which eliminates whole classes of defects such as dangling pointers and double frees, at the cost of extra CPU work, extra memory headroom and occasional pauses.

Garbage collection is built into Java, C#, Go, JavaScript, Python, Ruby and most other modern languages, while C and C++ leave memory management to the programmer and Rust replaces it with compile-time ownership rules. Not to be confused with garbage collection inside solid-state drives, which reorganizes flash blocks rather than program memory.

How a garbage collector decides what is garbage

A collector treats an object as live when it is reachable from a root, and everything else is garbage. Roots are references the program can use directly: local variables on thread stacks, CPU registers, global and static variables, and handles held by native code. Any object reachable by following references from a root is live, no matter how long ago it was last used.

This rule means that reachability approximates liveness. An object that the program will never touch again but that is still referenced, for example from a forgotten cache entry, stays in memory. That is why languages with garbage collection can still suffer logical memory leaks, even though they never suffer the classic leak of an unreferenced block that nobody frees.

Collectors use two broad families of techniques to find garbage. Tracing collectors start from the roots and mark everything reachable, then reclaim the rest. Reference counting keeps a counter in each object and frees it the moment the counter drops to zero. Many production runtimes combine them: CPython uses reference counting plus a cycle detector, because two objects that point at each other never reach a count of zero on their own.

Main garbage collection algorithms

Each algorithm makes a different trade-off between pause time, throughput and memory overhead. The table below summarizes the classic designs that modern collectors are built from.

AlgorithmHow it worksMain strengthMain weakness
Mark and sweepMarks reachable objects, then frees unmarked ones in placeSimple, no object movementHeap fragmentation over time
Mark and compactMarks live objects, then slides them togetherNo fragmentation, fast allocationMoving objects costs time
CopyingCopies live objects into an empty spaceCost depends only on live dataNeeds up to twice the memory
Reference countingFrees an object when its count reaches zeroImmediate, predictable reclamationMisses cycles, counter overhead
GenerationalCollects young objects often, old ones rarelyCheap collections of short-lived dataNeeds write barriers between generations
Classic garbage collection algorithms compared

Generational collection rests on the weak generational hypothesis: most objects die young. Temporary strings, iterators and request objects typically become garbage within milliseconds, so a small young generation can be collected frequently and cheaply, while long-lived objects are promoted to an old generation that is scanned far less often.

Modern collectors also run much of their work concurrently with the application. They rely on read barriers or write barriers, small pieces of code the compiler inserts around reference operations, so the collector stays consistent while the program keeps changing the object graph.

Pauses, throughput and memory overhead

The cost of garbage collection is measured along three axes that cannot all be minimized at once. Reducing pauses usually costs throughput, and improving both usually costs memory. Tuning a collector means choosing which of the three matters most for a given workload.

MetricWhat it measuresTypical targetWhat influences it
Pause timeHow long application threads are stoppedUnder 10 ms for interactive servicesConcurrency, heap size, root set size
ThroughputShare of CPU time spent outside the collectorAbove 95 percent for batch workAllocation rate, collection frequency
FootprintExtra memory needed beyond live dataOften 1.5 to 3 times the live setAlgorithm, headroom, fragmentation
Allocation rateBytes allocated per secondWorkload dependentCode style, object churn
Key garbage collection performance metrics

A stop-the-world pause halts every application thread so the collector can work on a frozen heap. Older collectors paused for hundreds of milliseconds on large heaps. Current low-latency designs such as ZGC and Shenandoah in the Java ecosystem, and the concurrent collector in Go, keep typical pauses in the sub-millisecond to few-millisecond range by moving almost all marking and relocation work into concurrent phases.

Memory headroom is the hidden price. A tracing collector runs efficiently only when the heap has substantial free space; as the heap approaches full, collections become more frequent and throughput collapses. Giving a service too little heap is one of the most common causes of poor garbage collection behavior.

Garbage collection compared with other memory strategies

Garbage collection is one of several ways to manage the lifetime of data, and each approach places the burden in a different place: on the runtime, on the compiler or on the programmer.

StrategyExample languagesSafetyRuntime cost
Manual managementC, C++ with raw pointersLow, errors cause crashes and exploitsMinimal, but bugs are expensive
Tracing garbage collectionJava, C#, Go, JavaScriptHigh for memory safetyCPU, memory headroom, pauses
Reference countingSwift, CPython, C++ shared pointersHigh, except for cyclesCounter updates on every copy
Ownership and borrowingRustHigh, checked at compile timeNear zero at run time
Region or arena allocationGame engines, compilersModerate, depends on disciplineVery low, bulk release
Memory management strategies across languages

Garbage collection manages memory only. Files, sockets, database connections and locks are resources that need deterministic release, so languages with a collector add constructs such as try-with-resources in Java, using in C#, with in Python and defer in Go. Relying on finalizers for these resources is a well-known mistake, because the collector gives no guarantee about when, or whether, a finalizer runs.

Common garbage collection problems and fixes

Most garbage collection trouble in practice comes from how the program allocates and retains objects, not from the collector itself. The following symptoms appear repeatedly in production systems.

SymptomLikely causeTypical fix
Heap grows steadily until failureObjects kept in static maps or cachesBound caches, use weak references
Frequent long pausesHeap too small or wrong collectorIncrease headroom, choose a low-latency collector
High CPU in the collectorExcessive short-lived allocationReuse buffers, avoid boxing in hot loops
Latency spikes after deploymentLarge objects promoted prematurelyTune generation sizes, stream large data
Typical symptoms, causes and remedies
  • Calling the collector manually, for example System.gc(), rarely helps and often triggers an unnecessary full collection.
  • Event listeners and callbacks that are registered but never removed are a frequent source of retained objects.
  • Measure before tuning: collector logs and heap profilers show allocation rate and pause distribution far more reliably than intuition.

In simple terms

A running program constantly creates small pieces of data and then stops needing them. Someone has to clear them away, or the computer slowly runs out of memory. With garbage collection, the programming language does this cleaning automatically.

Think of a large office where employees leave papers on desks. A cleaner walks through and keeps any paper that is still connected to an active project, and throws away everything else. The programmer never has to remember to throw anything away, which prevents many serious errors. The trade-off is that the cleaner needs time and some spare room to work, and occasionally everyone has to pause briefly while the cleaning happens.

A practical example

A team runs an online payment API in Java that handles about 4,000 requests per second. After a traffic increase, the 99th-percentile response time jumps from 40 ms to 600 ms several times per hour. The collector logs show full collections lasting about half a second, triggered because the 4 GB heap is nearly full of live data.

A heap profile reveals that a session cache has no size limit and keeps every customer session for 24 hours. The team bounds the cache to 200,000 entries with expiry after 30 minutes, raises the heap to 8 GB and switches to a concurrent low-latency collector. Pauses drop to under 2 ms, the latency spikes disappear and CPU time spent in garbage collection falls from 12 percent to about 3 percent.