How do G1, ZGC and Parallel GC differ, and how do you tune garbage collection?
Basics
GC finds objects unreachable from GC roots (thread stacks, static fields, JNI references) and reclaims them. Most objects die young (the generational hypothesis), so collectors scan the young generation frequently and cheaply and the old generation rarely.
Collectors
- Parallel GC: stop-the-world, multi-threaded; maximises throughput; pauses grow with heap size. Good for batch jobs.
- G1 (default since Java 9): heap divided into equal regions; collects the regions with the most garbage first; targets a pause goal (
-XX:MaxGCPauseMillis=200by default). Young collections are stop-the-world, old-generation marking is mostly concurrent, followed by mixed collections. A balanced default for services with heaps of a few to tens of GB. - ZGC (production-ready since Java 15, generational since Java 21): concurrent marking and relocation using coloured pointers and load barriers; pauses typically under a millisecond regardless of heap size (up to terabytes). Costs some throughput and CPU. Choose it for latency-sensitive services with strict p99 SLOs or very large heaps.
- Shenandoah: similar goals to ZGC (in OpenJDK builds from Red Hat and others).
- Serial: single-threaded; the JVM picks it automatically in containers with less than 2 CPUs or under about 1.8 GB of memory, which surprises people.
How to tune, in order
- Define the goal: throughput, p99 latency or footprint.
- Enable GC logging:
-Xlog:gc*:file=gc.log:time,uptime,level,tags, and analyse with GCeasy or JDK Mission Control. - Right-size the heap first (
-Xmsequal to-Xmxavoids resizing in servers), then pick the collector. - Reduce allocation in the code (it is often the real fix): avoid needless boxing, giant temporary collections and string building in hot paths.
- Change one flag at a time and re-measure under realistic load.
Follow-up questions interviewers ask
Try answering each one before you open it.
What does a stop-the-world pause mean and why does it matter?
All application threads are halted at a safepoint while the collector does work that cannot run concurrently. During the pause no requests are served, so pauses show up directly as latency spikes and can trigger client timeouts, failed health checks or leader re-elections. Low-pause collectors move most work to run concurrently with the application.
Your service has p99 latency spikes every few minutes. How do you check whether GC is the cause?
Correlate request latency with GC events: look at GC logs or the jvm.gc.pause Micrometer metric for pauses matching the spikes. Check for long young pauses (too much surviving data, often from caches), mixed or full GCs (old generation filling up, humongous allocations in G1) and allocation rate. Fixes range from resizing generations or the heap, raising the pause target, fixing allocation-heavy code and avoiding humongous objects, to switching to ZGC.