G1GC vs ZGC vs Shenandoah in 2026: Choosing the Right JVM Garbage Collector
A p99 latency alert fires at 3 a.m. The service is not out of CPU, the database is fine, and the heap graph looks healthy — but every few seconds a handful of requests take 400 ms instead of 4 ms. Nine times out of ten the cause is the garbage collector, and nine times out of ten the team is still running the default it inherited from a Dockerfile written years ago.
Collector choice is one of the few JVM decisions that changes both tail latency and cloud bill without touching application code. It is also one of the easiest to get wrong, because the internet is full of advice written for JDK 8 heaps running on hardware nobody has anymore.
TL;DR: Keep G1 as the default for typical web services — it is the JDK default for good reason and it balances throughput and pause time better than most teams need. Move to ZGC when p99 latency is a product requirement and your heap is large (tens of GB), and you accept some throughput and memory-headroom cost. Choose Shenandoah if you run OpenJDK builds that ship it and want pause times decoupled from heap size with a smaller footprint change than ZGC. Use Parallel only for batch jobs where throughput is everything. Use Epsilon only for short-lived benchmarks.
The Collectors Side by Side
The table below compares design intent, not marketing claims. Pause figures are documented design targets and typical behavior, not guarantees for your workload.
| G1 | ZGC | Shenandoah | Parallel | Epsilon | |
|---|---|---|---|---|---|
| Primary goal | Balanced latency/throughput | Ultra-low pause | Low pause, heap-size independent | Maximum throughput | No collection at all |
| Default since | JDK 9 | No (opt-in) | No (opt-in) | Pre-JDK 9 server default | No |
| Pause profile | ~tens of ms, target via MaxGCPauseMillis | Sub-millisecond design target | Low, mostly independent of heap size | Full-heap stop-the-world | None |
| Compaction | Yes, region evacuation | Yes, concurrent | Yes, concurrent | Yes, stop-the-world | N/A |
| Heap headroom cost | Moderate | Higher (colored pointers, relocation) | Moderate | Lowest | N/A |
| Throughput cost | Low | Higher than G1 in exchange for latency | Between G1 and ZGC | Highest | Zero GC work |
| Large heaps (100 GB+) | Workable with tuning | Designed for it | Designed for it | Long pauses | N/A |
| Flag | -XX:+UseG1GC | -XX:+UseZGC | -XX:+UseShenandoahGC | -XX:+UseParallelGC | -XX:+UseEpsilonGC |
Decision Matrix: Match the Collector to the Workload
| Workload | Collector | Reason |
|---|---|---|
| REST or gRPC service, 4–16 GB heap, p99 matters | G1 | Default, well-tuned, predictable; least operational surprise |
| Latency-critical API, 32–256 GB heap | ZGC | Pauses stay sub-millisecond while the heap grows |
| Same as above on OpenJDK builds without ZGC | Shenandoah | Lowest-pause option available on that build |
| Nightly ETL, report generation, batch scoring | Parallel | Highest throughput; pauses are irrelevant when nothing waits |
| Startup smoke test measuring allocation rate | Epsilon | Removes GC from the measurement entirely |
| Tiny container (256–512 MB), low allocation rate | G1 (or Serial) | Overhead of concurrent collectors is not worth it |
Why the Default Is Usually Right (and When It Is Not)
G1 has been the default since JDK 9 and it is genuinely good: region-based heap layout, incremental collection, and a pause target you can set with -XX:MaxGCPauseMillis=200. For a service with a 8 GB heap and a few hundred requests per second, G1 will hit single-digit-millisecond young pauses and occasional mixed collections in the tens of milliseconds — perfectly acceptable for a p99 target of 100–200 ms.
G1 stops being the right answer in two situations. The first is very large heaps. As the heap grows, G1’s mixed collections have more regions to evacuate per cycle, and pause times creep upward even with a target set. The second is a hard latency SLO in the low single-digit milliseconds — a target G1’s stop-the-world phases cannot meet no matter how you tune it, because evacuation pauses are inherently stop-the-world.
That is exactly the gap ZGC and Shenandoah were built to close.
G1: Tuning That Actually Matters
Most G1 tuning advice is noise. Three flags cover the overwhelming majority of real cases:
| |
-Xmsequal to-Xmxremoves heap resizing as a variable. In containers this is the single most common cause of “random” latency spikes after a quiet period.MaxGCPauseMillisis a goal, not a cap. Setting it to 20 ms on a 30 GB heap pushes G1 toward smaller young generations and more frequent collections — more total work for a target it cannot always hit. Start at 100–200 ms and only lower it with measurements.-Xlog:gc*is not optional. Without GC logs you are guessing. The output format is stable and cheap to ship to your log pipeline.
Two G1-specific traps are worth knowing. Humongous allocations — objects larger than half a region — bypass the young generation and can cause fragmentation and unexpected pauses. If you see humongous in GC logs, either raise -XX:G1HeapRegionSize or fix the allocation (usually a large array or an oversized response buffer). And G1NewSizePercent/G1MaxNewSizePercent should not be hand-tuned unless you have a specific reason; G1’s adaptive sizing is better than most hand-written values.
For reading the logs you produce, our JVM GC log analysis guide covers gcviewer and GCtoolkit workflows in detail.
ZGC: Sub-Millisecond Pauses for Large Heaps
ZGC’s design goal is a pause time that does not scale with heap size. It achieves this with colored pointers and load barriers: most of the work — marking, relocation, remapping — happens concurrently while application threads keep running.
| |
What changed recently matters for tuning advice found online. ZGC shipped as an experimental collector, became production-ready, and then gained a generational mode that handles short-lived objects far more efficiently than the original single-generation design. On current JDKs the generational mode is the default, which means much of the “ZGC is throughput-hungry” advice from its early days is now out of date — the generational design specifically targets allocation-heavy services.
The real costs of ZGC are memory-related, not CPU-related:
- Headroom. ZGC needs room to relocate objects while the application allocates. Budget 20–30% more heap than you would give G1 for the same workload, or you will see allocation stalls that look like pauses.
SoftMaxHeapSizeis the pressure valve: it lets ZGC start collecting earlier instead of letting the heap grow to-Xmx. In containers this is more useful than shrinking-Xmx, because the JVM can still absorb a burst.- Virtual address space. Colored pointers and multi-mapping want a large virtual address range. On 64-bit Linux this is normally fine; in restrictive sandboxes or 32-bit environments it is not.
One practical rule: do not enable ZGC and G1 tuning flags together. MaxGCPauseMillis has no effect on ZGC, and copying a G1 flag set into a ZGC deployment just adds confusion for the next person on call.
Shenandoah: Pause Times That Ignore Heap Size
Shenandoah takes a different route to the same goal. It performs concurrent compaction using Brooks-style forwarding pointers, and its pause times are largely independent of heap size. It is available in OpenJDK builds from several vendors (it originated at Red Hat) and is enabled with a single flag:
| |
The heuristics flag is the one thing worth understanding:
adaptiveis the default and the right starting point. It adjusts collection frequency to observed allocation pressure.staticis for when you want deterministic behavior and have measured the allocation rate yourself.compacttrades more frequent collections for a smaller footprint, useful when memory is the binding constraint.
Shenandoah’s historical weak spot was throughput on allocation-heavy workloads, because every object access goes through a forwarding check. Generational modes added in recent builds narrow that gap considerably, and for services that allocate moderately — request handlers, API gateways, CRUD services — the difference against G1 is usually in the noise.
Choose Shenandoah over ZGC when your JDK distribution ships it and does not ship ZGC, or when you want low pauses without ZGC’s memory headroom premium. Choose ZGC over Shenandoah when you are on a JDK where ZGC’s generational mode is mature and your heap is in the tens of gigabytes.
Parallel and Epsilon: Two Narrow but Real Use Cases
Parallel GC is the throughput king. It stops the world, uses all cores, and finishes fast. For a nightly batch job that processes 40 GB of records and has a five-hour window, it will beat every concurrent collector on wall-clock time. The flag is -XX:+UseParallelGC, and the only tuning you need is -XX:ParallelGCThreads if you are pinning CPUs.
Epsilon does no collection at all. It allocates until the heap is exhausted, then the JVM exits. That sounds useless until you need to measure allocation rate or run a short benchmark without GC interference:
| |
If the process dies with OutOfMemoryError: Java heap space and no GC log lines, that is Epsilon working as designed. Never run it in a long-lived service.
Container and Kubernetes Tuning
Collector flags belong in the container image or the deployment manifest, not in a wiki page nobody reads. JAVA_TOOL_OPTIONS is the cleanest injection point because it applies before main() and shows up in startup logs:
| |
Three container-specific notes:
MaxRAMPercentagebeats-Xmxin orchestrated environments. The JVM reads the cgroup limit, so the same image behaves correctly on a 2 GB and an 8 GB pod. Set it to 70–75% and leave the rest for metaspace, code cache, thread stacks and direct buffers.AlwaysPreTouchcosts startup time proportional to heap size. On a 64 GB heap it can add seconds; on a 2 GB heap it is nearly free and removes page-fault jitter from the first minutes of traffic.- GC logs must go somewhere durable. In Kubernetes, writing to a mounted volume or shipping to stdout are both fine — but a GC log that only exists inside a crashed pod is worthless.
Benchmarking Your Choice Instead of Trusting a Blog Post
Every collector comparison you read, including this one, is workload-dependent. The only number that matters is your number, and getting it takes an afternoon:
- Capture production allocation behavior. Run a load test with your real request mix — synthetic
GET /healthtraffic will not allocate like your actual endpoints. - Hold everything else constant. Same heap, same CPU limit, same request rate. Changing the collector and the heap size at once tells you nothing.
- Compare p50, p99, p999 and throughput, not averages. Averages hide exactly the pauses you are trying to eliminate.
- Run long enough to include a full heap cycle. A 60-second test on a 30 GB heap often never triggers the collection pattern that hurts you.
- Watch memory, not just time. A collector that halves p99 while pushing RSS into swap is not a win in a container with a hard limit.
For profiling the rest of the JVM while you do this, our JVM profiler comparison covers async-profiler, JFR and VisualVM, and if you are deciding between JVM distributions rather than collectors, the GraalVM vs OpenJ9 vs HotSpot comparison is the companion piece.
Pitfalls That Bite in Production
Copying flags between collectors. -XX:MaxGCPauseMillis is meaningless for ZGC and Shenandoah; -XX:G1HeapRegionSize is meaningless outside G1. Leftover flags do not error — they are ignored, which is worse, because the next engineer assumes they are doing something.
Forgetting -Xms. A JVM that starts at 512 MB and grows to 8 GB pays for heap expansion under load. In containers, set -Xms equal to -Xmx, or use MaxRAMPercentage with InitialRAMPercentage matching it.
Setting MaxGCPauseMillis to a fantasy value. 20 on a 40 GB heap does not produce 20 ms pauses; it produces frequent small collections and more total CPU. If you need sub-10ms pauses, switch collectors instead of tightening the target.
Ignoring humongous allocations. Large arrays and buffers are the most common reason a “tuned” G1 setup still shows unexpected pauses. Look for humongous entries in the GC log before touching any other flag.
Benchmarking on a laptop with a 2 GB heap. Every collector looks identical at 2 GB. The differences that matter show up at 32 GB and above, which is where you should be testing if that is what you run in production.
Assuming Shenandoah is everywhere. It is in OpenJDK builds from several vendors but not all distributions enable it. Verify with java -XX:+PrintFlagsFinal -version | grep -i shenandoah before you put it in a manifest.
FAQ
Is G1 still the default collector in 2026?
Yes. G1 remains the default for server-class JVMs, and for the majority of services it is still the right choice. Switching away from it is justified by a specific measured problem — usually tail latency on a large heap — not by the existence of newer collectors.
Should I use ZGC for a small service with a 2 GB heap?
Usually not. ZGC’s advantage appears when heap size makes G1 pauses visible; at 2 GB, G1’s pauses are already short, and ZGC adds memory headroom requirements plus a more complex failure surface. Tune G1 first, and only move if measurements justify it.
Does the collector change my application’s memory usage?
Yes, meaningfully. ZGC needs extra headroom for concurrent relocation and typically wants 20–30% more heap than G1 for the same workload. Shenandoah sits in between. Parallel uses the least for a given workload because it does not maintain concurrent data structures. Size the container limit against the collector you actually run.
How do I tell which collector a running JVM uses?
Run java -XX:+PrintFlagsFinal -version | grep -E "Use(G1|Z|Shenandoah|Parallel|Serial|Epsilon)GC" and look for the flag set to true. For a running process, jcmd <pid> VM.flags prints the effective flag set, which is also the fastest way to catch a container that silently ignored your JAVA_TOOL_OPTIONS.
Can I switch collectors without a code change?
Yes. Collector selection is a JVM startup flag, so it is a deployment configuration change. The caveats are operational: heap sizing may need adjustment, GC log dashboards and alert thresholds will shift, and any pause-time SLO you tuned around G1 needs re-baselining after the switch.
💰 想测试你的市场判断力?我用 Polymarket 做预测市场交易——这是全球最大的预测市场平台,从大选结果到技术监管时间线,什么都可以押注。和赌博不同,这是真正的信息市场:你懂的信息越多,胜率越高。我靠预测技术相关事件的走向已经赚了不少。用我的邀请链接注册:Polymarket.com