Skip to content
javahacks.dev
JVM & Performance

G1 vs ZGC vs Shenandoah vs Parallel and How to Choose

Compare the G1, ZGC, Shenandoah, Parallel and Serial collectors on pauses, throughput and footprint, and pick one with a test on your own workload.

7 min read
Summarize in AI
Flat illustration of a heap of objects with the unreachable ones being recycled, with the OpenJDK, Prometheus, Linux and Grafana logos.

Every few months someone on the team proposes switching the garbage collector because a conference talk said the pauses are gone. Sometimes they are right. More often the service had no pause problem, and the switch costs CPU and tail latency somewhere nobody was looking. The honest answer to "which collector" is a short decision rule plus a measurement you can run in ten minutes.

This post compares the five collectors in OpenJDK on what you will actually feel: pause time, throughput, memory and CPU overhead. It includes a small latency benchmark whose numbers come from a real run, says plainly how much to trust them, and ends with the procedure for deciding on your own workload. The benchmark ran on JDK 17.0.1; the feature statements refer to JDK 25 and name the release where a behavior changed.

The comparison

CollectorPausesThroughputFootprintChoose it when
G1 (-XX:+UseG1GC)Tens of milliseconds, tunable with a pause goalGoodModerateAlmost always: it is the default
ZGC (-XX:+UseZGC)Sub-millisecond to a few ms, nearly independent of heap sizeSlightly lower than G1HigherLatency matters and heaps are large
Shenandoah (-XX:+UseShenandoahGC)Short, nearly independent of heap sizeSlightly lower than G1ModerateSame case as ZGC, on distributions that ship it
Parallel (-XX:+UseParallelGC)Longest: stops all threads for every collectionBestSmallBatch jobs where only total time matters
Serial (-XX:+UseSerialGC)One thread, stops the worldFine for small heapsSmallestTiny heaps, single CPU, short-lived tools

ZGC and Shenandoah move the expensive work, marking and compacting live objects, to run concurrently with your threads. The price is CPU spent on the collector's own threads and a small tax on every reference read or write, called a barrier. G1 and Parallel stop your threads for the compaction instead. So the real trade is: pay with pauses, or pay with CPU.

Two recent changes affect old advice. ZGC became generational in JDK 21 (JEP 439), the generational mode became the default in JDK 23 (JEP 474), and the non-generational mode was removed after that. Shenandoah got a generational mode as well, an experiment in JDK 24 and a product feature in JDK 25. Benchmarks and blog posts about ZGC written before 2023 describe a collector that no longer exists in that form.

A benchmark you can run

The program below keeps a 1.5-million-entry map alive, about 150 MB, and for eight seconds replaces random entries in batches of fifty, which creates garbage the way a cache update does. It records the time of each batch and prints percentiles:

src/main/java/dev/javahacks/gc/Latency.javajava
import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

public class Latency {
    public static void main(String[] args) {
        Map<Integer, String> live = new ConcurrentHashMap<>();
        for (int i = 0; i < 1_500_000; i++) {
            live.put(i, "value-" + i);                     // the live set
        }
        long end = System.nanoTime() + 8_000_000_000L;
        long[] lat = new long[4_000_000];
        int n = 0;
        Random r = new Random(1);
        long ops = 0;
        while (System.nanoTime() < end && n < lat.length) {
            long t0 = System.nanoTime();
            for (int k = 0; k < 50; k++) {
                int key = r.nextInt(1_500_000);
                live.put(key, "v-" + ops++ + "-" + key);   // garbage: the replaced value
            }
            lat[n++] = System.nanoTime() - t0;
        }
        long[] s = Arrays.copyOf(lat, n);
        Arrays.sort(s);
        System.out.printf("batches=%d p50=%.3f ms p99=%.3f ms p99.99=%.3f ms max=%.1f ms%n",
            n, s[n / 2] / 1e6, s[(int) (n * 0.99)] / 1e6, s[(int) (n * 0.9999)] / 1e6, s[n - 1] / 1e6);
    }
}

Run it once per collector with the same fixed heap:

Shell
for gc in UseParallelGC UseG1GC UseZGC UseShenandoahGC; do
  echo "== $gc"; java -Xms1g -Xmx1g -XX:+$gc Latency
