Video in progress

How does generational ZGC in Java 21 differ from plain ZGC, and when does it make sense to move to it?

Generational ZGC splits the heap into young and old and collects young objects often and cheaply. As a result, on the same heap, CPU use and allocation stalls go down; starting with JDK 23 it is the default ZGC mode.

📖 Answer

The original ZGC was single-generation: it marked the whole heap every time. Its pauses were very short (under a millisecond), but in services with a high allocation rate the GC couldn't keep up, and threads fell into an "allocation stall". To avoid that, people made the heap big.

Generational ZGC (JEP 439, JDK 21) relies on the hypothesis that "most objects die young":

  • the young gen is collected often and in small amounts;
  • the old gen is marked less often;
  • as a result, the same load needs less heap and less CPU.

By version:

# JDK 21-22: both flags are needed to turn it on
java -XX:+UseZGC -XX:+ZGenerational -jar app.jar
# JDK 23+: generational is the default, non-generational was removed later
java -XX:+UseZGC -jar app.jar

When should you move? If pauses of 50-200 ms in p99 with G1 are breaking the SLO and the heap is bigger than a few GB, it is worth trying. But ZGC isn't free: throughput may drop a bit because of the load barriers, and RSS can differ noticeably from G1's. I usually compare on a canary with the same traffic: p99, CPU, RSS. For an ordinary CRUD service with a small heap (around 512 MB), G1 is still a good choice.