Java / Java 21 Interview Questions
What is Generational ZGC in Java 21 and why does it improve upon the original ZGC?
JEP 439 finalises Generational ZGC, which extends the existing low-latency Z Garbage Collector with separate young and old generations. Classic ZGC (introduced in Java 11) collects all live objects on every GC cycle, which is thorough but wastes CPU on long-lived objects that will not be collected.
| Aspect | Classic ZGC | Generational ZGC |
|---|---|---|
| Generations | Single generation — all objects | Young + Old (weak generational hypothesis) |
| GC frequency | Full heap every cycle | Young GC often, Old GC rarely |
| CPU overhead | Higher (scans all live data) | Lower (mostly scans short-lived young gen) |
| Allocation rate | Can struggle at very high rates | Handles higher allocation rates |
| Max pause | <1 ms (both) | <1 ms (both) |
| Enable flag | Default in Java 21 | ZGC is generational by default in Java 21 |
// Generational ZGC is the default ZGC mode in Java 21
// Enable ZGC (generational by default):
// java -XX:+UseZGC MyApp
// To use non-generational ZGC (legacy mode):
// java -XX:+UseZGC -XX:-ZGenerational MyApp
// Key tuning flags:
// -Xms / -Xmx — min and max heap
// -XX:SoftMaxHeapSize=N — soft limit ZGC tries to stay under
// -XX:ZUncommitDelay=N — delay before returning memory to OS
// Monitoring GC:
// -Xlog:gc*:file=gc.log
// jcmd GC.run — trigger a GC cycle
// jstat -gcutil 1s — watch GC stats every second The weak generational hypothesis states that most objects die young. By collecting the young generation far more frequently than the old generation, Generational ZGC spends less CPU per GC cycle and handles higher allocation rates — particularly beneficial for microservices and high-throughput applications running on Java 21 virtual threads.
More Related questions...