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

Step by step

The example above, written out — the same steps the animation plays.

  1. 1An empty heap. Objects live on the heap. The program reaches them through roots — its variables. Anything no root can reach is garbage.
  2. 2user = new User(). A User and its Session; the variable `user` points at the User.
  3. 3cart = new Cart(a, b). A Cart holding two items.
  4. 4tmp = "temp text". A temporary string for a moment.
  5. 5tmp = null. Nothing points at the string any more. It is garbage — but nothing frees it yet.
  6. 6list = X ⇄ Y. Two nodes that point at each other.
  7. 7list = null. X and Y still point at each other, so each has one reference — but no root reaches them.
  8. 8cart.remove(itemB). Item B leaves the cart.
  9. 9Memory is low: collect. The collector pauses the program and starts from the roots.
  10. 10Mark User. Reachable from the variable `user`.
  11. 11Mark Session. Reachable from User.
  12. 12Mark Cart. Reachable from the variable `cart`.
  13. 13Mark Item A. Reachable from Cart.
  14. 14Marking done. 4 objects are reachable. The other 4 are not.

…and 5 more steps — press Play above to watch them all.

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.