Garbage Collection Algorithm: G1 (Garbage First) GC
The G1 GC (Garbage First Garbage Collector) is the default garbage collector in the HotSpot JVM (Java 9+). It is designed for low pause times and efficient memory management, especially for large heaps (>4GB).
1. How G1 GC Works (Algorithm Overview)
G1 GC divides the heap into multiple fixed-size regions instead of traditional Young/Old generation separation.
🔹 Heap is split into regions (not fixed Eden/Survivor/Old spaces).
🔹 GC prioritizes collecting most garbage-filled regions first (“Garbage First”).
🔹 Concurrent execution reduces pause times.
2. G1 GC Algorithm Steps
Step 1: Heap Structure (Region-Based)
✔ Divides heap into fixed-size regions instead of separate Young/Old spaces.
✔ Each region can belong to Eden, Survivor, Old, or Humongous category.
🔹 Eden Region → Where new objects are allocated.
🔹 Survivor Region → Where objects that survive GC are moved.
🔹 Old Region → Where long-lived objects are stored.
🔹 Humongous Region → Where very large objects (bigger than one region) are stored.
Step 2: Young Generation Collection
✔ Minor GC collects only Young generation regions (Eden + Survivor).
✔ Surviving objects are promoted to Survivor/Old regions.
✔ Uses “copying” instead of compacting, improving efficiency.
Step 3: Concurrent Marking (Identifies Garbage)
✔ Runs alongside the application (does not fully stop execution).
✔ Marks unused objects in Old regions using a “card table”.
✔ Determines regions with the most garbage for next collection cycle.
Step 4: Mixed Collection (Young + Old)
✔ Unlike other GCs, G1 GC can collect both Young and Old regions together.
✔ Prioritizes collecting Old regions with most garbage first (hence “Garbage First”).
✔ Reclaims memory efficiently without long pause times.
Step 5: Compacting & Freeing Regions
✔ Freed-up regions are compacted and reused for new allocations.
✔ This reduces heap fragmentation, improving performance.
3. Why is G1 GC Efficient?
| Feature | Benefit |
|---|---|
| Region-based memory layout | More flexibility in managing memory |
| Prioritized garbage collection | First collects regions with most garbage |
| Concurrent execution | Reduces pause times |
| Compacting mechanism | Prevents memory fragmentation |
4. How to Enable G1 GC?
G1 GC is enabled by default in Java 9+, but you can specify it manually:
java -XX:+UseG1GC MyApp
5. Summary of G1 GC Algorithm
| Step | Description |
|---|---|
| 1. Heap is divided into regions | Heap split into Eden, Survivor, Old, and Humongous regions |
| 2. Young GC (Minor GC) | Clears Eden and moves surviving objects to Survivor/Old |
| 3. Concurrent Marking | Identifies regions with most garbage |
| 4. Mixed GC (Young + Old) | Collects Young and Old regions based on priority |
| 5. Compacting & Reuse | Defragments heap for efficiency |