Garbage Collection

Garbage collection frees memory automatically: objects the program can no longer reach from its variables are found and reclaimed.

An empty heap

rootsheap
user
cart
tmp
list
  • Just allocated
  • Marked: reachable
  • Being freed

Objects live on the heap. The program reaches them through roots — its variables. Anything no root can reach is garbage.

Step 1 / 19
Objects on the heap
0
Freed
0

What's happening?

  1. The program's variables are the roots; objects they point to, and everything those point to, are reachable.
  2. Mark: the collector follows every reference from the roots and marks what it finds.
  3. Sweep: everything left unmarked is garbage and its memory is freed — even objects that point at each other.

Complexity

Time
Proportional to the reachable objects (mark) and the heap (sweep)
Space
A mark bit per object

Where you'll meet it

Java, JavaScript, Python, Go and C# all collect garbage. Tuning it (heap size, G1, ZGC) is a standard part of running Java services.

Common mistake

Thinking a GC language cannot leak. If something stays reachable — a static map, a cache, a listener never removed — it is never collected.

FAQ

Why wasn't the X ⇄ Y cycle a problem?

Mark and sweep only asks "can a root reach it?". Reference counting asks "does anything point at it?" — and cycles always answer yes, so they leak.

What is a stop-the-world pause?

Time when the program is paused so the collector can work safely. Modern collectors (G1, ZGC) do most of their work alongside the program to keep pauses short.

What does generational mean?

Most objects die young, so new objects live in a small young area collected often and cheaply; survivors move to an old area collected rarely.