Skip to content
G1 GC Deep Dive: Region Heap, Pause Prediction, Mixed GC & Production Tuning

G1 GC Deep Dive: Region Heap, Pause Prediction, Mixed GC & Production Tuning

This article provides a comprehensive analysis of the G1 garbage collector, covering its region-based heap organization, pause prediction model, CSet selection for Young and Mixed GC, humongous object handling, failure modes leading to Full GC, production tuning parameters for JDK17, log analysis techniques, and key source code insights.

Architecture Pony
Architecture Pony
Architecture Pony

Introduction

This article continues the GC series by diving into G1 (Garbage-First), the default collector since JDK 9 and the workhorse for most online services. The core design goal of G1 is to turn "how long this collection pauses" from a physical property into a tunable budget — something CMS could not achieve. G1 uses region-based heap partitioning to make pause time a configurable parameter. After reading, you should be able to answer three production questions: how G1 achieves predictable pauses, which parameters move which curves, and why large objects are G1's primary weakness. ZGC will later address the design revolution when the budget is pushed to sub-millisecond.

Three Production Incidents

Incident 1: Bulk Import Overwhelms Humongous Regions

A data migration task wrote thousands of 2 MB binary blocks per second. With a 2 MB region size, every block became a humongous object. Humongous regions fragmented, Mixed GC couldn't keep up, the old generation filled, and eventually to-space exhausted triggered a 12‑second Full GC. Large objects don't participate in copying and require contiguous space, making them the primary cause of G1 fragmentation.

Incident 2: 10 ms Pause Target Backfires

A service lowered MaxGCPauseMillis from 200 to 10 ms chasing ultra-low latency. GC frequency increased, throughput halved, and three days later to-space exhausted triggered Full GC. Too small a target forces G1 to collect only a few regions per cycle; collection speed falls behind allocation speed — an over‑aggressive soft target is slow suicide.

Incident 3: Migrating with CMS Parameters

A JDK 8 + CMS system upgraded to JDK 17 but kept the old startup flags (including CMS switches silently ignored by the JVM). Large‑object behavior changed completely: CMS allocated large objects into the old generation's free list, while G1 sends them straight to humongous regions. The promotion curve deformed entirely. Switching collectors requires a full parameter rewrite; copying parameters across collectors is as dangerous as copying conclusions across versions.

Technical Analysis: How Region‑Based Design Changes GC

1.1 Why G1 Exists: CMS's Three Fatal Flaws

Every G1 design decision targets a CMS wound:

Fragmentation: Mark‑sweep doesn't move objects; fragments only grow until promotion fails.

Uncontrolled remark pauses: Incremental update rescans black objects; remark pauses can reach seconds on large heaps with many live objects.

Single‑threaded Full GC fallback: The fallback compaction is Serial; an 8 GB heap pauses 8‑20 seconds.

The common root cause: using "generation" as the collection unit — actions are coarse and indivisible. A collection either takes the whole young generation or the whole old generation; granularity is too coarse, so pause duration is dictated by content, not by a parameter. G1's countermeasure: slice the heap into ~2000 equal‑sized regions. The collection unit changes from "generation" to "block"; how many blocks to collect is decided by the budget — pause turns from a physical property into a tunable parameter, which is G1's soul.

The name itself is the design doc: Garbage‑First — regions with the highest garbage ratio are collected first. Concurrent marking measures each old‑gen region's garbage percentage; CSet filling always starts from the highest‑ratio head — maximizing reclaimed space per unit time. This is the economics behind "predictable pauses": same pause budget, buy the most space release. It also shifts GC from "passive space reclamation" to "active resource scheduling" — garbage is a renewable resource; collecting it has cost and benefit; the scheduler (G1) maximizes benefit. Later chapters on ZGC's concurrent compaction and monitoring metrics continue this economic thinking.

1.2 Heap Organization: Regions, Dynamic Roles & RSet

G1 divides the heap into 1‑32 MB (power‑of‑two) equal regions, targeting ~2048 regions. Each region's role is dynamically assumed : this round it's Eden, next round after collection it can become Old — "generation" becomes a logical label on a region, not a physical partition. Objects larger than half a region are classified as humongous , occupying one or more contiguous regions directly, bypassing generational flow.

Region‑based design introduces cross‑region references: when an old‑gen region references a young‑gen region, a Young GC that only scans the young generation would miss that reference and leak live objects. G1's solution is the Remembered Set (RSet) : each region keeps a "who references me" index, so Young GC can follow the index without scanning the whole heap. RSet is built on a write barrier that marks dirty card pages (512 B), with refinement threads asynchronously summarizing them into the RSet (source code in section 3.4).

