archive2023

Choosing a garbage collector for a Spring Boot service: G1, generational ZGC or Parallel

What G1, Parallel, ZGC with the new generational mode in JDK 21, and Shenandoah each optimise for, why heap size comes first, and how to compare collectors with GC logs, JFR and latency percentiles under load.

8 min read#dev#java#performance#gc

I am moving a few Spring Boot services to JDK 21, released on 19 September 2023, and the first question was whether to switch to its new Generational ZGC (JEP 439). The short answer is “maybe, but measure first”. The longer answer starts with what each collector is built for.

What each collector optimises

Every collector trades between three things: throughput (how much CPU time goes to your code and not to GC), pause time (how long application threads are stopped), and memory overhead (how much extra heap and native memory the GC needs). You cannot have the best of all three.

Collector Flag Optimises for Typical fit
Serial -XX:+UseSerialGC Small footprint Tiny heaps, one CPU
Parallel -XX:+UseParallelGC Throughput Batch jobs, offline processing
G1 -XX:+UseG1GC Balance, pause goal Most services, the default
ZGC -XX:+UseZGC Very short pauses Latency-sensitive services, large heaps
Shenandoah -XX:+UseShenandoahGC Very short pauses Similar to ZGC, depends on your JDK build

G1

G1 is the default since JDK 9 (JEP 248). It splits the heap into regions, collects young regions often, and collects old regions a few at a time in mixed collections. It tries to keep pauses below a goal, -XX:MaxGCPauseMillis, which is 200 ms by default. This is a goal, not a promise.

For a typical Spring Boot service with a heap of a few GB, G1 is a good choice and I start there. It gets better in every release, so a service that had G1 trouble on Java 8 may behave quite differently on 17 or 21.

One detail: G1 is only the default when the JVM thinks it is on a “server-class” machine, which means at least 2 CPUs and about 1792 MB of memory. In a small container with one CPU, the JVM picks Serial GC. Check what you really get:

java -XX:+PrintFlagsFinal -version | grep -E 'Use(Serial|Parallel|G1|Z|Shenandoah)GC '

Run this inside the container with the same limits as production.

Parallel

Parallel GC stops the application for every collection, young and old, and uses all GC threads to finish fast. Pauses for a full collection of a big old generation can be long. But the total CPU spent on GC is usually low, and it has no concurrent work running beside your code.

That makes it fine for batch jobs: a Spring Batch job, a nightly import, a report generator. Nobody waits for a single response, only for the whole job to finish. For those, I would try Parallel against G1 and keep the one that finishes faster with less CPU.

For a service that answers HTTP requests, long pauses show up directly as slow requests. I would not use Parallel there.

ZGC and generational ZGC

ZGC does almost all its work concurrently with the application, including moving objects. Pauses are very short and do not grow with heap size. It became a production feature in JDK 15 (JEP 377).

Until JDK 21, ZGC was not generational. It treated all objects the same, so it had to scan the whole heap more often than a generational collector. With many short-lived objects (which is what a Spring Boot service makes: request objects, JSON trees, strings), this cost CPU and needed extra heap headroom, because allocation could go faster than the concurrent collection.

JDK 21 adds a generational mode. In JDK 21 you must turn it on with two flags:

java -XX:+UseZGC -XX:+ZGenerational -jar app.jar

With only -XX:+UseZGC you get the old non-generational mode. JEP 439 says the plan is to make the generational mode the default in a later release and then remove the old mode. So if you start with ZGC on JDK 21, I would start with the generational mode directly.

Things to know about ZGC before switching:

  • It does not use compressed object pointers, so the same data can take more heap than with G1. Do not move an -Xmx value from G1 to ZGC and assume it fits the same way.
  • It needs headroom. If the heap is too small, allocation stalls happen. The threads wait for GC to free memory. This looks like a pause in your latency numbers, even though it is not a GC pause in the log. Search the log for “Allocation Stall”.
  • The concurrent work uses CPU while your code runs. On a container with very few CPUs this competes with request threads.

Shenandoah

Shenandoah is another low-pause collector, from Red Hat. It became production in JDK 15 (JEP 379), the same release as ZGC. It is not in every JDK build. Check with java -XX:+UseShenandoahGC -version on the exact build you run in production. In JDK 21 it is not generational. I have not used it in production, so I will not say more than that it is worth a test if your vendor ships it.

