GC algorithms
A GC algorithm is a strategy for finding live objects and reclaiming the rest. HotSpot ships several: Serial, Parallel, G1, ZGC, Shenandoah. They trade pause time, throughput, and memory overhead.
Detailed Explanation
All collectors answer the same question: what is reachable? They differ in how they walk, copy, and compact, and whether application threads run at the same time.
Serial uses one GC thread. Fine for small heaps and client tools. Parallel (throughput) uses many GC threads and pauses the application for the whole collection. Good for batch jobs that care about time-to-finish, not tail latency.
G1 (Garbage First, default since JDK 9) splits the heap into regions, collects young regions, and incrementally evacuates old regions with the most garbage. You give it a pause goal (MaxGCPauseMillis). It needs extra remembered-set memory. It is the right default for most services.
ZGC and Shenandoah aim at millisecond or sub-millisecond pauses on large heaps by doing almost all work concurrently, including compaction. They use more coloured pointers or barriers and more CPU. Generational ZGC (recent JDKs) adds the young/old split. Use them when pause SLAs dominate and you can spend cores.
CMS is removed. Do not copy CMS flags. Epsilon is a no-op collector for experiments. The interpreter and JIT are independent of which collector you pick; only pauses and layout change.
You reach for a different collector when G1 pauses miss the goal on a very large heap, or when a batch job should maximize throughput. You change flags one at a time and keep GC logs. You do not mix random -XX:+Use* flags from different collectors.
The cost of ZGC is CPU and a slightly larger heap for the same live set. The cost of Parallel is multi-hundred-millisecond pauses on big heaps. The cost of Serial on a 32G heap is a long freeze. Start with G1 defaults. Measure p99 pause and allocation stall, not a single jstat snapshot.
Code Examples
public class WhichGc {
public static void main(String[] args) {
// The collector name is a JVM flag, not an API. We can only print the VM.
System.out.println(System.getProperty("java.vm.name"));
System.out.println(Runtime.getRuntime().maxMemory());
}
}public class PauseHint {
public static void main(String[] args) {
// Do not call this in a service. It may trigger a full collection.
// Shown only so you know the API exists.
boolean ignored = false;
if (ignored) {
System.gc();
}
System.out.println("ok"); // prints: ok
}
}Common Gotchas
CMS flags do nothing useful on modern JDKs
the collector is gone.
G1 is the default
switch collector for a measured reason, not a blog title.
Low-pause collectors spend more CPU
you trade cores for latency.