RSet is G1's "space tax": ~5‑10% of heap memory plus write‑barrier maintenance overhead. G1's startup cost is noticeably higher than Parallel GC — on heaps below 4 GB G1 may not pay off (JDK 8u docs explicitly note this). Humongous objects amplify RSet cost: every region referencing a humongous region adds an entry; more humongous objects and wider references make RSet fatter. Understanding that "region‑based flexibility is bought" explains why G1 can underperform Parallel on small heaps.

Region size selection follows a rule: default derivation is "heap size ÷ 2048 rounded up to a power of two". An 8 GB heap yields 4 MB; a 32 GB heap yields 16 MB — larger heaps get larger default regions, and the humongous threshold rises with it , which is why "large heap + large objects" tolerates large objects better than small heaps. Manual G1HeapRegionSize tuning has only two valid triggers: business large‑object size is known and far exceeds the default threshold (increase), or per‑region collection cost within a single pause is too high and you want finer CSet granularity (decrease). A practical anchor: after adjusting RegionSize, humongous threshold = half region; work backwards from the business's maximum object size — max object 2 MB → region at least 4 MB; max object 64 KB → 1 MB region suffices. Don't guess RegionSize; derive it from the large‑object distribution.

1.3 How Collection Runs: CSet & Evacuation

Every G1 collection is a copying evacuation : select a set of regions as the Collection Set (CSet) , copy live objects into empty regions, then reclaim the entire CSet. Two collection types:

Young GC — CSet = all young‑gen regions (Eden + Survivor), triggered when Eden regions are exhausted.

Mixed GC — CSet additionally includes a batch of "highest ROI" old‑gen regions (highest garbage ratio first), appears only after concurrent marking completes, runs multiple rounds to gradually drain the old generation.

G1 has no "Minor/Major GC" terminology — Young GC is routine, Mixed GC is cleanup, Full GC is failure ; the health signals for each are completely different.

Evacuation is the same copying algorithm from the previous chapter, just on a different stage: copying between young regions, between old regions, or even promoting young directly to old regions — copying is G1's only action, so G1 is forever fragmentation‑free (contrast CMS's mark‑sweep). Dead objects require no sweeping: the whole CSet is reclaimed, dead objects disappear with the region — copying cost depends only on live objects; dead objects are free. This also explains the difference from the dynamic age‑threshold logic in chapter 03: Survivor in G1 is a set of regions, not two fixed blocks; the ageTable logic remains but physically more flexible.

1.4 Pause Prediction Model: How Budget Becomes Region Count

How does MaxGCPauseMillis land? G1 has a built‑in prediction model:

Budget split — pause target minus fixed overhead (RSet processing, reference processing, queue cleanup) = copy budget.

Cost prediction — maintain historical duration sequences for copy, scan, etc.; use decayed average (recent samples weighted higher) to predict single‑region collection cost.

CSet filling — old‑gen regions sorted by garbage ratio; fill from the head until predicted time approaches the budget.

Therefore, with the same 200 ms target, a fuller heap or more live objects means fewer regions collected per round — collection becomes "trickle flow". The philosophy is worth stressing: MaxGCPauseMillis is a soft target; G1 tries its best but does not guarantee it — the budget can be breached when "copy can't keep up".

Concurrent marking triggers when old‑gen occupancy exceeds IHOP (InitiatingHeapOccupancyPercent, default 45%) of the whole heap — Initial Mark (piggybacks on a Young GC) → Concurrent Mark (SATB for correctness) → Remark (short STW) → Cleanup (statistics per‑region garbage ratio). Since JDK 9 IHOP supports adaptive mode ( G1UseAdaptiveIHOP, on by default); G1 dynamically adjusts the trigger threshold based on historical promotion rates — before manually tuning IHOP, clarify whether you're solving "marking too late" or "marking too frequent".

Adaptation isn't limited to IHOP; G1's adaptive family works as a group:

Young generation size — G1 dynamically adjusts young‑gen region count between G1NewSizePercent (default 5%) and G1MaxNewSizePercent (default 60%), aiming to meet pause target while sustaining promotion rhythm.

IHOP — dynamically adjusts trigger threshold based on historical promotion rate.

CSet filling — dynamically decides how many regions to collect per round based on predicted cost.

