Java Garbage Collection Explained
Garbage collection is the JVM’s automatic memory management — it finds and reclaims objects your program no longer uses. Understanding GC is critical for building high-performance Java applications.
Why Garbage Collection?
In C/C++, you manually malloc() and free(). Forget to free → memory leak. Free twice → crash.
Java’s GC eliminates this:
void processOrder() {
Order order = new Order(); // allocated on heap
order.process();
// order goes out of scope — GC will reclaim it
}
Tradeoff: GC introduces pauses (stop-the-world events) that can affect latency.
GC Roots and Reachability
An object is live if it’s reachable from a GC root. Everything else is garbage.
GC Roots:
├── Local variables (on thread stacks)
├── Active threads
├── Static fields
├── JNI references
└── System class loader references
GC Root → obj A → obj B → obj C ← all live
obj D ← unreachable → garbage
Key: GC doesn’t use reference counting. It traces from roots — this handles circular references correctly.
The Generational Hypothesis
Observation: Most objects die young.
Object Lifetime Distribution:
^ Count
│ ████████████████████
│ ████████████
│ ████████
│ █████
│ ███
│ ██
│ █
└──────────────────────► Lifetime
short long
This is why the heap is divided into generations:
| Generation | Contains | GC Frequency |
|---|---|---|
| Young Gen (Eden + Survivors) | New objects | Frequent (minor GC) |
| Old Gen (Tenured) | Long-lived objects | Rare (major/full GC) |
Object Lifecycle
1. new Object() → allocated in Eden
2. Eden fills up → Minor GC triggered
Live objects → moved to Survivor S0
Dead objects → reclaimed
3. Next Minor GC → Eden + S0 live objects → S1
S0 cleared
4. After N minor GCs (age threshold) → promoted to Old Gen
5. Old Gen fills up → Major/Full GC triggered
Minor vs Major vs Full GC
| Type | Scope | Pause | Frequency |
|---|---|---|---|
| Minor GC | Young Gen only | Short (ms) | Frequent |
| Major GC | Old Gen | Longer | Less frequent |
| Full GC | Entire heap + Metaspace | Longest | Rare (avoid!) |
Full GC is the one that causes noticeable pauses. Your tuning goal: minimize Full GCs.
GC Algorithms
Serial GC
java -XX:+UseSerialGC -jar app.jar
- Single-threaded stop-the-world
- Best for: small apps, single-CPU machines, containers with 1 core
- Pause: proportional to heap size
Parallel GC (Throughput Collector)
java -XX:+UseParallelGC -jar app.jar
- Multi-threaded stop-the-world
- Maximizes throughput (total CPU time spent on app vs GC)
- Best for: batch processing, data pipelines
- Default in Java 8
G1 GC (Garbage-First)
java -XX:+UseG1GC -jar app.jar
- Default since Java 9
- Divides heap into regions (~2048 regions)
- Collects the regions with the most garbage first (hence “Garbage-First”)
- Targets a pause time goal (
-XX:MaxGCPauseMillis=200) - Best for: most applications (balanced throughput + latency)
┌───┬───┬───┬───┬───┬───┬───┬───┐
│ E │ E │ S │ O │ O │ H │ E │ O │ G1 Regions
│ │ │ │ │ │ │ │ │ E=Eden, S=Survivor
└───┴───┴───┴───┴───┴───┴───┴───┘ O=Old, H=Humongous
ZGC (Z Garbage Collector)
java -XX:+UseZGC -jar app.jar
- Sub-millisecond pauses (< 1ms), regardless of heap size
- Supports terabyte-scale heaps
- Concurrent — almost no stop-the-world
- Best for: latency-critical applications (trading, real-time)
- Production-ready since Java 15
Shenandoah GC
java -XX:+UseShenandoahGC -jar app.jar
- Similar goals to ZGC — low-pause concurrent collector
- Available in OpenJDK (not Oracle JDK)
- Concurrent evacuation (compacts while app runs)
- Best for: low-latency apps on OpenJDK
Choosing the Right GC
| Workload | Recommended GC | Why |
|---|---|---|
| General purpose | G1 | Balanced, default, well-tuned |
| Batch/throughput | Parallel | Max throughput, pauses acceptable |
| Low latency (< 10ms) | ZGC or Shenandoah | Sub-ms pauses |
| Small app/container | Serial | Minimal overhead |
| Huge heap (100GB+) | ZGC | Handles terabytes efficiently |
Decision Tree:
Is latency critical (< 10ms P99)?
├── Yes → ZGC (or Shenandoah on OpenJDK)
└── No
├── Throughput matters most? → Parallel GC
└── Balanced? → G1 GC (default)
Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
| Never checking which GC is active | May be using wrong GC for workload | java -XX:+PrintFlagsFinal -version | grep UseGC |
| Ignoring GC logs | Can’t diagnose latency spikes | Always enable GC logging in production |
Forcing System.gc() |
Triggers unnecessary Full GC | Never call it (use -XX:+DisableExplicitGC) |
| Allocating huge arrays | “Humongous” allocations bypass normal GC | Stream/chunk large data |
| Promoting too fast | Objects reach Old Gen before they die | Increase survivor space/age threshold |
Key Takeaways
- GC traces from roots — unreachable objects are garbage (handles circular refs).
- Generational hypothesis: most objects die young → young/old gen split.
- G1 is the default and right choice for most apps.
- ZGC for sub-millisecond pauses on latency-critical workloads.
- Full GC is the enemy — tune to minimize or eliminate it.
- Never call
System.gc()in production.
What’s Next?
Next: GC Tuning and JVM Flags — practical tuning with real flags and GC log analysis.