Heap sizing comes first

Most GC problems I have seen in services were heap sizing problems, not collector problems. Before changing the collector:

  1. Set the heap explicitly. Either -Xmx or -XX:MaxRAMPercentage in containers. Leave room for metaspace, thread stacks and direct buffers.
  2. Look at the live set. In the GC log, the heap after a full or mixed collection is roughly your live data. The max heap should be a few times bigger than that. If the live set is close to the max heap, any collector will struggle.
  3. Consider -Xms equal to -Xmx for services. The heap does not need to grow and shrink, and you see the real memory use from the start.
  4. Check for a memory leak. A growing live set over hours is a leak, and a different collector only makes it fail later.

Only after this does a collector comparison make sense.

How to compare collectors properly

The wrong way is to start the service with each collector, send some requests by hand, and look at the average response time. The average hides exactly what low-pause collectors improve: the slow requests at the tail.

Turn on GC logs

GC logs cost very little. I keep them on in production:

java -Xlog:gc*:file=/var/log/app/gc.log:time,uptime,level,tags:filecount=5,filesize=20m \
     -jar app.jar

gc* logs all GC tags. For a first look, -Xlog:gc gives one line per collection, which is easier to read. In the log I look at:

  • pause times and how often pauses happen,
  • heap size before and after each collection,
  • for G1, any “Pause Full” lines (a full GC in G1 means it could not keep up),
  • for ZGC, “Allocation Stall” lines.

Tools like GCViewer or GCeasy can read these files and draw graphs. Reading the raw log is still useful to check what the tool says.

Record with JFR

Java Flight Recorder is built into the JDK and has low overhead. Start a recording during the load test:

java -XX:StartFlightRecording=duration=10m,filename=gc-test.jfr,settings=profile \
     -jar app.jar

Or start it on a running process:

jcmd <pid> JFR.start duration=10m filename=gc-test.jfr settings=profile

Open the file in JDK Mission Control, or print GC events on the command line:

jfr print --events jdk.GarbageCollection gc-test.jfr | less
jfr summary gc-test.jfr

JFR also shows allocation by stack trace. Often the best GC improvement is to allocate less in one hot method, and JFR shows you which one.

Load test with a realistic load and look at percentiles

Run the same load test against each collector setup:

  • Same JDK build, same container limits, same heap size (or heap sizes that you chose on purpose for each collector).
  • A fixed request rate, close to real production traffic. A tool that just sends requests as fast as it can hides latency problems, because it slows down when the service slows down. wrk2 and Gatling can run at a fixed rate.
  • Long enough to include old-generation collections, not only young ones. Ten minutes is a minimum for me, longer if the service has caches that fill slowly.
  • A warmup phase that you do not count.
  • Record p50, p99, p99.9 and max latency, plus CPU use and container memory.

In Spring Boot, Actuator with Micrometer already exposes jvm.gc.pause and HTTP request timers. If you have Prometheus and Grafana, you can compare runs there. Make sure the request timers publish percentiles or histograms, because the default summary is not enough for this.

Then compare. Typical outcomes:

  • p50 stays the same with all collectors. This is normal. GC rarely changes the median much.
  • p99 or p99.9 is better with ZGC, but CPU use is higher. You decide if the tail is worth the CPU.
  • No real difference. Keep G1. The default has the most documentation and the most people who know it.

Run each setup more than once. If two runs of the same setup differ as much as two collectors do, you have not learned anything yet.

My decision list

  • Batch job, nobody waits for single responses: try Parallel and G1, keep the faster one.
  • Normal Spring Boot service, heap up to a few GB, latency goals in the hundreds of ms: G1, set the heap size, keep GC logs on.
  • Service with strict tail-latency goals, or a large heap where G1 pauses are too long: test generational ZGC on JDK 21 (-XX:+UseZGC -XX:+ZGenerational), give it more heap headroom, and watch CPU.
  • Very small container (1 CPU, small heap): check what the JVM picked. Serial may be the right choice there anyway.
  • Not on JDK 21 yet: G1, or non-generational ZGC on 17 if you measured that it helps. I would not plan a ZGC migration on 17 now that the generational mode exists in 21.

When you test generational ZGC, watch two things: allocation stalls (the jdk.ZAllocationStall event in JFR) and CPU use in small containers. A pause-time graph alone does not show either.