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.
| Algorithm | How it works | Main strength | Main weakness |
|---|---|---|---|
| Mark and sweep | Marks reachable objects, then frees unmarked ones in place | Simple, no object movement | Heap fragmentation over time |
| Mark and compact | Marks live objects, then slides them together | No fragmentation, fast allocation | Moving objects costs time |
| Copying | Copies live objects into an empty space | Cost depends only on live data | Needs up to twice the memory |
| Reference counting | Frees an object when its count reaches zero | Immediate, predictable reclamation | Misses cycles, counter overhead |
| Generational | Collects young objects often, old ones rarely | Cheap collections of short-lived data | Needs write barriers between generations |
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.
| Metric | What it measures | Typical target | What influences it |
|---|---|---|---|
| Pause time | How long application threads are stopped | Under 10 ms for interactive services | Concurrency, heap size, root set size |
| Throughput | Share of CPU time spent outside the collector | Above 95 percent for batch work | Allocation rate, collection frequency |
| Footprint | Extra memory needed beyond live data | Often 1.5 to 3 times the live set | Algorithm, headroom, fragmentation |
| Allocation rate | Bytes allocated per second | Workload dependent | Code style, object churn |
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.
| Strategy | Example languages | Safety | Runtime cost |
|---|---|---|---|
| Manual management | C, C++ with raw pointers | Low, errors cause crashes and exploits | Minimal, but bugs are expensive |
| Tracing garbage collection | Java, C#, Go, JavaScript | High for memory safety | CPU, memory headroom, pauses |
| Reference counting | Swift, CPython, C++ shared pointers | High, except for cycles | Counter updates on every copy |
| Ownership and borrowing | Rust | High, checked at compile time | Near zero at run time |
| Region or arena allocation | Game engines, compilers | Moderate, depends on discipline | Very low, bulk release |
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.
| Symptom | Likely cause | Typical fix |
|---|---|---|
| Heap grows steadily until failure | Objects kept in static maps or caches | Bound caches, use weak references |
| Frequent long pauses | Heap too small or wrong collector | Increase headroom, choose a low-latency collector |
| High CPU in the collector | Excessive short-lived allocation | Reuse buffers, avoid boxing in hot loops |
| Latency spikes after deployment | Large objects promoted prematurely | Tune generation sizes, stream large data |
- 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.