All three serve one goal: keep pauses hugging the budget. The cost is that you can almost never precisely predict the next GC's behavior — Eden region count varies every time; this is by design, not a bug. To put guardrails on adaptation, use the G1NewSizePercent / Max bounds (e.g., raise the lower bound for I/O‑heavy services to reduce GC frequency), rather than hard‑locking.

1.5 Humongous: G1's First Achilles' Heel

Large objects in G1 are treated completely differently from CMS (see diagram upper half): CMS allocates large objects via the old generation's free list; G1 sends objects exceeding half a region directly into contiguous regions — with a 2 MB region, a 1 MB object is already humongous. Three troubles follow:

Contiguous space requirement makes allocation fail more easily (fragmentation hotspot).

Humongous objects don't participate in copying (too large to move); reclamation can only judge the whole block dead and release it whole.

Regions referencing humongous objects must maintain RSet entries, amplifying bookkeeping cost.

Fortunately, the collector has eager reclaim : Young GC and Mixed GC both check humongous object references; unreferenced humongous regions are reclaimed whole immediately, without waiting for concurrent marking. Three‑pronged governance: business‑side rate‑limit large objects, increase G1HeapRegionSize to raise the humongous threshold, monitor humongous allocation rate.

1.6 Failure Modes: Step‑by‑Step to Full GC

G1's failure has a clear propagation chain (diagram lower half):

Allocation rate exceeds collection rate (pause target too tight, IHOP too late, large‑object flood) → free regions exhausted, evacuation finds no to‑space →

Evacuation Failure ( to-space exhausted ) — objects have nowhere to go, stay in place, current collection discounted →

Concurrent marking can't finish before old gen fills →

Full GC fallback .

Since JDK 10 G1's Full GC is parallelized (no longer CMS‑era Serial multi‑second stops), but it remains a second‑level event. Log keyword cheat sheet: to-space exhausted → increase G1ReservePercent (default 10%, emergency space reserve); Humongous regions steadily growing → large‑object governance; Pause Full appears → trace back which link in the trigger chain broke. to-space exhausted is a yellow warning: only one step away from Full GC.

Observation points for the failure chain: treat the chain as a movie . A healthy G1 shows a sawtooth old‑gen water level — Mixed rounds gradually lower it, allocation gradually raises it, cycle repeats. A sick G1's sawtooth climbs higher each cycle (each Mixed reclaims less), concurrent marking cycles trigger more frequently (IHOP interval shrinks), Young GC pauses grow longer (more live objects in CSet). All three curves worsening simultaneously means "collection systemically loses to allocation"; parameters can't fix it — must reduce allocation rate (rate‑limit, cache optimization, large‑object governance). Monitoring: plot these three curves on one dashboard; G1's health fits on one screen — far more effective than staring at single metrics.

1.7 Parameter System: A Map

Group G1 parameters by "which curve they move":

Pause curve — MaxGCPauseMillis (target), G1HeapRegionSize (per‑block cost).

Trigger timing — IHOP (concurrent marking start threshold).

Safety margins — G1ReservePercent (to‑space reserve),

G1MixedGCLiveRatioPercent</strong> (Mixed selection threshold).</li><li><strong>Young‑gen adaptation</strong> — <code>G1NewSizePercent

/ G1MaxNewSizePercent (adaptation bounds).

Two disciplines:

Never set Xmn / NewRatio — they lock young‑gen size, disabling G1's core adaptive capability (pause target becomes ineffective).

Xms must equal Xmx — runtime heap resizing interferes with the prediction model.

The parameter system's bedrock is RegionSize: it determines humongous threshold, per‑block collection cost, RSet granularity — before touching it, map your business's large‑object distribution.

Version perspective: G1 evolved while serving. Key milestones worth remembering — JDK 7u4 first available, JDK 9 default, JDK 10 Full GC parallelized (escaped Serial fallback), JDK 12 abortable Mixed GC + return memory to OS (container‑friendly), JDK 16 thread‑stack region experiment & humongous improvements, JDK 21 major region‑algorithm improvements (generational memory efficiency). So "G1 is slower than CMS" must be version‑qualified: JDK 8‑era G1 indeed lagged a well‑tuned CMS; JDK 17's G1 is a different machine — evaluate G1 by stating the version first; cross‑version collector comparison is a common accident source.

Production Practice: Two Configurations & One Failure Chain

2.1 Configuration 1: G1 Standard Production Parameters (8 GB Heap Online Service)

A complete JDK 17, 8‑core 16 GB container, 8 GB heap parameter set — most scenarios only need this "defaults + disciplines" baseline:

