In depth major gc in Java
- by utk
What is Major GC?
Major GC (also called Full GC) is the process that collects and cleans up the Old
Generation of the Java heap — where long-lived objects reside.
Old Gen = Tenured space where objects go after surviving several Minor GCs.
🔹 When Does a Major GC Occur?
A Major GC happens under these conditions:
1. Old Gen fills up (no room to promote objects from Young Gen).
2. Explicit GC call via System.gc() or Runtime.getRuntime().gc().
3. Heap compaction required due to fragmentation.
4. G1GC evacuation failure or promotion failure in Young Gen.
🔹 How Major GC Works (Step by Step)
🔸 Step 1: Stop-the-world
• All application threads are paused (even with concurrent GCs).
• Pause times can be long, especially with large heaps.
🔸 Step 2: Mark phase
• Traverses from GC roots (like static variables, local variables, active threads) to find
reachable objects.
• Uses techniques like tricolor marking:
o White: candidate for GC
o Gray: discovered, but references not scanned yet
o Black: scanned and retained
🔸 Step 3: Sweep phase
• Unreachable (white) objects are reclaimed.
🔸 Step 4: Compact phase
• Surviving objects are moved to remove fragmentation.
• Helps future allocations be faster.
☑️ G1 and ZGC reduce full compaction to minimize pause times.