本文由 AI 分析生成
建立時間: 2026-03-28 來源: https://yoziming.github.io/post/220126-jvm-gc/
Summary
Chinese-language reference on JVM memory model and GC strategies, covering reachability analysis for identifying garbage, reference strength types (strong/soft/weak/phantom), the generational heap structure (Eden → Survivor → Old Gen), and three GC algorithms (Mark-Sweep, Copying, Mark-Compact).
關於 JVM 記憶體模型和 GC 策略的中文參考文章,涵蓋可達性分析識別垃圾、引用強度類型(強/軟/弱/虛)、分代堆結構(Eden → Survivor → 老年區),以及三種 GC 算法(標記清除、複製、標記整理)。
Key Points
- Reachability analysis (可達性分析): traverse from GC Roots (VM stack refs, method area static refs, JNI refs); unreachable objects = garbage
- Reference types (JDK 1.2+): Strong (never GC’d while ref exists) → Soft (GC’d before OOM) → Weak (GC’d at next collection) → Phantom (notification only; no access to instance)
- Heap structure: Eden → Survivor (×2) → Old Gen (養老區); objects promoted based on age (MinorGC survivor count)
- Flow: new object in Eden → MinorGC → Survivor → promoted to Old Gen → FullGC → OOM if still no space
- GC algorithms: (1) Mark-Sweep: simple, leaves fragmentation; (2) Copying: no fragmentation, 50% space overhead; (3) Mark-Compact: no fragmentation, slow (good for Old Gen)
- In practice, algorithms are combined by region: Young Gen uses Copying, Old Gen uses Mark-Compact
Insights
The generational hypothesis (most objects die young) underpins the Eden/Survivor/Old Gen design. MinorGC is fast because it only handles Young Gen; FullGC is expensive because it covers the whole heap. The four reference strength levels provide a vocabulary for cache-friendly data structures: soft references implement “keep if memory permits” caches, weak references enable canonicalization maps (WeakHashMap), phantom references handle post-GC cleanup hooks. The “ice tray” analogy (每格格子) is a memorable way to visualize fragmented vs. compacted allocation.
Connections
Raw Excerpt
新物件創在Eden區,放不下就MinorGC小清理。每次MinorGC倖存者區中的物件就變老,待在倖存者區太久超過域值,就趕去老年區養老。老年區還是放不下,執行大掃除FullGC。