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.
3 points to say:
- Garbage = not reachable from GC roots, even when objects reference each other in a cycle.
- Young is collected often and cheaply because most objects die young; old rarely; a full GC signals trouble.
- Soft: freed when memory runs low; weak: at the next GC; phantom: resource cleanup;
ThreadLocalin a pool still leaks despite weak keys, so callremove().
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.