# ==== G1 Standard Production Parameters (JDK17, 8GB Heap)====
-Xms8g -Xmx8g
# Start=Max: avoid resize interfering with prediction model
-XX:+UseG1GC
# JDK9+ default on, explicit to prevent drift
-XX:MaxGCPauseMillis=200
# Pause soft target: default 200, online services don't go below 50
-XX:G1HeapRegionSize=4m
# Region 4M: humongous threshold 2M, set per large‑object distribution
-XX:InitiatingHeapOccupancyPercent=45
# Concurrent marking trigger threshold (initial value when adaptive on)
-XX:G1ReservePercent=10
# to‑space emergency reserve (default 10)
-XX:ParallelGCThreads=8
# STW parallel threads = CPU cores
-XX:ConcGCThreads=2
# Concurrent marking threads ~ cores/4
-XX:+ParallelRefProcEnabled
# Parallel reference processing (must enable when references many)
-XX:+DisableExplicitGC
# Block System.gc() (NIO‑heavy services caution, chapter 02 covered direct memory relying on GC)
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/dumps/oom.hprof
-Xlog:gc*,safepoint:file=/logs/gc.log:time,uptime:filecount=5,filesize=50m
# Collect GC + safepoint logs together: two evidences for pause attribution

2.2 Configuration 2: Large‑Object Governance Special Parameters

For "large‑object flood" scenes like Incident 1, the special combo is raise humongous threshold + relax Mixed to collect giants + business rate‑limit three‑pronged:

# ==== Large‑Object Governance Special (Incident 1 Scene)====
-XX:G1HeapRegionSize=8m
# Region 8M: humongous threshold raised to 4M, 2M blocks no longer judged humongous, return to normal generational copying
-XX:G1HeapWastePercent=5
# Continue Mixed only if reclaimable space > 5% (ROI threshold)
-XX:G1MixedGCLiveRatioPercent=85
# Only old‑gen regions with live ratio < 85% enter Mixed candidates
-XX:G1MixedGCCountTarget=8
# Mixed round cap 8: collect fewer per round, smoother
-XX:G1ReservePercent=15
# Large‑object flood scene: increase reserve to prevent exhausted
# Supporting disciplines:
# 1. Batch export/import use pagination + streaming, split single 2M block into 64K chunks (business side is root cure)
# 2. Observe humongous allocation rate (log line in 2.3), alert on flood

2.3 Reading G1 Logs: Three Event Types, Three Evidences

G1 log reading still asks three questions (what collected, before/after delta, pause duration), but must build separate ledgers per event type:

# ==== G1 Log Three Event Types (JDK17 Format Excerpt)====
# --- 1) Young GC: Routine Event ---
[gc] GC(32) Pause Young (Normal) (G1 Evacuation Pause) 3450M->512M(8192M) 18.4ms
# Pause 18.4ms < target 200ms: healthy
# Edens: 0->0(136): Eden region count change

# --- 2) Concurrent Mark Cycle Start ---
[gc] GC(35) Concurrent Mark Cycle
[gc] GC(35) Pause Initial Mark
# Piggyback Young GC, IHOP triggered
[gc] GC(35) Concurrent Mark 320.5ms
# Concurrent segment: no STW, watch for timeout

# --- 3) Mixed GC: Cleanup Event ---
[gc] GC(41) Pause Young (Mixed) (G1 Evacuation Pause) 2140M->780M
# Marked (Mixed): carried old‑gen regions

# --- Danger Signals (Act Immediately) ---
[gc] GC(52) Pause Young ... (to-space exhausted)
# Yellow alert: Evacuation failure
[gc] GC(53) Pause Full 1.2s
# Red event: Full GC fallback

# Humongous Observation Line (extra grep):
# Humongous regions: 12->0
# Zero after reclaim: healthy; sustained growth: flood

A daily gauge: Young GC P99 pause vs. target delta is G1's thermometer — long‑term below target means budget loose (can lower target to raise throughput); long‑term near or above target means budget tight (inspect live‑object size & large objects). Old‑gen water level after Mixed GC ends is the second thermometer: if water level doesn't drop after multiple Mixed rounds, concurrent marking cycle hasn't finished before next one starts — IHOP or allocation rate issue.

Beyond logs, heap dump is the second evidence for large‑object root cause: jmap -histo for instance counts & bytes, jmap -histo:live triggers Full GC before/after comparison (caution in production), or MAT analyzes dump sorted by object size — finding which framework produces those 2 MB byte[] beats any parameter. Incident 1 traced to MyBatis resultMap full load; switching to streaming query ( fetchSize) zeroed humongous allocations. Parameter governance always follows business governance: G1HeapRegionSize mitigates; SQL & framework usage cures.

