SteelReed

Search

Search posts, questions…

JVMQuestion 3 / 12

Middle

How does the GC decide what is garbage? Why is the heap split into young/old, and how do reference types differ?

Short answer

Java doesn't count references; it uses reachability: starting from GC roots, it marks every reachable object, and the rest is garbage. The heap is split into young/old because most objects die young; besides strong there are soft, weak, phantom references.

points toreference cycleGC rootslocal vars, staticsA: aliveB: aliveC: garbageD: garbage

3 points to say:

  1. Garbage = not reachable from GC roots, even when objects reference each other in a cycle.
  2. Young is collected often and cheaply because most objects die young; old rarely; a full GC signals trouble.
  3. Soft: freed when memory runs low; weak: at the next GC; phantom: resource cleanup; ThreadLocal in a pool still leaks despite weak keys, so call remove().

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.