library
advancedJVM Memory Model & Garbage Collection
Understand heap structure, GC generations, and how different collectors affect application latency.
The JVM divides heap memory into generations based on object lifespan:
Young Gen = a desk you clear every evening (minor GC). Old Gen = a storage room you deep-clean quarterly (major GC). ZGC = a cleaning crew that works around you without stopping your work (concurrent).
Key Concepts
1
Young Generation: newly created objects. Divided into Eden (where objects are born) and two Survivor spaces (S0, S1). Minor GC (young GC) collects Eden + one Survivor, copying survivors to the other. Fast — most objects die young (generational hypothesis).
2
Old Generation (Tenured): objects that survived multiple minor GCs. Major GC (or full GC) collects Old Gen — slower and more impactful. Triggered when Old Gen fills up.
3
Metaspace (Java 8+, replaced PermGen): stores class metadata, method bytecode. Auto-grows, limited by MaxMetaspaceSize.
4
Garbage Collectors:
- Serial GC: single-threaded, stop-the-world. Only for small heaps.
- Parallel GC: multi-threaded young + old collection. Default in Java 8. Optimizes throughput.
- G1 GC (default since Java 9): divides heap into ~2000 regions. Concurrent marking, incremental compaction. Targets pause time goals (-XX:MaxGCPauseMillis).
- ZGC (Java 15+): sub-millisecond pauses regardless of heap size. Concurrent everything. Ideal for latency-sensitive apps.
- Shenandoah: similar to ZGC, available in OpenJDK.
5
Key JVM flags: -Xms (initial heap), -Xmx (max heap), -Xmn (young gen size), -XX:+UseG1GC, -XX:MaxGCPauseMillis.