2.4 Post‑Mortem: Three‑Step to-space exhausted Diagnosis

Common endpoint of Incident 1/2. Fixed three‑step diagnosis:

Step 1: Check trigger chain — scroll back in logs to the last normal Young GC before to-space exhausted, compare "allocated vs. reclaimed" between the two; the delta is the breach point: delta large in young gen (allocation flood), large in old gen (promotion too fast).

Step 2: Inspect humongous regions — grep Humongous lines for allocation rate; Incident 1 showed hundreds of humongous allocations per second, confirming large‑object flood.

Step 3: Prescribe — large‑object flood → 2.2 special config; promotion too fast → check Survivor & dynamic age (chapter 03 method applies); pause target too tight → raise MaxGCPauseMillis.

Parameter tweaks always rank after business governance: G1 can't save a flood, only delay it.

2.5 Four Common Pitfalls

Pitfall 1: MaxGCPauseMillis=10ms for ultra‑low latency. Budget too small → collects too few regions per round → collection can't catch allocation → to-space exhausted. Online services 100‑200 ms is the experience zone; below 50 ms only after confirming live‑object scale truly supports it.

Pitfall 2: Copy CMS parameters verbatim into G1 startup script. CMS switches silently ignored; SurvivorRatio, Xmn etc. still interfere with adaptation — switch collector = rewrite parameter table. Migration anti‑pattern: using MaxTenuringThreshold to control promotion, but G1's age threshold is also adaptively adjusted (JDK 11+ dynamically lowers it), and what really affects promotion is Survivor region count — correct promotion control watches promotion rate curve & Eden count changes.

Pitfall 3: Manually lock young generation. Xmn or NewRatio kills G1's adaptive pause control; young‑gen size left to G1.

Pitfall 4: Small heap also uses G1. Below 4 GB, RSet fixed overhead (5‑10%) + write‑barrier runtime cost occupy too high a proportion; region count too low reduces "split‑block collection" flexibility. PS (throughput) or even Serial simpler and more efficient — collector selection: calculate fixed cost first, then pick sides.

Core Source Code: Four Segments to Understand G1 Internals

3.1 Pause Prediction: Decayed Average

// OpenJDK 17 · g1Predictions.hpp (simplified)
// TruncatedSeq: truncated history sequence
double G1Predictions::predict(
TruncatedSeq* seq) const {
if (seq->num() == 0) return 0;
double mean = seq->avg();
// Std‑dev weighted: more jitter → more conservative
double sd = seq->sd() * confidence_factor;
return mean + sd;
}
// confidence_factor default 2.0: mean + two std‑dev — rather overestimate than miss
// Copy cost = live bytes / historical copy rate
// CSet fill: accumulate predicted values until approaching MaxGCPauseMillis copy budget

Note the prediction is "mean + 2×std‑dev", not the mean itself: the more jittery the pause data, the more conservative the prediction, the fewer regions collected per round. This explains a phenomenon: under same parameters, services with jittery GC curves see visibly smaller per‑round collection than stable services — the model automatically leaves a safety margin for uncertainty. To make the model more accurate, first stabilize the load.

3.2 CSet Filling: Old‑Gen Region Selection

// OpenJDK 17 · g1CollectionSetChooser (simplified)
// After concurrent marking stats each old‑gen region:
struct RegionData {
size_t live_bytes;   // live bytes
size_t garbage_bytes; // garbage bytes
};
// Sort: highest garbage ratio first
//   reclaim = garbage / (live + garbage)
// Mixed fill threshold:
if (live_ratio > G1MixedGCLiveRatioPercent)
continue;  // too many live objects, not worth moving
if (garbage < heap * G1HeapWastePercent)
stop;      // remaining garbage too little, stop
// Fill from sorted head until predicted cost approaches pause budget

Two threshold parameters meet here: G1MixedGCLiveRatioPercent governs "per‑block ROI" (too many live objects → not worth moving); G1HeapWastePercent governs "whole‑round stop" (remaining garbage not worth another Mixed). Mixed GC's essence is ROI‑based clearance: old‑gen regions with too low ROI stay in the heap — that's why some services see old‑gen water level not fully drop after Mixed.

3.3 Humongous Judgment & Allocation

