Deep dive
At a high level, GC:
- Finds reachable objects (mark).
- Reclaims memory of unreachable objects (sweep) and may compact to reduce fragmentation.
Generational GC is based on the “generational hypothesis”: most objects die young. So the heap is split:
- Young gen (Eden + survivor spaces): collected often (minor GC) and usually fast.
- Old gen: collected less often (major/mixed collections) and typically more expensive.
Practical view
- Allocation is cheap; GC cost appears as pauses and CPU overhead.
- Modern collectors (G1, ZGC, Shenandoah) trade throughput vs pause-time differently.
Common pitfalls
- Thinking GC frees objects “when they go out of scope” (it’s reachability-based).
- Creating lots of short-lived garbage in hot paths.
- Holding references accidentally (memory leaks via caches, listeners, static maps).