ZGC & Shenandoah: How Concurrent Compaction Delivers Sub-Millisecond GC Pauses
This article explains how ZGC and Shenandoah achieve fully concurrent compaction via colored pointers and load barriers versus forwarding pointers, details allocation stalls and generational ZGC (JDK21), quantifies throughput costs, provides a G1-to-ZGC migration guide with configurations, verification criteria, alerting rules, and includes source-code-level analysis and interview Q&A.
Introduction
Following the deep dive into G1, this article crosses G1's latency ceiling into the "concurrent compaction" camp: ZGC and Shenandoah. They answer the same question — can pause time be made independent of heap size? G1 made pauses predictable but still includes live-object copying in stop-the-world (STW); ZGC moves marking and relocation fully concurrent, leaving only root processing in STW, achieving sub-millisecond pauses whether the heap is 16 GB or 16 TB. After reading, you should be able to answer three production questions: what technologies support sub-millisecond pauses, where the throughput tax is paid, and which services should adopt ZGC.
Three Production Incidents
Incident 1: SLA Stuck on GC Pause
A cache aggregation service with 16 GB heap on G1 showed P99 pause of 38 ms while downstream circuit-breaker threshold was 10 ms. Two weeks of parameter tuning (MaxGCPauseMillis from 200 down to 30, live-set reduction) only brought P99 to 25 ms — still an order of magnitude away. Switching to ZGC dropped P99 pause to 0.4 ms, eliminating circuit-breaks within a week. Lesson: when latency targets exceed a collector's physical limit, tuning is a dead end; changing the tool is the only way out.
Incident 2: Allocation Stall Masquerading as "False Pause"
An order service on JDK 11 with ZGC (non-generational) had daily pauses of a few hundred microseconds, but during peak sales occasional 100 ms+ request spikes appeared with no corresponding long GC pauses in logs. Deep in GC logs the term "allocation stall" surfaced: allocation rate exceeded concurrent marking speed, heap exhausted before marking finished, forcing application threads to stop and wait for the cycle to complete. Classic ZGC's full-heap marking is its Achilles' heel under allocation spikes; JDK 21 generational ZGC was born to solve this.
Incident 3: CPU Explosion After ZGC Adoption
Deploying ZGC across a fleet of 4-core container services yielded beautiful pauses but average CPU usage rose 18%, exhausting headroom and triggering throttling. Post-mortem revealed concurrent GC threads consumed ~25% of cores, and read/write barriers added overhead on application threads. Small heaps in small containers simply cannot afford this tax. Sub-millisecond pauses are bought with throughput and CPU; you must run the numbers before switching — not every service can pay.
A pre-switch checklist — five questions, need at least three "yes": heap ≥ 8 GB? Latency SLA has a hard 10 ms target (not "lower is better")? CPU headroom ≥ 25%? Container memory limit recalculated for full heap? JDK ≥ 21 (generational)? If three are "no", your problem likely isn't what ZGC solves — go back and master G1 first.
Technical Analysis: Two Approaches to Concurrent Compaction
1.1 From G1 to ZGC: The Third Latency Tier
Three collector generations side by side: Parallel — "pause depends on luck" (proportional to heap and live set, seconds common); G1 — "pause is budgetable" (pause prediction model breaks target into CSet filling, typical pauses controllable, but evacuation remains STW — budget floor locked by "how many live objects to copy this round", 16 GB live set pins P99 at 20-50 ms, a physical limit); ZGC — "pause independent of heap" — moves the heaviest work (copying live objects) entirely out of STW, runs fully concurrent, STW only three root-processing phases each 100-200 µs. The essential difference across tiers is just one thing: whether the pause formula still contains a "heap size" variable.
Concurrent compaction must clear three hurdles. First, correctness : concurrent "compaction" is riskier than concurrent "marking" — while relocation runs, application threads may hold references to old copies; if updates land on dead copies, data is lost. Second, who relocates : GC threads copy concurrently, but application threads encountering old references must recognize and fix them, requiring every "read reference" to pass a barrier. Third, cost : barriers sit on the hot object-access path; where to store mark bits and forwarding info? How much memory bloat? ZGC and Shenandoah give two different answers: ZGC chooses colored pointers + load barrier; Shenandoah chooses forwarding pointers + read/write barriers.
A prerequisite often overlooked: this design only works on 64-bit JVM. ZGC's colored pointers "steal" high pointer bits for mark state; 32-bit pointers have no spare bits — hence ZGC never appears on 32-bit platforms, and its address-space ceiling is 4 TB (42 address bits): not because larger is technically impossible, but each extra borrowed bit halves usable address space. Pointer as metadata — the design's starting point.
Completing the "pause formula" view: Parallel pause ≈ full-heap live-object copy time; G1 pause ≈ CSet live-object copy time + model error — fewer variables but copy still dominates; ZGC pause ≈ root-set scan time — only variable left is "how many references in thread stacks", completely decoupled from heap. All three collectors are doing the same thing: eliminating terms from the pause formula one by one. Understand this thread and any "collector comparison" interview question can be derived from the formula rather than memorizing tables.
1.2 Colored Pointers: Storing GC State in the Pointer
Traditional GCs keep mark state in object headers (Mark Word mark bits); pointers are just addresses. ZGC flips it: state lives in the pointer, object header stays clean. 64-bit pointer uses low 42 bits for address (4 TB), bits 42/43/44 are M0, M1, Remapped view bits, bit 45 is Finalizable. At any moment a reference is in one of three views: Remapped = "view corrected, points to real object"; M0 = "accessed during current marking cycle"; M1 = "accessed during next marking cycle". With the bit layout (Figure 2), every pointer carries its own GC state.
How can three views "exist simultaneously"? Answer: multi-mapping . ZGC maps the same physical memory to three different virtual address ranges (base address, base+view bit each), so a pointer landing in a particular range indicates the object's state — reading any view yields the same physical data. This yields a stunning simplification: changing an object's state doesn't require touching the object, just "move the pointer to another view" or remap pages , and pointer fix-up can be amortized by the load barrier in application threads.
Multi-mapping sounds magical but implementation is plain: at startup the heap's virtual address range is mapped three times (once per view) to the same physical pages. Cost is 3x virtual address space — but virtual addresses are free (no physical pages allocated until touched), so 16 GB heap occupying 48 GB virtual space is a non-issue. This also explains a common puzzle: why ZGC process virtual memory (VSZ) often shows tens of GB while physical memory (RSS) is normal — mistaking VSZ alerts for memory leaks is the first ops lesson in the ZGC era.
Why two mark bits M0/M1 instead of one? To eliminate a full-heap mark-clearing scan . Classic schemes clear all object-header mark bits before each marking cycle — itself a full-heap scan. ZGC alternates M0/M1: current cycle uses M0, next uses M1, then back to M0 — if the bit matching current epoch is not set, it's recognized as stale state from previous cycle and fixed on the fly. Two rotating mark bits amortize "clear old marks" into subsequent cycles' read paths — another space-for-time trade-off.
1.3 Load Barrier: Whoever Loads a Reference Repairs the View
State in pointer is just the foundation; the real enabler of concurrency is the Load Barrier (Load Value Barrier, LVB) : every time an application thread loads a reference from a field, the JIT inserts a tiny check. Fast path does a single bit test — if Remapped bit is set, pass through immediately; 99% of accesses take this path, overhead 1-2 ns. Slow path handles the rest: if M0/M1 view, check whether it matches current epoch; if object already relocated, consult forwarding table for new address; finally write the "good pointer" back to the field and update remembered set — next access to same field hits fast path. "Self-healing" is the soul of this mechanism: every reference consumer participates in compaction, relocation completeness converges naturally with business traffic.
Contrast with write barriers in CMS/G1 (Section 03): CMS/G1 use write barriers to guard reference relationships (avoid missed marks) ; ZGC uses read barriers to guard view consistency (avoid using stale pointers) . Why not write barrier? Because concurrent compaction demands "when seeing an old reference, immediately get the new address" — only guaranteed at the moment of "read"; write barrier only records "reference relationship changed", cannot solve "the ticket in hand has expired". Compaction semantics dictate barrier placement.
Quantifying barrier cost: fast path is four instructions (fetch bit, mask, compare, branch), JIT inlines it at access site, single access 1-2 ns, hit rate >99% — that's why ZGC dares put barrier on read path. Real cost is slow path, which only spikes during active GC cycles: throughput tax isn't spread evenly year-round but concentrated in the active GC cycle window — explaining why average CPU rise (Incident 3's 18%) far exceeds steady-state measurements: capacity planning must use peak-window numbers, not averages.
1.4 Shenandoah: The Forwarding Pointer Path
Shenandoah solves the same problem with a completely different carrier: place an 8-byte "forwarding pointer" (Brooks Pointer) before every object header , all accesses go through it to reach the object body. Normally it points to itself; during relocation, after new copy lands, a single CAS flips the forwarding pointer to the new copy, and the old object's forwarding pointer is also updated — thereafter any thread holding old reference reaches the new home via the forwarding pointer. Barrier logic becomes trivial: just check the forwarding pointer, no bit twiddling; read barrier handles forwarding, write barrier handles SATB snapshot.
Side-by-side comparison lays out the trade-offs. ZGC colored pointers: zero object bloat (state in pointer, object gains zero bytes), but requires 64-bit + multi-mapping, barrier logic complex (view, epoch, forwarding table three things); Shenandoah forwarding pointers: every object fixed +8 bytes — small objects (e.g., 16-byte Integer) bloat 50%, and every access adds an extra pointer dereference, but barrier implementation simple, platform requirements low (no multi-mapping dependency). One-sentence mnemonic: ZGC pays its tax in "implementation complexity"; Shenandoah pays in "per-object memory" — both want application threads to help relocate, just different admission tickets.
In Chinese teams' real selections there's another factor: distribution. Shenandoah long only available in OpenJDK and RHEL-family distros (Oracle JDK doesn't ship it), while Chinese production environments mostly run OpenJDK or domestic distros — both accessible — but community resources, incident cases, tuning experience are far richer for ZGC; "being able to search an answer when things break" is itself productivity. Unless the team already has Shenandoah institutional knowledge, default to ZGC for new deployments — ecosystem depth is an often-underestimated weight in selection.
1.5 ZGC Cycle & Allocation Stall
Classic ZGC (production-ready from JDK 15) one full cycle (Figure 4): three STW points (Mark Start / Mark End / Relocate Start) each only process root set, ~100-200 µs each; concurrent marking, weak reference processing, relocation set selection, concurrent relocation all run alongside application threads. Pause composition contains zero "heap size" terms — the technical delivery of the sub-millisecond promise. Cycle ends, M0/M1 alternate, repeat.
But "full-heap marking" hides a trap: when allocation rate exceeds marking rate, heap exhausts before marking completes , application threads fail allocation and stall waiting for the cycle to finish — the allocation stall from Incident 2, appearing as a tiny line in GC logs but a 100 ms+ "false pause" on business side. Three mitigations: reduce allocation rate (back to cache/large-object governance), tune ZAllocationSpikeTolerance to trigger cycles earlier, and the fundamental fix — upgrade to JDK 21 generational ZGC . Generational version splits heap into Young/Old; Young runs independent small cycles (most objects die young, marking work plummets), Old runs low-frequency large cycles; official claim 2-3x throughput improvement, pauses remain sub-millisecond. Section 03's foreshadowing pays off here: non-generational wasn't because "generational hypothesis was wrong", but because concurrent compaction's remembered-set cost couldn't be justified at the time; JDK 21 balanced that ledger.
Generational ZGC also solves a classic ZGC ops pain: uncontrollable collection timing. Classic version only had "start cycle when heap nearly full" hard trigger; low-traffic periods could go long without collection, sawtooth memory curves hard to alert on; generational Young cycles naturally trigger frequently, memory curve smooth, alerting thresholds easier to define. Upgrade path as discipline: on JDK 17 evaluate ZGC can wait; after JDK 21 upgrade directly to generational ZGC — same code, JDK 21's G1 and generational ZGC both improve significantly over JDK 17, upgrade itself often yields more gain than switching collectors.
1.6 Throughput Tax: Where the Sub-Millisecond Money Comes From
ZGC isn't magic; it converts pauses into three runtime costs. First, barrier tax : load barrier on every reference-read hot path, write path maintains SATB snapshot and remembered set — official throughput concession 10-15%, allocation-heavy workloads higher. Second, memory tax : three-view mappings, forwarding tables, remembered sets total ~5-10% of heap, plus AlwaysPreTouch pre-faulting physical memory, container memory waterline generally higher than G1. Third, CPU tax : concurrent phases GC threads default to ~25% of cores (tunable via ConcGCThreads), CPU-intensive workloads must plan capacity as "one less core for business when GC runs". Run these three numbers before signing the "sub-millisecond" contract.
Tax paid, you get more than pause numbers. ZGC is insensitive to allocation-rate spikes (G1 forced into back-to-back Young GCs under allocation bursts), handles large-heap scaling gracefully (heap 16 GB → 64 GB, pause curve nearly flat), and no G1-style Humongous anxiety — large objects are just contiguous pages, migration strategy identical. Latency-sensitive + large heap + high allocation variance = ZGC's home turf; CPU-constrained, small heap, throughput-maximizing batch = its away game.
1.7 Version Availability & Selection Decision Tree
Version clarity: ZGC experimental in JDK 11, production in JDK 15, generational (ZGenerational) in JDK 21 (default-on from JDK 23); Shenandoah experimental in OpenJDK 12, production in JDK 15 (Oracle JDK long excluded, only OpenJDK/RHEL-family teams can use). Figure 5 gives decision tree: default G1; evaluate ZGC if latency P99 has hard 10 ms target or heap ≥ 16 GB; offline batch stays on Parallel; tiny containers (<256 MB) Serial is enough . Collector switch is a costly decision — parameter system, log format, ops experience all relearned; don't pay tuition for curiosity.
Frequent question: Does ZGC have Full GC? Yes, but nature completely different. G1 Full GC is a regular fallback path (evacuation failure triggers it); ZGC Full GC is last resort in extreme cases (concurrent relocation fails, e.g., severe memory pressure), single-threaded STW, once it appears it's a severe incident signal. Healthy ZGC logs should never show Full GC — appearance = alert, same stance as G1 but trigger probability lower. The more advanced the collector, the more sensitive you must be to "anomaly signals" because they're rarer and less familiar.
Production Practice: Migration, Configuration & Acceptance
2.1 Generational ZGC Full Production Config (JDK 21, 8 GB Heap)
An 8C16G container, 8 GB heap online service full parameter set — ZGC's parameter surface is much cleaner than G1, most scenarios "defaults + discipline":
# ==== ZGC Generational Production Params (JDK21+, 8G Heap) ====
-Xms8g -Xmx8g
# Initial=Max: capacity planned upfront, no resize variable
-XX:+UseZGC
-XX:+ZGenerational
# Generational switch: introduced JDK21, default-on JDK23+;
# explicit for audit and cross-version comparison
-XX:ConcGCThreads=2
# Concurrent GC threads: default ~25% of CPU; 8C container
# explicitly capped at 2 to leave cores for business
-XX:SoftMaxHeapSize=6g
# Soft limit: ZGC tries to keep usage within 6G, reserve 2G
# elasticity for allocation spikes (ZGC-specific waterline param)
-XX:ZAllocationSpikeTolerance=2.0
# Allocation spike tolerance: larger = later cycle trigger;
# lower when allocation stall appears (start marking earlier)
-XX:+AlwaysPreTouch
# Pre-touch entire heap at startup: avoid runtime first-touch
# jitter, strongly recommended for large-heap containers
-Xlog:gc*:file=/logs/zgc.log:time,uptime
:filecount=5,filesize=50m
# Unified logging: gc* level needed for stall & phase details
-XX:MaxDirectMemorySize=1g
# Off-heap limit still locked (Section 02 discipline unchanged)Three parameters deserve expansion. SoftMaxHeapSize is ZGC's unique elastic waterline: hard limit remains Xmx, but ZGC normally keeps usage under soft limit, using the delta as burst buffer — it turns "how much heap headroom" from ops convention into built-in collector strategy. ConcGCThreads in containers should be explicit: default 25% auto-calc gives 2 cores on 8C, but if business already near capacity redline, that default is Incident 3's hidden tax. ZAllocationSpikeTolerance is the allocation-spike "tolerance coefficient", default 2.0; lower when allocation stall occurs (earlier cycle start), raise when throughput insufficient — one of few params still needing per-workload tuning in generational ZGC era.
Comparing with G1's parameter table reveals philosophy difference: G1 has dozens of knobs (pause target, region size, concurrent marking phases layered), tuning like running experiments; ZGC makes most decisions adaptive (concurrent threads, cycle trigger, relocation pacing self-tuned), leaving ops only two questions: "how much resource" and "how much waterline" — good (clean config, hard to mis-tune) and bad (when things break, no "tune parameter" crutch, must confront via allocation-rate reduction and resource planning). Half of ZGC-era tuning lives outside JVM flags.
2.2 G1→ZGC Migration: Parameter Migration Checklist
Incident 3's lesson condensed into a migration checklist — switching collectors mandates switching parameter sets, this checklist should go straight into change templates:
# ==== G1 to ZGC: Parameter Migration Checklist ====
# 1. DELETE (ineffective or harmful under ZGC)
# -XX:+UseG1GC
# -XX:MaxGCPauseMillis=200
# (concept gone, leaving it misleads log readers)
# -XX:G1HeapRegionSize=4m
# -XX:InitiatingHeapOccupancyPercent=45
# -Xmn / -XX:NewRatio
# (ZGC generational manages itself, manual young-gen lock forbidden)
# -XX:MaxTenuringThreshold / SurvivorRatio
# 2. RETAIN (collector-agnostic)
# -Xms / -Xmx / off-heap limits / GC log path
# 3. ADD (see 2.1 full config)
-XX:+UseZGC -XX:+ZGenerational
-XX:SoftMaxHeapSize=<75% of heap>
-XX:ConcGCThreads=<container cores / 4, max 2>
# Shenandoah side (OpenJDK 17+) reference:
-XX:+UseShenandoahGC
-XX:ShenandoahGuaranteedGCInterval=300000
# 5-min guaranteed cycle: prevents long-term no-collection under low allocationBiggest pitfall: Xmn / NewRatio — G1 era already warned manual young-gen sizing breaks adaptivity; under ZGC these params are rejected or cause startup failure. Next: MaxGCPauseMillis — harmless but harmful to communication: on-call engineers seeing it think pause target still active, but ZGC has no such concept. Shenandoah's GuaranteedGCInterval is a thoughtful design: long-idle low-allocation services might never trigger a cycle; guaranteed interval covers the "never collect" edge case.
Migration also has an easily missed domain: GC-behavior-dependent auxiliary logic . Monitoring panels with jstat-format scripts, custom code that circuit-breaks on "Young/Full GC counts", benchmark docs citing G1 metrics — these scattered "GC-aware" pieces must switch dialects, otherwise first week post-launch brings not failure alerts but metric gaps and false positives. Add "grep old metric keywords" as final item on migration checklist.
2.3 Migration Acceptance: What to Watch, How to Judge
Post-switch acceptance fixed on four metrics. 1) Pause distribution : logs show only three Pause types (Mark Start / Mark End / Relocate Start), each should be <1 ms, P99 trended weekly — ZGC pauses should have no long tail; long tail = anomaly. 2) Allocation stall : grep log keyword, single occurrence demands action (reduce allocation rate or tune SpikeTolerance), consecutive occurrences mean Young cycles still not keeping up. 3) Throughput comparison : same-traffic load test G1 vs ZGC, compare TPS and CPU average — throughput drop >15% means concurrent threads or barrier cost biting you, back to capacity planning. 4) Memory waterline : AlwaysPreTouch makes startup occupy full Xmx physical memory; container memory limit must be recalculated as full heap + off-heap + metaspace, not G1-era experience values.
Minimum load-test standard: Latency criterion is both P99 GC pause and interface P99 must improve — pause pretty but interface P99 worse means throughput tax ate the gains; Resource criterion is same traffic CPU average rise ≤15%, memory peak ≤85% container limit. Any criterion missed → tune first, then retrospective; if still failing, roll back to G1 — collectors have no faith, only ledgers.
Rollback plan — every collector switch must have an exit: archive original G1 parameter file, make startup script dual-profile, rollback = rename file + one rolling restart . Rollback triggers pre-defined: interface P99 degradation >5%, CPU average breaches limit, or any stall storm — any one triggers immediate rollback, restore business first, investigate later. Switch success defined not as "it runs" but "observed one week anomaly-free + rollback plan never activated".
2.4 Alerting Dialects & Patrol
ZGC-era alerting must be rewritten; carrying over G1 dialects causes culture shock. Five references: ① Any Pause >1 ms alerts (healthy few hundred µs, >1 ms means something); ② Allocation stall occurrence alerts — closest signal to "Full GC precursor" in ZGC era; ③ Concurrent cycle duration P99 >30 s alerts (marking falling behind allocation precursor); ④ Heap usage consistently above soft limit alerts — elastic waterline breached means burst became norm; ⑤ CPU average week-over-week rise >10% correlated with GC logs — concurrent threads stealing cores is gradual. Patrol: weekly 10 min reviewing stall counts and cycle duration trends, even simpler than G1 patrol — provided dialects are upgraded to ZGC first.
Old-vs-new dialect cheat sheet for on-call: "Young GC frequency" → "Young cycle duration & interval"; "Full GC appears = alert" retained but meaning upgraded (more severe); "Old-gen waterline" → "Heap usage vs soft limit"; "Mixed GC backlog" deleted (ZGC has no Mixed concept); new additions: "stall count", "concurrent cycle duration P99", "CPU attribution" three lines. Dialect migration isn't regex replacement; it's upgrading the entire on-call mental model — upgrade people first, then systems.
Core Source Code: Four Truths of Concurrent Compaction
3.1 Colored Pointer Bit Definitions
zGlobals defines pointer bit layout — 42 address bits, four state bits, matching Figure 2:
// zGlobals.hpp: Colored pointer bit definitions (64-bit)
const uintptr_t ZADDRESS_BITS = 42;
// Address bits: 4 TB virtual address space
const uintptr_t ZMARKED0 = 1ULL << 42;
const uintptr_t ZMARKED1 = 1ULL << 43;
// Two mark view bits, alternated by epoch
const uintptr_t ZREMAPPED = 1ULL << 44;
// "View corrected" bit, mark of good pointer
const uintptr_t ZFINALIZABLE = 1ULL << 45;
// Finalizable objects marked separately
// Three view addresses = base | corresponding bit;
// Same physical page multi-mapped to three views simultaneously,
// Pointer lands in which view = object in which state3.2 Load Barrier Fast/Slow Paths
Load barrier is the heart of ZGC concurrent correctness — fast path single bit test, slow path completes mark counting, relocation query, self-healing write-back (simplified):
// Load barrier (zBarrier, simplified)
oop load_barrier(oop o) {
if (o == nullptr) return o;
uintptr_t addr = to_address(o);
if (is_good_or_null(addr)) {
return o; // Fast path: Remapped view
}
if (is_marked(addr)) {
inc_live(addr); // Slow path 1: concurrent marking
}
uintptr_t good = remap_object(addr);
// Check mark bit or forwarding table, get "good view" address;
// Relocated object returns new copy address (self-heal)
return from_address(good);
}
// Caller writes return value back to field: next same-field access fast pathTwo engineering details. First, inc_live runs in application thread — live byte count is "incidentally" accumulated, ZGC doesn't need extra live-object traversal to estimate relocation set benefit. Second, self-heal writes back to the field itself, not a local variable — hot field self-heals once, subsequent accesses all fast path. These two details jointly guarantee "slow path is rare and one-off", keeping barrier tax within 10-15%.
3.3 Shenandoah Forwarding Pointer Access
Shenandoah correctness relies on forwarding pointer + read/write barriers — read barrier ensures "old reference forwards to new copy", write barrier handles SATB snapshot (simplified):
// Shenandoah read barrier (simplified)
oop load_reference(oop* p) {
oop o = *p;
if (o != NULL && in_collection_set(o)) {
oop fwd = get_forwardee(o);
if (fwd != o) {
cas_set_oop(p, fwd); // Atomic redirect
// Old reference self-heal: write back new address
}
return fwd;
}
return o;
}
// Forwarding pointer 8 bytes before object header:
// Normally points to self; relocation CAS flips to new copy3.4 Allocation Stall & Generational Trigger
Allocation stall source face and generational ZGC response (simplified):
// Classic ZGC: allocation failure stalls business thread (illustrative)
if (!mark_completed() && need > free()) {
stall(); // allocation stall: wait for this cycle
// Cycle completes — "marking can't catch up with allocation"
// Direct cost
}
// Generational ZGC: Young gen small cycle independent trigger
bool should_start_young_gc() {
// Young gen occupancy hits threshold → start small cycle:
// Only mark Young, don't touch Old — marking work plummets,
// Cycle shorter & more frequent, stall probability drops sharply
return young_used >= young_threshold;
}
// Old objects promoted to Old's large cycle, low-frequency full-heap markSeven Accounts: Full Cost of Migrating G1→ZGC
Latency Account: P99 pause 38 ms → 0.4 ms, interface P99 from circuit-breaker edge back to safe zone — primary migration benefit, only account directly convertible to SLA attainment rate.
Throughput Account: Same-traffic TPS down 10-15%, allocation-heavy higher; translates to capacity as "same-cost machines carry 10% less traffic", peak-sale expansion budget must float accordingly.
CPU Account: Concurrent GC threads + barrier overhead total ~20-25% cores; 4-core small containers hurt most (lose one core), 16+ cores relatively painless — small containers must count cores before migrating.
Memory Account: View mappings, forwarding tables, remembered sets ~5-10% of heap; AlwaysPreTouch makes startup occupy full physical memory — container limit recalculated at full heap.
Ops Account: Log format, alerting dialects, patrol checklist all rewritten (Section 2.4 five rules); on-call must relearn "Pause only three types, stall is #1 signal" new worldview.
Risk Account: Heap <8 GB benefit doubtful (G1 sufficient), 32-bit and old JDK (<15) directly unusable; Shenandoah requires OpenJDK-family distro.
Opportunity Account: Saved not pause numbers but the downstream circuit-breaker thresholds, retry storms, and capacity redundancy they enable — on latency-sensitive chains this benefit outweighs throughput tax by an order of magnitude.
High-Frequency Interview Questions (with Answers)
20 Q&A covering: why ZGC pauses heap-independent, colored pointer bit layout, 64-bit requirement, load barrier fast/slow path, self-healing, M0/M1 alternation, Shenandoah forwarding pointer mechanics, Brooks pointer cost, one-sentence ZGC vs Shenandoah difference, allocation stall causes and avoidance, classic ZGC non-generational rationale and generational changes, ZGC three-color marking missed-mark solution, ZGC Full GC nature, throughput tax breakdown, suitable/unsuitable workloads, G1→ZGC parameter deletions, SoftMaxHeapSize purpose, Xmn/NewRatio effectiveness, AlwaysPreTouch rationale, JDK 21 collector selection flow.
One-Page Cheat Sheet
ZGC in Nine Sentences: ① Pause heap-independent: STW only three root-processings, each few hundred µs; ② Colored pointers: 42-bit address + M0/M1/Remapped view bits, pointer is metadata; ③ Multi-mapping: same physical page three views, state = address; ④ Read barrier self-heal: whoever loads reference repairs, relocation completeness converges with traffic; ⑤ M0/M1 rotation: eliminates per-cycle full-heap mark clear, clearing amortized into read path; ⑥ Shenandoah changes ticket: forwarding pointer 8 bytes/object, simpler barriers; ⑦ Allocation stall: marking can't catch allocation — false pause, stall appears = act; ⑧ Generational ZGC (JDK21): Young independent small cycles, throughput doubles, pauses unchanged; ⑨ Throughput tax three parts: barrier 10-15%, memory 5-10%, CPU default 25% cores — run the numbers before signing.
Summary & Next Episode Preview
Revisiting the three opening incidents: cache service SLA stuck on pause — answer is switch to ZGC not keep tuning G1; order service allocation stall during peak — answer is JDK 21 generational not bigger heap; 4-core container CPU explosion — answer is run the seven accounts not follow the herd. All technical substance of ZGC and Shenandoah compresses to one sentence: let application threads participate in compaction at the moment they load a reference — colored pointers and forwarding pointers are just two admission tickets for "letting threads see relocation".
Collector journey completes mainline: Parallel's throughput era, G1's budget era, ZGC's sub-millisecond era — three generations of design trade-offs laid bare. Next article "Memory Allocation & Escape Analysis" returns to an earlier stage than collectors — how objects are born: TLAB allocation, stack allocation, scalar replacement, how escape state decides an object "never needs GC". The best collection is keeping it out of the heap; next episode watches this zero-cost path's implementation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
