How does garbage collection decide what to free — and what are GC roots?
⚡ Short Answer
GC frees objects that are unreachable from GC roots (stack locals, statics, JNI refs, active threads). Mark: traverse from roots marking live objects; Sweep: reclaim unmarked; Compact: defragment. Java GC is reachability-based, not reference-counting, so it handles cycles.
☕Coffee Chat Question
Concept Made Simple
“How does garbage collection decide what to free — and what are GC roots?”
🧠Mind Map Answer
Remember It Faster
🔥What If?
Think Beyond the Expected
Two objects reference each other but nothing else points to them — are they collected?
Yes. Java uses reachability from GC roots, not reference counting, so an isolated cycle is unreachable and gets collected. This is why Java doesn't leak on reference cycles (unlike naive ref-counting).
😂Real World
'Path to GC roots' in a heap analyzer (MAT) is exactly this concept — to fix a leak you find what root still references the object that should be dead.
🎯Interviewer's Expectation
Keywords they're listening for:
⚠️Common Mistakes
- ✗Thinking Java uses reference counting
- ✗Assuming reference cycles leak
- ✗Confusing 'unreachable' with 'null'
✅Best Practices
- ✓Use MAT 'path to GC roots' for leak hunting
- ✓Null out long-lived references when done (rarely needed)
- ✓Understand roots to reason about retention
🔁Follow-up Questions
- 1Why doesn't Java use reference counting?
- 2What does 'path to GC roots' tell you in a heap dump?
- 3What is a safepoint and why does GC need one?
🧩Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly — AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: Garbage Collection (JVM) Interview question: "How does garbage collection decide what to free — and what are GC roots?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
⭐ Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission — at no extra cost to you. It helps keep Full Stack Interview Guru free.