Java › Garbage Collection
How do the different modern garbage collectors (G1, ZGC, Shenandoah) differ in their approach to minimizing GC pause times, and when would you choose one over the default?
AdvancedAnswer
G1 (Garbage-First, the default collector since Java 9) divides the heap into many small, equally-sized regions and prioritizes collecting the regions with the most garbage first, aiming to meet a configurable target pause time goal (-XX:MaxGCPauseMillis) while still handling both young and old generation collection, suitable for the vast majority of general-purpose applications with heaps up to tens of gigabytes; ZGC and Shenandoah are more specialized, low-latency collectors designed to keep pause times extremely short (typically sub-millisecond to a few milliseconds) even for very large heaps (hundreds of gigabytes or more) by performing the vast majority of GC work concurrently with application threads rather than requiring long application-pausing phases, at the cost of somewhat higher CPU overhead and memory footprint compared to G1 -- ZGC/Shenandoah are typically chosen specifically for latency-sensitive applications (like high-frequency trading or real-time systems) where even G1's already-good pause times aren't sufficient.
# Selecting a garbage collector via JVM flags
java -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -jar app.jar # default, general-purpose, tunable pause target
java -XX:+UseZGC -jar app.jar # ultra-low latency, very large heaps
java -XX:+UseShenandoahGC -jar app.jar # similarly low-latency, different implementation approachReal-world example A high-frequency trading platform switches from the default G1 collector to ZGC after discovering that even G1's typically-good pause times occasionally exceeded their strict sub-millisecond latency budget under specific market-data-burst conditions, accepting ZGC's somewhat higher baseline CPU overhead in exchange for consistently much shorter worst-case pauses.