Java Memory Model
GC Algorithms
Compare modern Garbage Collectors: Serial, Parallel, CMS, G1, and ZGC.
Interview: Commonly tested on GC algorithm selection: G1GC vs ZGC latency limits, and Stop-The-World pauses.
The JVM offers several Garbage Collection algorithms designed for different performance goals (throughput, latency, or memory footprints). Selecting the right collector is vital for production scalability.
Core Idea
Modern collectors (like G1 and ZGC) segment the heap and perform concurrent collection to reduce pause times.
Why It Matters
Excessive Stop-The-World (STW) pauses degrade API response latency, violating service-level SLAs.
Interview Lens
Tests knowledge of collector trade-offs and modern low-latency collectors like ZGC.
Garbage Collectors Compared
1. Parallel GC (-XX:+UseParallelGC)
Uses multiple threads to perform collection in parallel. Focuses on maximizing throughput (CPU cycles devoted to application logic), but suffers from longer Stop-The-World (STW) pauses.
2. G1 (Garbage-First) GC (-XX:+UseG1GC)
Default since Java 9. Divides the heap into equal-sized virtual regions. It prioritizes collecting regions with the most garbage first, matching a user-defined pause time target.
3. ZGC (Z Garbage Collector) (-XX:+UseZGC)
A concurrent, low-latency garbage collector introduced as production-ready in Java 15. Performs all memory reclamation phases concurrently with application threads, limiting pauses to sub-millisecond durations regardless of heap size.
Interview-Relevant Information
Q: What is a Stop-The-World (STW) pause?
Answer: An STW pause occurs when the GC algorithm suspends all application threads (mutators) to safely inspect references, move objects, and reclaim memory without state modifications occurring.
Quick Checklist
What GC is default in modern Java? Which collector guarantees sub-millisecond pauses? If yes, you understand GC algorithms.
Use Cases
Using G1GC for general business web applications requiring consistent pause boundaries.
Deploying ZGC for high-frequency trading applications where latency spikes must be prevented.
Common Mistakes
Assuming the Parallel GC is deprecated (it is still widely used in batch processing pipelines where throughput matters more than latency).
Configuring heap sizes too small for G1GC, causing it to fail recovery targets and fall back to Full STW GCs.