Skip to main content
CSArchitecture & RuntimeDiagramIntermediate

Garbage Collection

KO: 가비지 컬렉션 (GC)·EN: Garbage Collection·JA: ガベージコレクション(GC)·GC

Automatic memory management where the runtime traces reachability from root references to reclaim unreachable heap objects safely

Table of Contents

Structure Diagram

Garbage Collection Mark-Sweep-Compact Cycle
GC CYCLE1. Heap Allo…2. Mark Reac…3. Sweep / E…4. Compact H…
2/42. Mark Reachable
Trace from GC Roots
Quick Answer

What is Garbage Collection?

Automatic memory management where the runtime traces reachability from root references to reclaim unreachable heap objects safely. It is a core concept in Architecture & Runtime within CS.

Core Principles

Garbage Collection (GC) automatically reclaims heap memory occupied by objects that are no longer reachable from GC Roots (active stack frames, registers, globals), eliminating manual free() bugs like double-free and use-after-free.

  • Key Techniques:
    • Mark-and-Sweep / Copying: Trace live references from roots and reclaim unmarked objects.
    • Generational GC: Exploits the fact that most objects die young—collecting the Young Generation frequently and cheaply while promoting survivors to Old Gen.
    • Concurrent Low-Pause GC: Modern collectors (ZGC, Shenandoah, Go's tri-color GC) run concurrently to keep Stop-the-World (STW) pauses under a millisecond.

Practical Takeaways

  • GC does not prevent logical memory leaks: Forgotten references in global maps, caches, or event listeners remain reachable forever.
  • Reduce allocation rate on hot paths: High churn triggers frequent GC cycles and P99 latency spikes; reuse buffers (sync.Pool, ring buffers) where it counts.
  • Match GC to workload: Throughput-focused batch jobs favor Parallel GC; latency-sensitive APIs favor G1, ZGC, or Go's concurrent GC.

Notable Examples

  • JVM (G1, ZGC), V8 (Orinoco), Go Runtime, and .NET CLR.
  • Reference Counting Hybrids: CPython combines refcounting with a cyclic GC; Swift uses ARC with weak/unowned references.