Java / Java 21 Interview Questions
What garbage collectors are available in Java 21 and how do you choose between them?
Java 21 ships four major garbage collectors, each optimised for different trade-off points on the throughput-vs-latency spectrum.
| GC | Flag | Pause target | Throughput | Best for |
|---|---|---|---|---|
| Serial GC | -XX:+UseSerialGC | Not optimised — STW | Low | Single-core, small heap (<100 MB) |
| Parallel GC | -XX:+UseParallelGC | Seconds (STW) | Highest | Batch, throughput-first, CPU-heavy |
| G1 GC (default) | -XX:+UseG1GC | <200 ms target | High | General-purpose, heaps 1–32 GB |
| ZGC (Generational) | -XX:+UseZGC | <1 ms | Good | Low-latency, very large heaps (>32 GB) |
| Shenandoah | -XX:+UseShenandoahGC | <10 ms | Good | Low-latency alternative to ZGC |
// G1 (default since Java 9) — good general purpose starting point
// java -Xms4g -Xmx4g -XX:+UseG1GC -XX:MaxGCPauseMillis=200 MyApp
// ZGC — for large heaps needing sub-millisecond pauses
// java -Xms16g -Xmx32g -XX:+UseZGC MyApp
// In Java 21, ZGC is generational by default
// Parallel GC — batch jobs, maximum throughput
// java -Xms8g -Xmx8g -XX:+UseParallelGC -XX:ParallelGCThreads=8 MyApp
// GC logging (useful in all environments)
// -Xlog:gc*:file=gc.log:time,uptime:filecount=5,filesize=20m
// Key GC metrics to monitor:
// - GC pause duration and frequency
// - Allocation rate (Eden fill rate)
// - Promotion rate (objects escaping young gen)
// - Heap occupancy after GC
// - Metaspace usageFor Java 21 virtual-thread applications: ZGC (Generational) or G1 are the best choices. Virtual threads create many short-lived objects (parked continuations), and G1/ZGC handle high young-generation allocation rates well. Avoid Parallel GC for latency-sensitive applications — its stop-the-world pauses can be seconds long on large heaps.
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...