// OpenJDK 17 · g1CollectedHeap (simplified)
HeapWord* G1CollectedHeap::allocate_new_
tum(array_length, purpose) {
size_t obj_size = object_size(array_length);
// Judgment: exceeds half region → humongous
if (obj_size >= humongous_threshold) {
// Find n contiguous free regions
//   first block holds object header, rest continue
return humongous_obj_allocate(obj_size);
}
// Normal object: TLAB pointer bump
return attempt_allocation(obj_size);
}
// humongous_threshold =
//   region_size / 2 - object header overhead
// Region 4M → threshold ~2M

This snippet explains why tuning RegionSize governs large objects: threshold rises linearly with region size; at 8 MB region, objects ≤4 MB return to normal generational copying. But the cost is also linear: larger region → higher per‑block collection cost, coarser pause granularity — RegionSize is the switch between "large‑object friendliness" and "pause granularity"; inspect large‑object distribution before moving it.

3.4 Cross‑Region References: Write Barrier & Refinement

// OpenJDK 17 · g1SATBCardTable (simplified)
// Post‑write barrier: mark dirty card after reference assignment
void G1SATBCardTable::post_barrier(
oop* field, oop new_val) {
CardValue card = card_for(field);
if (dirty(card)) return;  // already dirty, skip
_card_table[card] = dirty_value;
}
// Refinement threads (background) asynchronously digest dirty cards:
//   read dirty card → check if cross‑region reference
//   → update target region's RSet
//   → clear dirty mark
// Queue backlog = Refinement can't keep up =
//   GC‑time RSet incomplete, pauses lengthen

Dirty‑card backlog is a hidden G1 risk: when business reference writes are too fast (heavy cross‑region assignments) and refinement threads can't digest, GC logs show "Refinement backlog" signals; Young GC must digest dirty cards itself, pauses grow. This is the concrete shape of the "write‑barrier tax" in G1: every line of 3.4 is the second runtime cost beyond the 5‑10% memory overhead from 1.2 — understanding both taxes defines G1's applicability boundary.

Reuse chapter 03's safepoint method on G1: GC log + safepoint log must be collected together (2.1's log params already include), pause attribution still splits into "rendezvous" + "work". A G1‑specific rendezvous issue is NMT‑triggered safepoint ops and jcmd ( Thread.dump_to_file, GC.run etc.) hitting safepoints; troubleshoot by checking safepoint log operation type first. Monitoring dashboard recommendation: Young GC P99, Mixed GC P99, to-space exhausted count (weekly), Full GC count (weekly) — all G1 problems eventually land on one of these four curves.

Seven Accounts

Region Account: RegionSize is parameter bedrock — decides humongous threshold (half), per‑block collection cost, RSet granularity. Before moving it, map business large‑object distribution; increase for large‑object friendliness, decrease for pause granularity.

RSet Account: 5‑10% heap memory + write‑barrier runtime + refinement thread CPU — G1's flexibility is bought. Below 4 GB, calculate this account before choosing G1.

Pause Account: MaxGCPauseMillis is soft target, not hard guarantee. Too small → collects too little → can't catch allocation → exhausted → Full GC. Online services 100‑200 ms; below 50 ms only after confirming live‑object scale.

Large‑Object Account: Exceeds half region → humongous: contiguous space, no copy, RSet bookkeeping amplified. Governance triad: business rate‑limit, raise threshold, monitor allocation rate — business‑side cure always precedes parameter mitigation.

IHOP Account: Default 45% triggers concurrent marking; adaptive on → it's initial value. Before tuning IHOP, distinguish problem: marking too late (lower) vs. marking too frequent (raise or accept adaptive).

Failure Account: to-space exhausted is yellow warning, Full GC is red event. Fixed trigger chain: allocation > collection → to‑space exhausted → marking unfinished → fallback. G1ReservePercent is the last insurance pad.

Upgrade Account: CMS parameters copied into G1 script are silently ignored or disrupt adaptation. Switch collector = switch parameter system: Xmn / NewRatio disabled, SurvivorRatio ineffective, log format completely changed — rewrite startup script per G1 parameter table.

High‑Frequency Interview Questions (with Answers)

Q1: Essential difference between G1 and CMS? CMS uses generation‑level mark‑sweep; fragments only grow, remark pauses uncontrolled, Full GC single‑threaded. G1 slices heap into equal regions, collects by block via budget‑driven CSet with copying — no fragments, predictable pauses (soft target). Core difference: collection granularity from generation to block; pause from physical property to tunable parameter.

