The JVM’s Garbage Collector Menu: G1, ZGC, and Why Collector Choice Beats Flag Tweaking

The JVM ships with five garbage collectors, and most teams run whichever one their base image defaulted to. That is usually G1, it is usually fine, and the conversation ends there. Then a service with a 30 GB heap starts throwing 8-second pauses every few hours, someone reaches for a bag of -XX flags, and the tuning gets worse before it gets better.

The useful insight is that collector choice is an architectural decision, while flag tuning is a local optimization on top of it. Switching from Parallel GC to ZGC changes what the collector promises; adjusting -XX:MaxGCPauseMillis only changes how hard G1 tries to hit a target it may be structurally unable to meet. This post walks through each collector the JVM ships today, what trade-off each one makes, and how to tell which one your workload actually needs.

What every collector shares

All five collectors — Serial, Parallel, G1, ZGC, and Shenandoah — are tracing collectors. They start from GC roots (thread stacks, static fields, JNI handles), follow references to mark every reachable object, and reclaim the rest. None of them use reference counting, so cycles are a non-issue, and none of them run “whenever memory gets full” in the naive sense: they are triggered by allocation pressure against heuristics that model your pause and throughput goals.

They differ in two questions. First, how much work runs while your application threads keep executing versus while they are paused at a safepoint. Second, whether the collector compacts — moves live objects together to eliminate fragmentation — and if so, where that move happens. Compaction is what makes allocation a pointer bump instead of a free-list search, and it is also the most expensive and disruptive part of any collector. Every design choice below falls out of those two axes.

Serial and Parallel: full-heap, stop-the-world, compacting

Serial GC (-XX:+UseSerialGC) runs the entire collection on one thread while the application is fully stopped. Parallel GC (-XX:+UseParallelGC) is the same algorithm with the stop-the-world work spread across multiple GC threads. Both collect the whole heap: young generation copy, old generation mark-sweep-compact, all inside one pause.

This is not a legacy embarrassment — it is the right design when the only goal is throughput. A batch job that runs for ten minutes and pauses for 600 milliseconds twice does not care about pause time; it cares about total CPU spent on GC, and full-heap STW collectors spend the least. The trap is scaling: pause length grows roughly with live-set size, so a Parallel collector that pauses 50 ms on a 2 GB heap may pause multiple seconds on a 32 GB heap with the same live-data ratio. The collector scales with cores; the pause scales with heap.

G1: garbage-first, region-based, pause-targeted

G1 has been the default since JDK 9, and its core idea is to chop the heap into regions — typically between 1 and 32 MB, sized to a power of two — and collect the regions with the most garbage first. Hence “garbage first”. The generational structure still exists, but the young generation is a set of regions rather than a contiguous block, so its size can flex between -XX:G1NewSizePercent and -XX:G1MaxNewSizePercent to hit the pause target you set with -XX:MaxGCPauseMillis (200 ms by default).

G1 still pauses for young collections and for the marking phase, but it keeps pauses bounded by only collecting a subset of old-generation regions per cycle — mixed collections that incrementally walk the old gen over many short pauses instead of one long one. The prediction engine estimates how many regions it can afford per pause, and that estimate is where the failure mode lives: if live data in old regions is dense, evacuation of even a few regions blows the target, and G1 falls back to a full, stop-the-world compaction of the whole heap — parallel across threads since JDK 10, but still a full-heap pause. You will see it as a Pause Full (G1 Compaction Pause) line in the logs.

The classic way to trigger this by accident is humongous allocations: any object larger than roughly half a region is “humongous” and gets a contiguous run of regions all to itself. Caches of large arrays, big byte[] buffers, and deserialized payloads are typical offenders. Humongous regions fragment the heap in a way region-based collection struggles to clean up promptly, and G1 added eager reclamation of unreferenced humongous objects specifically because this hurt so many real workloads. If your GC logs show a growing humongous region count, the fix is region sizing (-XX:G1HeapRegionSize) or smaller allocations — not a flag that tweaks the pause target.

ZGC: concurrent relocation and sub-millisecond pauses

