🗑️ Java Garbage Collector (GC): Timing, Behavior &
Object Types
🧠 Java Memory Overview
🔄 Stack vs Heap
• Stack:
• 🧠 Stores method call frames and local variables.
• 🗑️ Automatically freed when a method ends.
• 🚫 Not managed by the Garbage Collector.
• Heap:
• 📦 Stores objects, arrays, and data created using new .
• 🔄 Shared among all threads.
• ✅ Managed by the Garbage Collector.
🧹 Role of the Garbage Collector
• GC manages memory in the heap by reclaiming memory occupied by unreachable objects.
• 🚫 It does not manage memory in the stack.
• ⚙️ Java offers several GC algorithms, including Serial, Parallel, G1, ZGC, and Shenandoah.
📌 Anonymous vs Reference Objects
📍 Reference Object
Person p = new Person();
• 📌 The object is stored in the heap; p (the reference) is on the stack.
• 🕒 The object becomes eligible for GC when p goes out of scope or is explicitly set to null .
1
⚡ Anonymous Object
new Person().sayHello();
• ❓ The object is not assigned to any variable.
• ⚡ It becomes eligible for GC immediately after use.
📝 Summary
Type Held in Variable? GC Eligibility Trigger
Reference Object Yes When reference is lost or nullified
Anonymous Object No After method execution ends
🧪 Real-Time Example
public class GCDemo {
static class Test {
@Override
protected void finalize() throws Throwable {
System.out.println("Object finalized");
}
}
public static void main(String[] args) {
Test obj = new Test(); // reference object
obj = null; // eligible for GC
new Test(); // anonymous object, no reference
System.gc(); // Suggest GC
}
}
✅ This will likely print "Object finalized" (not guaranteed) showing when the object is collected.
⏰ When Does GC Run?
• ⏳ Non-deterministic: The exact timing is unpredictable.
• 🚨 GC is triggered by the JVM under conditions such as:
• 📈 Increased memory pressure
• 🔁 Heap usage reaching certain thresholds
• 🧪 Developers can suggest GC using System.gc() , but the JVM may ignore it.
2
⚙️ Working Principle of Java GC
📂 1. Mark Phase
• Identifies all live (reachable) objects starting from GC Roots (e.g., static fields, active thread stacks).
🗑️ 2. Sweep / Delete Phase
• Reclaims memory by removing unreferenced objects.
🔁 3. Compact Phase (Optional)
• Moves live objects together to avoid fragmentation.
♻️ 4. Generational GC
Java divides heap into:
• 🔹 Young Generation: New objects (frequent GC)
• 🔸 Old Generation: Long-lived objects (infrequent GC)
• 🔧 Metaspace: Class metadata (not part of heap)
This optimizes performance by collecting short-lived objects more often.
⏳ Average Garbage Collection Time
⚡ By GC Type
GC Type Avg Young GC Time Avg Old GC Time Notes
Serial GC 10–100 ms 200 ms – few sec 🧵 Single-threaded
Parallel GC 20–100 ms 300 ms – few sec 🧵 Multi-threaded
G1 GC 1–20 ms 100 ms – 1 sec 🗂️ Region-based and predictable
ZGC/Shenandoah <10 ms <10 ms ⚡ Ultra low-latency, concurrent
📊 Typical Ranges
Application Type Young GC Avg Old GC Avg
🖥️ Small desktop app 10–50 ms 300–1000 ms
🌐 Medium web server 20–100 ms 0.5–2 sec
🚀 High-scale services <20 ms <200 ms (G1/ZGC)
3
🎯 Factors Influencing GC Time
• ⚙️ Choice of GC algorithm
• 📏 Size of the heap
• 🧪 Rate of object allocation
• ⏳ Lifespan of objects
• 🎯 Configured pause time goals (tunable via JVM flags)
📈 Monitoring Garbage Collection
📝 Enable GC Logs:
-XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:gc.log
🛠️ Recommended Tools:
• 🔍 VisualVM
• 📊 Java Mission Control (JFR)
• 📈 JConsole
• 🧾 GCViewer
📋 Example GC Log:
[GC (Allocation Failure) 100M->30M(200M), 0.0156780 secs]
• 🕒 Indicates a GC pause of 15.6 milliseconds
📚 Summary Table
GC Phase Avg Time Primary Goal
🧼 Young GC 10–100 ms Fast cleanup of short-lived objects
🧹 Full/Old GC 100 ms – few sec Compacts and reclaims long-lived data
⚡ Modern GC (ZGC) <10 ms (any gen) Predictable, ultra-low pause times