In depth Garbage collection in Java
- by utk
Let’s dive deep into Java Garbage Collection (GC) — how it actually works inside the JVM,
the different algorithms, tuning options, memory leaks, and how to profile it.
🔥 IN-DEPTH GUIDE TO GARBAGE COLLECTION IN JAVA
🔹 1. JVM Memory Structure Recap
The heap is managed by the garbage collector and is divided into:
➤ Young Generation (Nursery)
• Eden Space – where new objects are allocated.
• Survivor Spaces – S0 and S1, alternate during collection.
• Most objects die young → collected quickly and often.
➤ Old Generation (Tenured)
• Long-lived objects moved from Young Gen after surviving several GCs.
➤ Metaspace (Java 8+)
• Stores class metadata, no longer part of heap.
🔹 2. GC Lifecycle Phases (Mark-Sweep-Compact Model)
Step 1: Mark
• Traverses object graph from GC roots (like static references, stack variables) to
mark all reachable objects.
Step 2: Sweep
• Unmarked objects (i.e. unreachable) are considered garbage and their memory is
reclaimed.
Step 3: Compact
• Moves surviving objects together to eliminate fragmentation.
• Reduces allocation time for future objects.
🔹 3. Object Aging and Promotion
Objects "age" with each GC they survive in the Young Gen. Once they pass a threshold
(e.g., 15 GC cycles), they’re promoted to Old Gen.
text
CopyEdit
Eden → Survivor 0 → Survivor 1 → ... → Tenured
Promotion is expensive, so it's optimized carefully.