Q2: What is G1's Region? How are roles assigned? 1‑32 MB (power‑of‑two) equal memory blocks, target ~2048. Roles dynamically assumed: same region can be Eden/Survivor/Old at different times — generation is logical label, not physical partition. Objects > half region become Humongous, occupy contiguous regions.

Q3: What is RSet (Remembered Set)? Why needed? What's the cost? Each region records "who references me" as a point‑to index, letting Young GC discover cross‑gen references without full‑heap scan. Built on write barrier marking dirty 512 B cards + refinement threads asynchronously summarizing into RSet. Cost: ~5‑10% heap memory + write‑barrier CPU — reason G1 doesn't pay off on small heaps.

Q4: What is CSet? Difference between Young GC and Mixed GC CSet? Collection Set: regions to be evacuated this round. Young GC CSet = all young‑gen regions (Eden+Survivor), triggered when Eden exhausted. Mixed GC additionally carries old‑gen regions sorted by garbage ratio, runs multiple rounds after concurrent marking completes.

Q5: How does MaxGCPauseMillis affect collection? What if set too small? It's the soft pause target: budget = target − fixed overhead; budget ÷ per‑region predicted cost = regions collectable this round. Too small (e.g., 10 ms) → collects too few → allocation outruns collection → to-space exhausted → Full GC. Online services 100‑200 ms experience zone.

Q6: How does G1's pause prediction model work? Maintains historical duration sequences for copy, scan, etc.; prediction = mean + 2×std‑dev (more jitter → more conservative); CSet fills by accumulating predicted costs until budget approached. Hence jittery services automatically collect fewer regions per round — model leaves safety margin for uncertainty.

Q7: What is IHOP? Default? When to tune? InitiatingHeapOccupancyPercent: old‑gen occupancy reaches 45% of heap → start concurrent marking cycle. JDK 9+ adaptive on ( G1UseAdaptiveIHOP), manual value becomes initial. Marking too late → lower; marking too frequent hurts throughput → raise — clarify problem first.

Q8: What is Humongous object? Why G1's first weakness? Object > half region: directly occupies contiguous regions, doesn't copy (too large to move), referencing regions all maintain RSet. Three risks: contiguous allocation fails easily, fragmentation hotspot, bookkeeping cost amplified. Governance: business rate‑limit + increase G1HeapRegionSize to raise threshold + monitor humongous allocation rate.

Q9: What is eager reclaim? Young GC / Mixed GC actively check humongous references: unreferenced humongous regions reclaimed whole immediately, without waiting for concurrent marking. Allows short‑lived large objects (temp buffers) to be reclaimed promptly, easing humongous pile‑up.

Q10: What is to-space exhausted ? How to handle? Evacuation copy finds no target space (to‑space): live objects stranded in place, current collection discounted — yellow warning, one step from Full GC. Handling: check G1ReservePercent (default 10% reserve), check large‑object flood, check promotion rate, relax pause target to collect more per round.

Q11: When does G1 Full GC occur? Difference from CMS? Fallback when concurrent marking can't finish before old gen fills (end of evacuation‑failure chain). Difference: CMS Full GC = Serial single‑thread (8 GB pauses 8‑20 s); JDK 10+ G1 Full GC parallelized, but still second‑level failure event — healthy G1 shouldn't see Full GC.

Q12: Pros/cons of increasing G1HeapRegionSize? Pros: humongous threshold rises (half), more objects return to generational copying, large‑object friendly. Cons: per‑block collection cost up, pause granularity coarser, region count down. It's the switch between "large‑object friendliness" and "pause granularity" — inspect large‑object distribution first; default derives from 2048 blocks.

Q13: Why avoid Xmn / NewRatio under G1? They lock young‑gen size, disabling G1's core adaptive capability — G1 dynamically adjusts young‑gen region count to meet pause target; locking equals manual takeover of pause control. Similarly SurvivorRatio ineffective under G1.

Q14: G1 Young GC trigger condition? Difference from PS Minor GC? Trigger: Eden regions exhausted (not fixed ratio). Difference: G1 collects young‑gen region set each time, count decided by adaptation (constrained by pause target), copy target also dynamic free regions; PS collects whole Eden/Survivor at fixed ratio.

Q15: Five phases of concurrent marking cycle? Which are STW? Initial Mark (STW, piggybacks Young GC for roots) → Root Region Scan (concurrent) → Concurrent Mark (concurrent, SATB) → Remark (STW, short) → Cleanup (STW, short, stats garbage ratio, prepares CSet candidates). Long phases fully concurrent; STW segments all short.

