Skip to main content
PreparationZone Logo
PrepZone

Garbage Collection

Reachability, collectors, reference strengths and a hands-on GC log reading simulator.

Pass checkpoint below

Read these first

Why this matters

  • "Reachable, not referenced" is the distinction that makes reference-counting cycles a non-problem in Java and explains why null-ing a field sometimes does nothing.
  • The choice of collector is one of the few JVM settings that genuinely changes application behaviour, and the defaults have changed across versions.
  • The four reference strengths are the mechanism behind every cache that evicts itself under memory pressure.

Reachability

Allocated in Eden
Still reachable → survivor spaceAge counter increases
Promoted to old generation
ReclaimedMemory returned to the heap
Collection is driven by reachability, not by scope. An object survives exactly as long as some live thread can still reach it through a chain of references.

The collector begins at the GC roots and follows every reference it can.

What counts as a root

  • Local variables and parameters in every frame of every live thread's stack.
  • Static fields of loaded classes.
  • Active threads themselves.
  • JNI references held by native code.
  • Objects used as monitors in a synchronized block.

Anything not reached from a root is garbage, regardless of how many references point at it.

Java
Loading compiler…

The phases

  • Mark — walk from the roots and flag every reachable object.
  • Sweep — reclaim the space held by unmarked objects.
  • Compact — slide survivors together so free space is contiguous, which keeps allocation a pointer bump and prevents fragmentation.

Young collections use copying instead: survivors are moved to the empty survivor space in one pass, which marks, frees and compacts simultaneously. This is why collecting the young generation is so much cheaper than collecting the old one.

Stop-the-world

Some phases require application threads to be paused, because moving an object while a thread is reading it would be unsafe. Threads stop at safepoints — predetermined spots in compiled code where their state is known.

Modern collectors minimise but cannot entirely eliminate these pauses. Concurrent marking happens while the application runs; the short pauses that remain are for starting and finishing the cycle.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 6 sections

  • The collectors
  • The four reference strengths
  • What you can and cannot control
  • Finalisation is gone
  • Read GC logs like a staff engineer
  • Common misreadings

Test yourself

Answer these before moving on — recall is what makes it stick.