What are common GC algorithms available in the JVM (Serial, Parallel, G1, ZGC)?
Quick Answer
Serial GC uses a single thread for collection and stop-the-world pauses, suited to small heaps/single-core environments. Parallel GC uses multiple threads for collection to maximize throughput, at the cost of longer individual pauses, and was the historical default. G1 (Garbage-First, default since Java 9) divides the heap into many small regions and prioritizes collecting the regions with the most garbage first, balancing throughput and pause time. ZGC (and Shenandoah) are low-latency collectors targeting sub-millisecond pauses even on very large heaps, trading some throughput/CPU overhead for that latency guarantee.
Detailed Answer
The JVM supports several pluggable garbage collectors, each tuned for a different goal along the classic throughput vs. latency (pause time) trade-off:
-
Serial GC (
-XX:+UseSerialGC): a single thread performs the entire collection, and all application threads pause during it ("stop-the-world"). Simple and low-overhead, appropriate for small heaps or single-CPU environments where multi-threaded collection wouldn't pay off. -
Parallel GC (
-XX:+UseParallelGC): uses multiple threads to perform collection faster, but still stop-the-world for the application during a collection. Optimizes for maximum throughput (total useful work done over time), accepting occasionally longer individual pauses. Was the JVM's default collector for a long time (pre-Java 9). -
G1 (Garbage-First) GC (
-XX:+UseG1GC, default since Java 9): divides the heap into many small, equally-sized regions rather than one contiguous young/old split, and tracks how much garbage each region holds. It prioritizes collecting the regions with the most reclaimable garbage first ("garbage first"), aiming to hit a configurable target pause time (-XX:MaxGCPauseMillis) while still maintaining good throughput — a balanced default for most general-purpose server applications. -
ZGC (
-XX:+UseZGC) and Shenandoah: modern, low-latency collectors designed for sub-millisecond pause times, even on very large heaps (multi-GB to TB scale), by doing almost all collection work concurrently with running application threads rather than stopping them. They trade some CPU overhead/throughput for that strong latency guarantee — ideal for latency-sensitive services where a multi-hundred-millisecond GC pause is unacceptable.
Choosing: G1 is a solid default for most applications; Parallel GC still suits pure batch/throughput-oriented workloads where occasional longer pauses are fine; ZGC/Shenandoah are the right call when consistent low latency matters more than raw throughput, especially on large heaps.