JVM GC Deep Dive: Reachability, Tri-Color Marking, Generational Algorithms & STW Mechanics
This article explains JVM garbage collection fundamentals including reachability analysis, tri-color marking, three basic algorithms, stop-the-world mechanics, generational hypothesis, Minor GC flow, promotion paths, collector families from CMS to ZGC, production tuning parameters, log analysis, and HotSpot source code insights for troubleshooting.
The article opens by framing GC as the only JVM subsystem that actively interrupts business: misconfigured memory is a chronic illness, but misconfigured GC is sudden death. It establishes five foundational questions — how garbage is identified, how marking works, how collection executes, why Stop-The-World (STW) exists, and what generational division actually means — noting that G1 and ZGC are built entirely on these answers.
Three Production Incidents
Incident 1 — Static cache pins objects to GC Roots: A service used a static Map as a local cache without eviction. Because static variables are GC Roots, every cached object remained permanently reachable. Old generation grew ~40 MB/day, triggering a 15-second Full GC monthly. Root cause: the leak is not a GC failure but a misuse of root references; fix by adding capacity limits and TTL-based eviction.
Incident 2 — CMS promotion failed cascade: A JDK 8 + CMS system under load hit promotion failed → concurrent mode failure, with single Full GC pauses of 8 seconds causing upstream timeouts. Root cause: CMS uses mark-sweep (no compaction), so fragmentation only increases. When promoted objects couldn't find contiguous space, a Full GC was forced to compact. Parameters can only delay, not eliminate, this architectural flaw; ultimate fix is migrating to G1.
Incident 3 — Undersized Survivor triggers promotion storm: A service squeezed young generation to 512 MB to "save memory." After each Minor GC, Survivor filled immediately, causing dynamic age calculation to promote batches of 2-3 year-old "fake long-lived" objects. Old generation growth spiked, turning weekly Full GCs into hourly ones. Lesson: dynamic age calculation is Survivor's pressure valve; too small a Survivor opens the valve too often, forcing old generation to pay young generation's debt.
Technical Analysis: Garbage Determination, Marking & Collection
1.1 Garbage Determination: From "Who References Me" to "Who Can Reach Me"
Two approaches exist: Reference Counting (simple, immediate, but fails on cycles — A↔B keeps counts non-zero) and Reachability Analysis (JVM's choice). Starting from GC Roots , the collector traverses downward; reachable objects live, unreachable die. Cycles are naturally collected because mutually referencing orphans are unreachable from roots.
GC Roots checklist (must memorize): local variables in active stack frames, static variables, constant pool references, JNI local references, active Thread objects, and objects held by synchronized locks. Incident 1 is now precisely stated: the static Map is a root, so its entries are always reachable regardless of business usage.
Two engineering perspectives on root enumeration:
Root enumeration is part of the pause: scanning all thread stacks and class static fields. More threads/classes = longer pauses. OopMap optimizes stack scanning to a table lookup; static fields use metadata layout.
Cross-generational references are solved by Remembered Sets (card tables). Old-to-young references would force scanning the entire old generation during Minor GC, violating the generational premise. The JVM divides old generation into 512-byte cards; a card is marked dirty when it references a young object. Minor GC then scans only dirty cards. Generational collection isn't free: it trades old-gen scanning cost for write-barrier and remembered-set maintenance.
1.2 Four Reference Types: Knobs for Liveness
Reachability is binary, but business needs are graded. Java provides four strengths:
Strong — ordinary assignment; OOM before collection.
SoftReference — collected only under memory pressure; natural for caches (controlled by SoftRefLRUPolicyMSPerMB, default 1 second per free MB).
WeakReference — guaranteed collection at next GC; used for ThreadLocal keys (hence remove() is mandatory: key collected → value becomes unreachable but retained in map).
PhantomReference — doesn't affect liveness; used for post-collection notification (e.g., DirectByteBuffer cleaner).
All can enqueue via ReferenceQueue for callbacks. Reference strength is a knob on reachability: caches → soft, metadata maps → weak, resource cleanup → phantom.
Pitfalls: SoftReference caches hand lifetime to GC — many soft refs prolong GC, hit rate fluctuates with pressure; prefer Caffeine/Guava. WeakReference means "next GC" not "immediate". ThreadLocal in thread pools is a hazard: thread reuse leaks previous request's value (classic user-context bleed); use TransmittableThreadLocal instead. References supplement GC semantics, they don't replace manual lifecycle management.
1.3 Tri-Color Marking: Concurrent Marking's Mathematical Model
If marking paused all threads, implementation is trivial but pauses are huge. Modern collectors run marking concurrently with mutators, leading to the tri-color abstraction:
White — unvisited, candidate garbage.
Gray — self marked, fields not fully scanned.
Black — self and all fields scanned, safe.
Collector processes gray set: turn gray→black, shade referenced white→gray, until gray set empties; remaining white is garbage. Concurrent mutator updates can cause missed marking if two conditions hold simultaneously: a black object adds a reference to a white object, AND all gray→white paths to that white object are deleted. The white object becomes unreachable from roots but is live — collected erroneously, worse than a pause.
Fixes break one condition:
Incremental Update (CMS) — watches new references: when black→white occurs, record it; during remark, re-scan those references. Semantics: "reachable at marking end = live."
SATB — Snapshot-At-The-Beginning (G1) — watches deleted references: when a gray→white reference is overwritten, snapshot the white object. Semantics: "reachable at marking start = live." Remark is shorter, but objects dying after snapshot become floating garbage this cycle.
Both rely on write barriers : JVM inserts hook code around every reference store, logging events to a queue. Concurrent correctness is bought with a small per-write runtime cost.
1.4 Where Stop-The-World Comes From
GC needs a consistent object reference graph — references must not change during analysis (write barriers fix errors but can't afford "graph changing while traversing" cost explosion). Most phases are now concurrent; true pauses come from a few non-concurrent critical paths:
Root enumeration — requires consistent snapshot, implemented via safepoints.
Copy/compaction reference updates — objects move, all pointers must be rewritten; concurrent rewrite would corrupt.
Remark — processes concurrent marking leftovers.
Safepoints are the STW mechanism: mutator threads poll a memory page at specific locations (method calls, loop back-edges, throws). GC sets page to "request stop"; threads see it and park. A real production trap: counting loops (e.g., for(int i=0;i<N;i++) ) may iterate tens of thousands of times without hitting a safepoint . GC waits for that thread — log shows 5 ms GC work but monitoring shows 500 ms pause; the delta is "waiting for threads to arrive." Diagnose with -XX:+UseCountedLoopSafepoints and -Xlog:safepoint. OopMap makes root enumeration O(reference count) not O(stack depth) by recording exact reference locations per frame at compile time.
STW isn't GC laziness; it's the minimal non-concurrent set under consistency constraints. Collector evolution is the history of moving pieces of this set into concurrency.
Monitoring perspective: JVM pauses aren't only GC. All safepoint operations require all threads to arrive — biased-lock revocation, jstack / jcmd dumps, deoptimization. If GC logs are clean but service jitters, suspect safepoint synchronization. Two-step diagnosis: enable -Xlog:safepoint to see sync-time distribution; capture thread dump at jitter moment to find threads stuck outside safepoints. Half of "GC looks fine but service shakes" cases end in safepoint logs.
1.5 Generational Hypothesis & Minor GC Full Flow
Generational motivation is an empirical rule: vast majority of objects die young — request objects, temporary collections, intermediate results rarely survive a request; few objects (caches, singletons, pools) that survive youth tend to live long. Partition by survival rate: young gen uses mark-copy (cheap frequent collection); old gen uses mark-sweep/compact (infrequent).
Minor GC flow (5 steps): Eden fills → all threads to safepoint → root scan → live objects from Eden + From copied to To with age+1 → objects meeting promotion criteria move to Old → Eden/From cleared, From↔To swap roles.
Three promotion paths:
Age reaches MaxTenuringThreshold (default 15, 4-bit hard cap).
Dynamic age calculation — when same-age objects' total size exceeds Survivor target (default 50%), the whole age group promotes early.
Large objects go directly to old (or humongous region in G1).
Incident 3 mechanism is path 2: Survivor only tens of MB, normal traffic overflows every GC, dynamic calculation promotes 2-3 year olds in batches. Diagnose promotion issues: check Survivor capacity first, then talk about the rest.
Generational is logical or physical depending on collector. G1 has no contiguous Eden/Survivor; Regions dynamically play generational roles. Classic ZGC abandoned generations (JDK 21 added generational ZGC) because concurrent compaction made cross-generational remembered-set costs high — generational benefit must outweigh maintenance cost. JDK 21 generational ZGC delivered 2-3× throughput, re-proving generational hypothesis's universal value. Generational is a repeatedly validated organizational principle, not an implementation detail of one collector.
1.6 Three Fundamental Algorithms: Functions of Survival Rate
All collectors reduce to three algorithms:
Mark-Sweep — simplest, two passes, no object move, leaves fragmentation — CMS old gen, Incident 2's fragmentation is its destiny.
Mark-Copy — split space in two, copy live objects, clear source region wholesale. No fragmentation, allocation via pointer bump (fast), but sacrifices space and explodes when live ratio is high — naturally fits low-survival young gen.
Mark-Compact — slide live objects to one end, no fragmentation, no space sacrifice, but moving objects rewrites massive references → longest pauses — suits old gen and Full GC fallback.
Algorithm choice is a function of survival rate; generational simply separates objects by survival rate and assigns each the cheapest algorithm.
Algorithms also dictate allocation strategy — often overlooked: copy/compact leave contiguous memory → pointer bump (single instruction); mark-sweep leaves holes → free-list allocation (search, merge, may fail). Fragmentation wastes space AND slows every allocation. Eden's TLAB allocation is near-free because copy algorithm maintains contiguity. CMS's fragmentation is a double tax: promotion fails (no contiguous space) AND daily allocation slows. This drove G1's region-based + copy-style design: keep allocation on pointer bump forever.
1.7 Collector Families: One Main Evolutionary Line
Collector evolution has a single mainline: shorten pauses .
Gen 1: Serial/Parallel — throughput focus, full STW, shortest total GC time, batch workloads.
Gen 2: CMS — pioneered concurrent collection, old gen mark-sweep mostly concurrent, but fragmentation & remark pauses are fatal flaws; deprecated JDK 9, removed JDK 14.
Gen 3: G1 — heap divided into Regions, "predictable pause targets", default from JDK 9.
ZGC/Shenandoah — compaction also concurrent, sub-millisecond pauses independent of heap size.
JDK 17 available set: Serial, Parallel, G1 (default), ZGC, Shenandoah — CMS is history; legacy systems' endgame is migrate to G1 or upgrade JDK. Selection mnemonic: batch → throughput (Parallel), online → balanced (G1), huge heap + extreme latency → ZGC.
Shenandoah vs ZGC: both sub-ms, heap-size-independent. Shenandoah (Red Hat) uses forwarding pointers (extra pointer outside object header); ZGC uses colored pointers, added generational in JDK 21. Both trade throughput and extra memory (forwarding pointers, colored pointers + remembered sets). Recommended priority: start with G1, only evaluate ZGC when G1 pauses are proven bottlenecks (huge heap or tens of ms) — collector switch is a costly decision, not a trial.
Two confusing concepts clarified:
Old family is combinatorial : young and old collectors paired independently — ParNew+CMS (classic), Parallel Scavenge+Parallel Old (throughput), but PS+CMS incompatible (interface mismatch, historical baggage, interview favorite). G1/ZGC are whole-heap : one collector manages entire heap, no combination concept.
"Major GC" is ambiguous — some call it old-gen collection, some conflate with Full GC. In production say "Old collection" and "Full GC" to avoid ambiguity. Parameters must align with collector version: JDK 8 -XX:+PrintGCDetails → JDK 17 unified logging -Xlog:gc*. Old parameter lists applied blindly cause no-op or startup failure — version alignment is GC parameter discipline #1.
Production Practice: Two Config Sets & One Log-Reading Method
2.1 Config 1: Parallel Throughput Full Params (Batch Jobs)
Offline compute, report batches — fear total time, not pauses . Parallel is cost king: same CPU budget, minimal total GC overhead. Example 8C16G container, 8G heap:
# ==== Throughput-first: Batch Service (JDK17) ====
-Xms8g -Xmx8g
# Full heap pre-allocated, avoid runtime resize jitter
-XX:+UseParallelGC
# Young PS + Old Parallel Old
-XX:NewRatio=2
# Old:Young = 2:1, Young ~2.7G
-XX:SurvivorRatio=8
# Eden:S0:S1 = 8:1:1
-XX:MaxTenuringThreshold=15
# Batch objects die young, default 15 fine
-XX:ParallelGCThreads=8
# GC threads = CPU cores, don't overcommit in container
-XX:GCTimeRatio=99
# Throughput target: GC time 1%
-XX:MaxGCPauseMillis=200
# Pause soft target, throughput can relax
-XX:+UseAdaptiveSizePolicy
# PS auto-adjusts generation sizes (default on, less manual tuning)
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/dumps/oom.hprof
# OOM auto-dump, first scene for postmortem
-Xlog:gc*:file=/logs/gc.log:time,uptime:filecount=5,filesize=50m
# JDK9+ unified logging: rotate 5 files of 50M2.2 Config 2: CMS Triage Params (JDK 8 Emergency)
Incident 2 style — can't migrate JDK. Triage three steps: start concurrent collection earlier (before old gen fills), force periodic compaction to suppress fragmentation, accelerate remark to shrink pauses. Full params:
# ==== CMS Triage Params (JDK8, Incident 2 Scene) ====
-Xms8g -Xmx8g
-XX:+UseConcMarkSweepGC
# Young ParNew + Old CMS
-XX:CMSInitiatingOccupancyFraction=70
# Start concurrent at 70% old gen, leave headroom
-XX:+UseCMSInitiatingOccupancyOnly
# Only trigger by above threshold, disable adaptive
-XX:ParallelGCThreads=8
-XX:ConcGCThreads=3
# Concurrent threads ~1/4 of GC threads
-XX:+CMSParallelRemarkEnabled
# Parallel remark, compress remark pause
-XX:+CMSScavengeBeforeRemark
# Minor GC before remark to reduce re-scan
-XX:CMSFullGCsBeforeCompaction=2
# Force compaction after 2 Full GCs
-XX:+ExplicitGCInvokesConcurrent
# System.gc() runs concurrent collection
-XX:+PrintGCDetails -XX:+PrintGCDateStamps
-XX:+PrintTenuringDistribution
# Age distribution: window to observe dynamic age calc
-Xloggc:/logs/gc.log
# JDK8 legacy logging (JDK9+ use -Xlog:gc*)2.3 Reading a GC Log: The Three Questions
Logs are GC's ECG. Fixed three-question reading:
Which region collected?
Before/after delta?
How long paused?
Example (fields vary by collector):
# ==== GC Log Three-Question Reading (Illustrative) ====
[gc] GC(12) Pause Young (Allocation Failure) 2365M->412M(8192M) 4.5ms
# Q1: Young only collects young gen; GC(12) sequence
# Q2: 2365M->412M before/after (surviving total), 8192M heap capacity
# Q3: 4.5ms this pause
[gc] GC(15) Pause Full 3.2s
# Full appears: full heap collection, second-level pause
# → must check promotion curve & fragmentation
# Non-restart quick observation: jstat sampling
jstat -gcutil <pid> 1000 10
# Sample 10 times/sec each region occupancy & GC counts
# O slow climb + FGC growth = promotion storm
# + check daily O growth slope for anomalyTwo observation habits: (1) Chart Minor GC frequency and promotion volume — promotion spike (Incident 3 shape) appears hours before Full GC, best early warning. (2) Every Full GC must be attributed — promotion failure, metaspace, explicit System.gc(), large object allocation failure — record in postmortem. Log value is in trend comparison, not single-line interpretation.
Upgrade log reading to alerting thresholds (calibrate to business baseline):
Minor GC P99 pause > 50 ms — young gen live set may be out of control, check caches/collections.
Full GC occurs → immediate alert — in online services Full GC is an anomaly.
Old gen day-over-day growth > 30% — promotion storm or leak precursor.
Old gen steady-state > 80% — Full GC imminent, preemptively scale or shed load.
GC frequency doubles — cause outside traffic (large objects, batch jobs, leak).
These five in on-call handbook move GC fault detection from "user complaints" to "curve inflection points."
2.4 Postmortem: Promotion Failed Diagnosis in Three Steps
Incident 2 full diagnosis replay.
Qualify: Log shows promotion failed immediately followed by concurrent mode failure — promotion failed first, meaning old gen lacked contiguous space for promoted objects.
Check fragmentation: jstat -gcutil O% oscillates ~70% but Full GC only drops it slightly; MAT dominator tree confirms no giant retained objects — fragmentation confirmed, not leak.
Triage: Lower CMS trigger to 70%, enable periodic compaction, rate-limit large result-set objects. After three steps promotion failed vanished, but root cure remains: migrate to G1. CMS fragmentation is architectural; parameters only delay, cannot eradicate.
Quick triage to distinguish "fragmentation" vs "leak" (both cause frequent Full GC, opposite fixes). Two signals:
Old gen water level after Full GC — compaction-type Full GC ends at low level (e.g., <30%) → no leak, just fragmentation or transient large object; stays high and climbs → consider leak.
Heap dump dominator tree — fragmentation shows normal business objects; leak shows a stable, ever-growing collection. Diagnose first, prescribe second; avoid "tuning a leak as fragmentation" or vice versa.
2.5 Three High-Frequency Misconceptions
Misconception 1: Increase Xmn to eliminate Minor GC. Larger young gen → more live data copied per Minor GC → longer pauses, plus squeezes old gen → accelerates promotion. Generational tuning is balance: ensure Survivor fits normal traffic first, then discuss Eden size.
Misconception 2: SurvivorRatio is a universal knob. Ineffective in G1 (dynamic Regions), in Parallel must work with adaptive sizing — parameters always couple with collector.
Misconception 3: Ample memory means ignore GC. Pause is determined by live object copy/scan volume , not free space — a single large cache can make 16G heap Minor GC pause 100 ms. GC tuning targets live object scale, not heap size.
Closing with a Weekly GC Inspection Checklist (10 min/week):
Pull week of GC logs, compute Minor GC frequency & P99 pause, compare to prior week.
Calculate promotion volume (sum of old gen delta per Minor GC), plot weekly trend.
Check if dynamic age calculation triggers continuously ( PrintTenuringDistribution desired survivor size chronically hitting Survivor cap).
Verify every Full GC has attributed root cause recorded.
Review new code for static collections/local caches — confirm capacity caps & eviction.
Inspection value is in trends, not snapshots — GC failures almost always have days of evolution curves; inflection points precede alerts by a wide margin.
Core Source Code: Four Segments to Understand GC Internals
3.1 Dynamic Age Calculation Reality (HotSpot Simplified)
// OpenJDK 17 · ageTable.cpp (simplified)
uint ageTable::compute_tenuring_threshold(
size_t survivor_capacity) {
// TargetSurvivorRatio default 50:
// Survivor only expects to use half capacity
size_t target = survivor_capacity
* TargetSurvivorRatio / 100;
uint age = 1;
size_t total = 0;
while (age < MAX_AGE) { // MAX_AGE=15
total += sizes[age]; // total bytes of that age
if (total > target) break;
age++;
}
// Clamp to MaxTenuringThreshold
return MIN2(age, MaxTenuringThreshold);
}
// Dynamic age calc: accumulates BYTES not object count;
// threshold computed REAL-TIME each GCThis source clarifies two widespread misreads: dynamic age calculation accumulates bytes, not object count (so a few large objects can trigger it); threshold is computed real-time each GC , not a fixed config — MaxTenuringThreshold is only an upper clamp. To observe it, JDK 8 enable PrintTenuringDistribution; log's "desired survivor size" is this target.
3.2 Minor GC Main Flow (PS Simplified)
// OpenJDK 17 · psScavenge.cpp (pseudo-code level)
void PSScavenge::invoke() {
// 1. Request global safepoint: all threads arrive
// 2. Parallel root scan: stacks/classes/JNI roots
// via OopMap direct locate, no full stack walk
// 3. Copy phase: live objects to To or promote Old;
// object header age field +1
// 4. Promotion-failed objects: stay or trigger fallback
// 5. Swap From/To; use age table to compute
// next promotion threshold (3.1 function)
}
// Pause cost = live object size + root count
// Independent of total heap — why young gen dares frequent GC3.3 Write Barriers: Concurrent Marking's Engineering Landing
// HotSpot Write Barrier (simplified)
// Post-barrier: triggers after every reference store
void oop_store(oop* field, oop val) {
*field = val;
card_table->mark(field);
// Card page 512B whole-page dirty, cost O(1)
}
// CMS Incremental Update: barrier records black->white
// G1 SATB Pre-barrier: records overwritten old value
void g1_satb_pre_barrier(oop* field) {
oop old = *field;
if (old != null && marking_active)
satb_queue->push(old);
}
// Tri-color correctness entirely rests on these few hook linesWrite barriers explain an often-ignored cost: reference stores in concurrent collectors aren't free — each store carries a hook. This is also why G1's baseline memory footprint and single-core throughput lag Parallel Scavenge. Understanding "correctness is purchased" explains why small heaps/services run faster on PS.
3.4 Safepoint Polling: STW's Switch
// Safepoint Mechanism (simplified)
// Mutator polls memory page at safepoint locations
if (polling_page_read()
== SAFEPOINT_REQUESTED)
SafepointSynchronize::block(this);
// All threads arrived, GC truly begins
// Pause = GC work time + wait-for-threads time
// Long counting loops delay safepoint arrival
// -XX:+UseCountedLoopSafepoints fixes
// -Xlog:safepoint observes arrival timeSafepoint source answers Section 1.4's suspense: GC log pause usually only counts GC work; "wait for last thread" appears explicitly in safepoint logs. Production "monitoring pause ≠ GC log" → enable -Xlog:safepoint to see sync time, then hunt long counting loops — a fix ten times cheaper than switching collectors.
Connecting 3.2 and 3.4 yields an engineering conclusion: Minor GC pause structure is "arrival + work"; optimization directions are completely different — slow arrival → check safepoints & long loops; slow work → check live object scale. Production must first split pause into these two segments before deciding which end to touch, avoiding "double GC threads yet zero improvement" missteps. This is also the groundwork for Chapter 09's diagnostic toolchain: pause attribution is GC troubleshooting's first triage.
Seven Accounts Summary
Root Reference Account: Static Map /collections are GC Roots; objects hung there are immortal. Local caches must have capacity caps + expiration eviction. "GC fixes leaks" only works if objects are truly unreachable.
Reference Account: Caches → soft, metadata maps → weak, off-heap cleanup → phantom. ThreadLocal must remove() — weak key collected but strong value remains in map.
Marking Account: Concurrent correctness bought via write barriers: CMS incremental update re-scans black, G1 SATB snapshots deletions. Cost: reference stores no longer free.
Pause Account: STW = GC work + thread arrival. Long counting loops are stealth assassins; UseCountedLoopSafepoints + safepoint logs are the two-hammer diagnosis.
Promotion Account: Three paths: age threshold, dynamic age (byte-based), large object direct. Dynamic age triggers when Survivor tight → batch early promotion. Promotion spike is earliest warning signal.
Algorithm Account: Sweep leaves fragments (CMS destiny), copy wastes space (young gen exclusive), compact most expensive (old gen/Full GC fallback). Algorithm choice = f(survival rate); don't cross-apply.
Selection Account: JDK 17: Serial/Parallel/G1/ZGC/Shenandoah; CMS removed. Batch → throughput, Online → balanced, Huge heap → low latency. Pick collector first, then tune params.
High-Frequency Interview Questions (with Answers)
The article lists 20 Q&A covering: reachability vs reference counting, GC Roots enumeration, four reference types & scenarios, ThreadLocal leak mechanism, finalize() self-rescue (once, deprecated JDK 9+), tri-color marking & missed-mark conditions, incremental update vs SATB, write barrier purpose, STW necessity & non-concurrent phases, safepoint & monitoring vs log discrepancy, OopMap role, generational hypothesis & speedup, Minor GC flow & speed reason, three promotion paths, dynamic age algorithm & misreads, three algorithms pros/cons/applicability, CMS promotion failed cause & mitigation, JDK 17 collector lineup & selection, GCTimeRatio vs MaxGCPauseMillis tradeoff, first production GC troubleshooting step (GC log + jstat sampling, promotion trend as early warning).
One-Page Cheatsheet
GC Basics in Eight Lines: ① Liveness from roots; ② Reference grading: soft cache, weak map, phantom cleanup; ③ Concurrent marking via tri-color, missed-mark fixed by CMS (watch adds) / G1 (watch deletes); ④ STW unavoidable for root enum, safepoint is switch, long loops are assassins; ⑤ Minor GC cost = live objects + roots, heap-size independent; ⑥ Dynamic age by bytes, small Survivor → early tenure; ⑦ Sweep fragments, copy wastes space, compact costliest; ⑧ JDK 17 family: throughput Parallel, balanced G1, low-latency ZGC, CMS exited.
Conclusion & Next Episode Preview
Revisiting three incidents with this episode's vocabulary:
Incident 1: Static Map is GC Root → objects forever reachable. Fix isn't GC tuning, but cache caps + eviction to make objects unreachable.
Incident 2: CMS mark-sweep doesn't move objects → fragmentation accumulates → promotion fails → Full GC fallback. Triage trio (lower trigger, periodic compaction, remark acceleration); root cure: migrate G1 for permanent pointer-bump allocation.
Incident 3: Undersized Survivor → dynamic age triggers continuously → 2-3 year old "fake long-lived" objects batch-promoted. Give young gen back to young gen; Survivor fits normal traffic → dynamic age returns to pressure-valve role.
Three incidents, three root causes: root reference misuse, algorithm destiny, pressure valve failure — GC symptoms vary infinitely, but root causes live in the combination of "determination, marking, collection, generational" concepts.
This episode laid the GC foundation: garbage determination via reachability, concurrent marking via tri-color + write barriers, execution cost honestly exposed as STW by safepoints, three algorithms divided by survival rate, collector family's sole mainline = shortening pauses . Three incidents map to three accounts: root misuse (static cache), algorithm destiny (CMS fragmentation), valve failure (Survivor too small → dynamic age explosion). Next episode "G1 Full Analysis" enters modern collector: Region-based heap organization, pause target decomposition into collection tasks, Mixed GC CSet selection, G1 tuning params in production — every concept here finds its upgraded version in G1.
Hands-on homework: Enable GC logs on your service (JDK 17 -Xlog:gc*, JDK 8 PrintGCDetails + PrintTenuringDistribution), run a load wave, then answer three questions — Minor GC frequency? Single pause? Promotion curve stable? Bring these three numbers to the next episode; every G1 parameter will instantly reveal which curve it moves.
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.
