What is garbage collection in Java?
Garbage collection (GC) in Java is the automatic process of identifying objects on the heap that are no longer reachable from any GC root (active threads, static fields, local variables on stack) and reclaiming their memory. The developer is freed from manual memory management, eliminating use-after-free and double-free bugs common in C/C++.
The JVM heap is divided generationally based on the observation that most objects die young (the weak generational hypothesis). The Young Generation holds newly created objects and is collected frequently in Minor GC events, which are fast. Objects that survive enough Minor GCs are promoted to the Old Generation (Tenured), collected less frequently in Major GC or Full GC events. Some collectors also use a Metaspace (formerly PermGen) for class metadata.
GC algorithms in modern JVMs include Serial GC (single-threaded, for small heaps), Parallel GC (throughput-focused, multi-threaded), CMS (Concurrent Mark Sweep — low pause but deprecated in Java 9, removed in 14), G1GC (Garbage First — default since Java 9, balances throughput and latency), ZGC (scalable, near-zero pause times, production-ready since Java 15), and Shenandoah (Red Hat, low-latency concurrent GC).
The GC process generally involves: mark (traverse from GC roots, mark live objects), sweep (reclaim unmarked objects), and optionally compact (slide live objects together to eliminate fragmentation). Compacting collectors avoid fragmentation but require a Stop-the-World pause while references are updated.
GC tuning involves choosing the right collector for your workload, sizing the heap and generation spaces (-Xms, -Xmx, -XX:NewRatio), and monitoring GC logs for pause frequency and duration. For latency-sensitive applications, ZGC or Shenandoah are preferred because they do most work concurrently with the application.
Explains reachability-based collection, generational heap structure (Young/Old), and names at least two modern GC algorithms.
Adds the weak generational hypothesis rationale, mark-sweep-compact phases, GC roots definition, and distinguishes throughput vs. latency tradeoffs in collector selection (G1 vs. ZGC).
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment