What Is Garbage Collection? Automatic Memory Cleanup
Garbage collection (GC) is automatic memory management: the runtime tracks which objects are still reachable and frees the memory of those that are not.
In languages with garbage collection, you allocate memory by creating objects but rarely free it explicitly. A background mechanism, the garbage collector, periodically finds objects no program path can reach anymore and reclaims their memory. This removes a whole category of manual-memory bugs at the cost of some runtime overhead and occasional pauses.
How GC decides what to free
A collector starts from "roots" (global variables, the stack, active references) and traces every object reachable from them. Anything not reached is garbage and can be freed. This reachability model is why a forgotten reference can keep memory alive longer than you expect.
Common collection strategies
- Mark-and-sweep: mark reachable objects, then sweep away the rest.
- Generational: collect short-lived young objects often, old ones rarely.
- Reference counting: free an object when its reference count hits zero.
- Compacting: move live objects together to reduce fragmentation.
What GC costs you
Garbage collection trades manual control for safety. The price is CPU spent tracing the heap and, in some collectors, pauses where the program briefly stops so the GC can work. Modern collectors minimize these pauses, but they never fully disappear.
GC does not prevent all leaks
A garbage collector frees only unreachable memory. If your code keeps a reference alive (in a cache, a list, an event listener), the object is still reachable and never collected. That is a memory leak even in a garbage-collected language.
A quick example
In a JavaScript or Java program, once no variable points to an object, the collector is free to reclaim it on its next cycle, with no free() call from you. You simply stop referencing the object.
GC in CI
Test runs and builds can pressure the heap, and GC overhead grows as memory fills. When a process exceeds available memory, the runner can OOM-kill it mid-test. Larger runners (Latchkey) give the collector more room, and transient OOM kills can be auto-retried so a memory spike does not fail an otherwise good build.
Key takeaways
- Garbage collection automatically frees memory for objects the program can no longer reach.
- It removes manual-free bugs but costs CPU and can cause occasional pauses.
- GC does not stop leaks: a still-reachable reference keeps memory alive forever.