How JVM garbage collection works in G1GC and Generational ZGC
Compare G1GC regions and remembered sets against Java 21 Generational ZGC colored pointers and load barriers, plus Safepoint tuning and production pitfalls.
Stop-The-World (STW) garbage collection pauses are one of the most common causes of p99 latency spikes in JVM backends. This post explains the weak generational hypothesis, Safepoints, and how Java’s default G1GC compares to Java 21 Generational ZGC in architecture and production tuning.
Tested on Java 21 LTS (Eclipse Temurin / OpenJDK HotSpot JVM, JEP 439 Generational ZGC).
Weak generational hypothesis, reachability, and Safepoints
Modern JVM garbage collectors are built around the Weak Generational Hypothesis. Most objects allocated during a request die almost immediately, and long-lived objects rarely point to newly created ones. Separating the heap into a Young generation and an Old generation lets the collector reclaim short-lived objects quickly without scanning the entire heap on every cycle. (For a breakdown of how heap generations fit alongside Metaspace and native memory, see JVM runtime memory areas and OOM types.)
To decide which objects are still alive, the JVM runs Reachability Analysis rather than reference counting. Starting from GC Roots—local variables on thread stacks, static fields, active JNI global references, and monitor locks—the collector traverses the reference graph. Any object unreachable from those roots becomes eligible for reclamation.
Scanning roots and moving objects safely requires a Stop-The-World (STW) pause where every application thread halts. HotSpot doesn’t interrupt threads at arbitrary bytecode instructions; it waits until each thread reaches a Safepoint—such as a method return or a loop back-edge—where the JIT compiler has recorded an accurate reference map (OopMap).
In production, I’ve often seen latency spikes blamed on GC when the actual culprit was Time-To-Safepoint (TTSP). If a single thread is stuck in a long int-indexed counted loop (which HotSpot omits Safepoint polls from by default) or blocked on a major page fault, every other thread sits idle waiting for that one straggler before GC can even begin. Checking safepoint logs alongside GC logs is the fastest way to tell whether you have a collection problem or a TTSP problem.
How G1GC splits the heap into Regions and runs Mixed GC
G1GC (Garbage-First) has been the default collector since Java 9. Instead of carving the heap into two rigid contiguous blocks, G1GC divides memory into equal-sized logical Regions (1 MB to 32 MB each) and assigns them dynamically as Eden, Survivor, Old, or Humongous.
Scanning the entire Old generation during a Young GC would defeat the point of generational collection. To avoid that, G1GC splits the heap into 512-byte slices tracked by a Card Table, and each Region maintains a Remembered Set (RSet) listing external cards that hold references into it. Whenever application code mutates a reference field, a JIT-inserted Write Barrier marks the corresponding card dirty. During Young GC, G1GC only scans the relevant RSets to find Old-to-Young references.
G1GC runs in three main phases:
- Young GC: Reclaims Eden and Survivor regions in a short STW pause and promotes surviving objects to Survivor or Old regions.
- Concurrent Mark: Once heap occupancy crosses the Initiating Heap Occupancy Percent (IHOP) threshold, background threads mark live objects concurrently with application threads and calculate how much garbage sits in each Old region.
- Mixed GC: Selects Old regions with the highest ratio of reclaimable garbage (“garbage first”) and evacuates them alongside Young regions.
The flag -XX:MaxGCPauseMillis (default 200 ms) is a soft target, not a hard ceiling. G1GC adjusts Young generation sizing and the number of Old regions per Mixed GC to meet that target, but sudden allocation bursts or heavy fragmentation can still push pauses past it.
How Java 21 Generational ZGC achieves sub-millisecond pauses
G1GC compacts and copies surviving objects during STW pauses, so pause times tend to grow as live data sets get larger. Original single-generation ZGC solved this by moving objects concurrently with application threads, keeping pauses under a millisecond. The catch was that it had to scan the entire heap every cycle, which drove up CPU and memory overhead in high-allocation services.
Generational ZGC, introduced in Java 21 via JEP 439 (-XX:+UseZGC -XX:+ZGenerational), brings separate Young and Old generations to ZGC (and became the default ZGC mode in Java 23 via JEP 474). Short-lived request objects get reclaimed cheaply in the Young generation, cutting both CPU overhead and required heap headroom compared to non-generational ZGC.
The mechanism behind ZGC’s sub-millisecond pauses combines Colored Pointers and Load Barriers. ZGC encodes marking and relocation metadata directly into unused high bits of 64-bit object references. Whenever application code loads a reference from the heap, a Load Barrier checks those metadata bits.
flowchart TD
A["GC phase transition (sub-ms STW)"] --> B["Concurrent marking and relocation set selection"]
B --> C["Application reads reference (Load Barrier)"]
C -->|"Good color"| D["Access object field immediately"]
C -->|"Needs relocation"| E["Self-heal pointer via forwarding table"]
If the thread reads a reference to an object that is mid-relocation, the Load Barrier looks up the forwarding table, finishes moving the object if needed, and updates the pointer in place (Self-Healing). Subsequent reads hit the fast path with zero extra work. Because marking, relocation, and pointer remapping all happen concurrently, STW pauses stay under 1 ms regardless of whether the heap is 4 GB or 256 GB.
Comparing G1GC vs. Generational ZGC and when not to use ZGC
| Dimension | G1GC (Default) | Generational ZGC (Java 21) |
|---|---|---|
| STW pause latency | Tens of ms to ~200 ms (MaxGCPauseMillis target) | Under 1 ms (independent of heap size) |
| Throughput | Higher (cheaper Write Barrier) | Slightly lower (concurrent Load/Store Barriers) |
| Memory and CPU overhead | Low to moderate (RSet footprint) | Higher (needs extra heap headroom and CPU cores) |
| Java 21 activation | Default (-XX:+UseG1GC) | -XX:+UseZGC -XX:+ZGenerational |
| Best-fit workloads | General APIs, batch jobs, small containers (<= 2 GB) | Strict p99/p999 SLA APIs, caches, large heaps (>= 4 GB) |
Don’t switch to Generational ZGC blindly. On small containers with 1–2 vCPUs and <= 2 GB of RAM, ZGC’s concurrent threads compete directly with application threads for CPU, and the smaller heap leaves little room for concurrent reclamation. In those environments, G1GC delivers better throughput and lower memory cost. Batch pipelines where total job completion time matters more than tail latency are also better off staying on G1GC (or even Parallel GC).
Generational ZGC pays off when you have at least 4 GB of heap, spare CPU cores, and strict p99 or p999 latency targets where a 150 ms Mixed GC pause violates your SLA.
Inspecting GC behavior and Safepoints locally
Before and after switching collectors, I always verify pause distribution, TTSP, and allocation rates using Unified GC Logging and jstat instead of guessing from APM graphs alone.
1
2
3
4
5
6
7
8
# 1. Enable Generational ZGC with Unified GC and Safepoint logging
java -Xms4g -Xmx4g \
-XX:+UseZGC -XX:+ZGenerational \
-Xlog:gc*,safepoint:stdout:time,uptime,level,tags \
-jar app.jar
# 2. Observe generation occupancy and GC counts every second on a running JVM
jstat -gcutil <pid> 1000
In the Unified log output, watch two lines closely: Safepoint entries showing reaching safepoint times (which expose TTSP spikes) and ZGC’s Allocation Stall counters.
Production pitfalls and tuning checklist
Warning: Humongous allocations in G1GC and insufficient heap headroom in ZGC trigger the two worst failure modes in production—Full GC and Allocation Stalls.
First, watch out for Humongous Objects in G1GC. Any single object larger than 50% of a Region size (such as a large byte[] buffer or a multi-megabyte JSON payload) bypasses Eden and allocates straight into contiguous Old regions called Humongous Regions. Frequent humongous allocations fragment the heap and can force a stop-the-world Full GC. Fix this by streaming large payloads instead of buffering them in memory, or by increasing -XX:G1HeapRegionSize so those objects fall below the 50% threshold.
Second, guard against Allocation Stalls in Generational ZGC. If your application allocates objects faster than ZGC’s concurrent threads can reclaim memory and the heap fills up, mutator threads block until space frees up. Running ZGC safely requires keeping 20–30% heap headroom and enough CPU quota so concurrent GC threads aren’t throttled by container CFS limits.
Before rolling a GC change to production, run through this checklist:
- Measure baseline p99 latency, TTSP, and allocation rate (MB/s) with
-Xlog:gc*,safepoint. - For G1GC, check GC logs for
Humongousallocations andTo-space exhaustedevents. - For Generational ZGC, provision at least 20–30% free heap headroom and verify
Allocation Stallcount stays at zero under peak load. - Keep
-Xmsequal to-Xmxin production containers to avoid heap resize pauses and unpredictable memory spikes.
Choosing between G1GC and Generational ZGC comes down to latency budgets and infrastructure headroom. Measure your allocation patterns and Safepoint pauses first, then pick the collector whose trade-offs match your workload.