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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
