Java Garbage Collection Explained: G1, ZGC & Generational Heap
Understand how the Java JVM reclaims heap memory. Learn Young Generation, Eden, Survivor spaces, Old Generation, Stop-the-World pauses, G1, and ZGC.
// Demonstrating object eligibility for Garbage Collection
public class GCDemo {
private String resourceId;
public GCDemo(String id) {
this.resourceId = id;
}
public static void main(String[] args) {
GCDemo obj1 = new GCDemo("ActiveResource-1");
GCDemo obj2 = new GCDemo("TemporaryResource-2");
// obj2 becomes eligible for garbage collection once reassigned to null
obj2 = null;
// Island of isolation example
Node a = new Node();
Node b = new Node();
a.neighbor = b;
b.neighbor = a;
a = null;
b = null; // Both objects now unreferenced from GC Roots
}
}
class Node {
Node neighbor;
}
1. JVM Heap Organization: The Generational Hypothesis
Java's Garbage Collector operates on the empirical observation known as the Weak Generational Hypothesis: the vast majority of allocated objects have very short lifespans (e.g. temporary loop variables, method parameters). To optimize reclamation, the JVM heap is segmented into distinct generations:
- Young Generation: Composed of the Eden space and two Survivor spaces (S0 and S1). All newly instantiated objects are placed in Eden.
- Old (Tenured) Generation: Holds long-lived objects that survive multiple minor garbage collection cycles.
2. Minor GC vs. Major/Full GC
When the Eden space fills up, the JVM triggers a Minor GC. Live objects are marked using reachability analysis from GC Roots (threads, static variables, local variables) and copied into a Survivor space. Dead objects are discarded immediately without fragmentation. After surviving several rounds (tenuring threshold, default 15), survivors are promoted to the Old Generation.
3. Modern Production Collectors: G1 and ZGC
Modern enterprise applications utilize advanced low-pause collectors:
- Garbage-First (G1 GC): Partitions the heap into equal-sized regions and prioritizes collecting regions with the most garbage first within a target pause time budget.
- ZGC (Z Garbage Collector): A scalable low-latency collector capable of sub-millisecond pauses on terabyte heaps using colored pointers and load barriers.
- Objects are eligible for GC when they are no longer reachable from any active GC Root.
- System.gc() is only a hint to the JVM and does not guarantee immediate collection.
- Profiling tools like VisualVM and JConsole help detect memory leaks caused by lingering static references.
Frequently Asked Questions
What are GC Roots?
Gain deep mastery over these concepts with direct instructor guidance, code reviews, and mock interviews at C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad.
Explore Related Course Call 7503962162