ZGC takes the opposite bet: do essentially everything — marking, relocation, reference processing — concurrently with the application, and keep the application paused only for the few phases that genuinely require it. Pauses are sub-millisecond and, critically, independent of heap size, because the pause does no scanning proportional to live data. ZGC works with heaps from a few hundred megabytes to 16 TB, and since JDK 24 it has been a generational collector by design — the young generation gets collected more often than the old one, because most objects die young and collecting the young gen concurrently is cheaper than repeatedly tracing the whole heap. The old -XX:+ZGenerational opt-in flag is gone; there is nothing to switch.

How does an application thread survive its objects being moved underneath it? Two mechanisms. Colored pointers pack GC metadata into otherwise-unused bits of the 64-bit object reference itself, so a reference simultaneously encodes which heap view it points into and whether it has been visited by the current cycle. Load barriers then intercept every reference load: when a thread reads a reference that ZGC has relocated, the barrier heals it in place, updating the reference to point at the new location before the thread continues. The application pays a small, fixed tax on every reference access, in exchange for pauses that stop scaling with heap size.

The trade is throughput and footprint. Barrier work and concurrent GC threads cost CPU — budget roughly 10 percent — and ZGC’s default posture is generous with memory: it uncommits unused memory back to the OS after an idle period (300 seconds by default), but its adaptive sizing means the honest way to run it is to set -Xms and -Xmx to the same value and give it the heap it needs. Starving a latency collector to save RAM is how you turn a pauseless design into a thrashing one.

Shenandoah: the other pauseless collector

Shenandoah achieves the same goal — compaction concurrent with the application, sub-millisecond pauses — with a different mechanism: instead of metadata in the pointer, it uses a forwarding pointer per object and read/write barriers that resolve it. Historically the barrier strategy made Shenandoah cheaper on workloads dominated by reference updates, while ZGC’s design leaned harder on loads; modern versions of both have converged enough that measured differences are workload-specific. The practical difference is distribution: Shenandoah ships in OpenJDK builds such as Temurin but is not included in Oracle’s JDK builds, so on many infrastructures the decision is made for you. Both are production-grade; pick by benchmarking your workload, not by folklore.

Choosing, and then verifying

The decision procedure fits in four lines. Throughput-bound batch work with pauses nobody observes: Parallel. Everything under roughly 4-8 GB of heap where 50-200 ms pauses are acceptable: G1, which is why it is the default. Latency-sensitive services on large heaps — the p99 must stay flat as the heap grows: ZGC (or Shenandoah on a build that ships it). Tiny containers where even G1’s bookkeeping matters: Serial is a legitimate answer.

Then verify with GC logs instead of vibes. Unified logging is one flag:

# Pause times, cause, and heap before/after for every collection
java -Xlog:gc*:file=/var/log/myapp/gc.log:time,uptime,level,tags -jar app.jar

# Quick summary of pause distribution
grep "Pause " gc.log | awk '{print $NF}'

And a minimal reproduction harness for humongous pressure under G1:

// Run with: java -Xmx1g -Xlog:gc -XX:+UseG1GC HumongousDemo
public class HumongousDemo {
    public static void main(String[] args) {
        // Default region size on a 1g heap is 1 MB, so 600 KB arrays
        // are humongous (> 50% of a region) and each gets its own
        // contiguous region allocation.
        for (int i = 0; i < 100_000; i++) {
            byte[] chunk = new byte[600 * 1024];
            if (i % 2 == 0) {
                // Retain every other chunk: live humongous set grows.
                HUMONGOUS.add(chunk);
                if (HUMONGOUS.size() > 200) {
                    HUMONGOUS.clear(); // sudden mass reclamation
                }
            }
        }
    }
    static final java.util.List<byte[]> HUMONGOUS = new java.util.ArrayList<>();
}

Watch the log for Humongous regions: lines climbing between collections — that is fragmentation forming in real time.

The part nobody says out loud

Most “GC problems” are allocation problems. A service that allocates 3 GB per second will make any collector work hard; a service that allocates 50 MB per second runs fine on all of them. Before tuning flags, find who allocates: an allocation-profiled flame graph (async-profiler’s alloc mode) usually surfaces a serializer, a logging call building strings per request, or a cache rebuilding arrays per lookup. Fixing one hot allocation site moves your pause profile more than any -XX flag ever will. The collector menu decides the shape of your pauses; your allocation rate decides how often you pay them.

Leave a Reply

Your email address will not be published. Required fields are marked *