Q16: What do G1MixedGCLiveRatioPercent and G1HeapWastePercent control? Former controls per‑block ROI: old‑gen regions with live ratio > it (default 85) excluded from Mixed candidates — too many live objects to move. Latter controls whole‑round stop: when reclaimable space < it (default 5%) stop Mixed — remaining garbage not worth another round. Together they decide old‑gen water level after Mixed ends.

Q17: Why not G1 below 4 GB? RSet space overhead (5‑10%) + write‑barrier runtime are fixed taxes; smaller heap → higher proportion; fewer regions reduces "split‑block collection" flexibility. Small heaps: PS (throughput) or even Simpler — collector selection: calculate fixed cost first.

Q18: Danger signals in G1 logs? to-space exhausted: evacuation failure, yellow warning; Pause Full: Full GC fallback, red event; Humongous regions sustained growth: large‑object flood; Refinement backlog / Young GC pause long‑term near target: budget tight. Healthy profile: only Young/Mixed, no Full, humongous stable, pauses below target.

Q19: Why enable ParallelRefProcEnabled? Reference objects (soft/weak/phantom/final) processed single‑threaded by default; reference‑heavy services (caches, heavy ThreadLocal) spend large chunk of Young GC pause in reference processing; parallelizing significantly compresses this fixed overhead — near‑zero‑cost parameter.

Q20: CMS → G1 migration checklist? ① Delete all CMS/ParNew params (ignored or disruptive); ② Ban Xmn / NewRatio / SurvivorRatio; ③ Xms=Xmx; ④ Set MaxGCPauseMillis (default 200 start); ⑤ Evaluate large‑object distribution for RegionSize; ⑥ Switch logs to -Xlog:gc*; ⑦ Observe one week Young pause / humongous / IHOP trigger frequency, then fine‑tune.

One‑Page Cheat Sheet

G1 in Nine Sentences: ① Heap split into regions, roles dynamically assumed, generation is label not partition; ② RSet records "who references me", 5‑10% space tax buys cross‑region index; ③ Collection fills CSet by budget, budget = target − fixed overhead; ④ Prediction uses decayed average, more jitter → more conservative; ⑤ Young GC routine, concurrent marking intel, Mixed cleanup; ⑥ IHOP 45% triggers marking, JDK 9+ adaptive; ⑦ Humongous = > half region, contiguous space no copy; ⑧ Exhausted = yellow, Full = red, Reserve = insurance; ⑨ Ban Xmn, Xms=Xmx, switch collector = rewrite parameter table.

Summary & Next Episode Preview

Reviewing the three incidents:

Incident 1: 2 MB binary blocks under 4 MB region all judged humongous → humongous fragmentation + Mixed can't catch up → to-space exhausted → 12 s Full GC — fix: raise RegionSize to 8 MB so 2 MB blocks return to generational copying, plus business sharding rate‑limit, humongous allocation rate zeroed.

Incident 2: 10 ms target forces G1 to collect only single‑digit regions per round, collection speed can't match allocation — revert to 200 ms, exhausted disappears, throughput recovers.

Incident 3: CMS params copied, silently ignored; promotion curve deformation root cause: RegionSize not reset per large‑object distribution — rewrite startup script per 2.5 migration checklist, curve restores.

G1's three event types each have distinct health signals; failure modes have clear chains — master log triage and G1 is no longer a black box.

Next episode 05 "ZGC & Shenandoah": when pause budget pushes to sub‑millisecond, region‑based + copying architecture isn't enough — how forwarding pointers, colored pointers, concurrent compaction, colored barriers make "move objects" fully concurrent; why ZGC once dropped generations then brought them back in JDK 21; and what heap scale justifies that technical tax. G1's pause target is "tunable"; ZGC's target is "heap‑independent" — next episode shows how that leap is achieved. G1's every overhead (RSet, write barrier, prediction model) serves "selective collection"; ZGC chooses the opposite — no selection, full‑heap concurrent compaction, using another bookkeeping scheme to push pauses to the floor.

Hands‑on homework: grep "Humongous regions" in your G1 service logs, compute humongous allocation rate & peak occupancy ratio; then check Young GC P99 vs. MaxGCPauseMillis delta — these two numbers decide whether you need to move G1HeapRegionSize , and are the first‑hand evidence for "whether to upgrade to ZGC" in the next episode.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JVMGarbage CollectionJDK17G1 GCPause PredictionProduction TuningMixed GCHumongous ObjectsGC Log AnalysisRegion-based Heap
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.