done
Text
== UseParallelGC
batches=613984 p50=0.011 ms p99=0.019 ms p99.99=0.243 ms max=147.1 ms
== UseG1GC
batches=564486 p50=0.013 ms p99=0.020 ms p99.99=1.216 ms max=29.7 ms
== UseZGC
batches=434019 p50=0.016 ms p99=0.042 ms p99.99=0.516 ms max=13.3 ms
== UseShenandoahGC
batches=776341 p50=0.009 ms p99=0.023 ms p99.99=0.345 ms max=21.0 ms

Read the columns for what they say. The max column is the longest stall any batch saw, and it follows the textbook ordering for the stop-the-world collectors: Parallel stopped the program for 147 ms, G1 for about 30 ms. ZGC's worst case was 13 ms, which on this unrefined single run includes scheduler noise as well as collector work. The batches column is a throughput proxy, and ZGC completed the fewest (434,019), because its barriers and concurrent threads consume CPU that the application would otherwise use.

Now the caveats, because this is the part people skip. This is one run per collector on a 10-core laptop, a 150 MB live set in a 1 GB heap, on a non-generational ZGC from JDK 17. Shenandoah winning on throughput here says more about this workload than about Shenandoah. Do not copy these numbers into a decision. Copy the method, and run it on your data with your allocation pattern for at least ten minutes, repeated three times.

So which one

For most services, keep G1 and spend the effort elsewhere. It has been the default since Java 9, it is tuned by a huge installed base, and its pauses of tens of milliseconds are invisible next to a database call. Our rule:

  1. Start with G1. Set -Xmx, leave the rest alone, and read the GC log under real load. If p99 latency is within your target, you are done.
  2. Switch to ZGC or Shenandoah when pauses show up in your latency percentiles. The symptom is a p99.9 spike that lines up with GC log entries, or a heap of tens of gigabytes where G1's pauses grow. Pauses on these collectors barely depend on heap size, which is their main selling point.
  3. Choose Parallel for batch jobs where nobody is waiting on an individual request and finishing sooner is the goal. It does the least bookkeeping per object.
  4. Choose Serial for small, short-lived processes: command-line tools, build steps, containers with under two CPUs. It has the smallest footprint and no thread-coordination cost.

A fifth path is not to switch collectors but to allocate less. Cutting garbage with primitive arrays, avoiding boxing in hot loops and streaming results instead of materializing them gives every collector less to do. See garbage collection explained for how allocation rate drives the cost.

The container surprise

You do not always get the collector you think you asked for. The JVM runs ergonomics at startup: if it sees fewer than two available processors, or less than roughly 1.8 GB of memory, it treats the machine as a "client" and picks Serial, ignoring that G1 is the server default. A Kubernetes pod with limits.cpu: 1 therefore runs Serial, and a service moved into a smaller container gets slower pauses than it had on a VM. Check what you are running:

Shell
java -XX:+PrintFlagsFinal -version | grep -E 'Use(Serial|Parallel|G1|Z|Shenandoah)GC'
jcmd <pid> VM.flags | tr ' ' '\n' | grep -E 'Use.*GC'

If a one-CPU container needs G1, ask for it with -XX:+UseG1GC. The CPU interaction goes further than choice: concurrent collectors need cores to run their threads, so ZGC on a pod limited to one core competes with the application for the only CPU. See CPU limits in containers.

How to decide with evidence

A procedure that takes an afternoon and prevents a month of regret:

  1. Replay realistic traffic against a staging copy at production rate, with the same heap and CPU limits as production.
  2. Enable GC logging: -Xlog:gc*:file=gc.log:time,uptime,level,tags.
  3. Record request latency percentiles (p50, p99, p99.9) and CPU utilization, not just averages.
  4. Run each candidate collector for at least ten minutes after warm-up, three times.
  5. Compare p99.9 latency, total CPU and resident memory. Switch only if the pause win is larger than the CPU and memory you give up.

How to read the log that step two produces is in reading GC logs, and what to adjust inside G1 once you have decided to stay is in tuning G1 without cargo culting.

Where the comparison does not apply

If your heap is sized wrong, no collector helps; see GC overhead limit exceeded for a service that is out of memory rather than slow. For a function-as-a-service workload that starts, runs briefly and dies, collector choice is far less important than startup. Not every distribution ships every collector, so check the output of -XX:+PrintFlagsFinal on your build. The current descriptions are in the HotSpot GC tuning guide, and the generational ZGC default change is JEP 474.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.