Medium java java-21

How does garbage collection work in the JVM?

The 30 second answer

The garbage collector finds objects that can no longer be reached from roots, like thread stacks and static fields, and frees their memory. Most HotSpot collectors are generational, because most objects die young: the young area is collected often and cheaply, and objects that survive long enough move to the old area. Collectors trade throughput, pause time and memory. G1 is the default on most server machines.

Reachability: GC roots include local variables in active stack frames, static fields, JNI references and live threads. Anything not reachable from a root is garbage, so circular references alone don't leak.

Generations: new objects are allocated in the young generation (eden). A young collection copies live objects to a survivor space; objects that survive several collections are promoted to the old generation. Old-generation collection is rarer and more expensive.

HotSpot collectors in Java 21:

CollectorGoal
Serialsmall heaps, single CPU
Parallelmaximum throughput, longer pauses
G1 (default)balance throughput and a pause-time target
ZGCvery low pauses, mostly concurrent
Shenandoah (in many OpenJDK builds)low pauses, concurrent compaction

G1 became the default on server-class machines in Java 9 (JEP 248); on machines the JVM considers small it picks Serial.

Sources: GC Tuning Guide: Garbage Collector Implementation, GC Tuning Guide: Available Collectors, JEP 248: Make G1 the Default Garbage Collector

Sources (0)
See inline citations in the answer above.