What's happening?
- The program's variables are the roots; objects they point to, and everything those point to, are reachable.
- Mark: the collector follows every reference from the roots and marks what it finds.
- 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.