What is Mark-and-Sweep GC?
Fast recall
Quick revision
Core answer
Understanding of the fundamental two-phase GC algorithm and its mechanics
Not knowing there are two distinct phases — mark first to identify live objects, then sweep to reclaim dead ones
Mention the fragmentation problem and that modern GCs add a compaction phase to address it
Interview-ready guide
Interview answer
Mark-and-sweep is a tracing garbage-collection model with two ideas. First, start from GC roots and mark every object reachable through reference paths. Second, reclaim the space belonging to objects that remain unmarked. Because liveness comes from roots rather than reference counts, an unreachable cycle can be collected. A basic non-compacting sweep may leave separated free regions between survivors. Production JVM collectors are more complex: they may copy objects, compact selected regions, mark concurrently, and use barriers or remembered sets. G1, ZGC, and Shenandoah should therefore be explained through their own documented phases, not as a literal full-heap mark followed by moving every survivor to one end.
What is Mark-and-Sweep GC
Direct Answer
Mark-and-sweep is a tracing model with two phases: mark objects reachable from GC roots, then make unmarked space reusable. A basic non-compacting sweep can leave free regions between live objects. Production JVM collectors combine tracing with collector-specific copying, compaction, regions, barriers, and concurrent work.
Code Example
// Conceptual representation of mark-and-sweep
public class MarkSweepDemo {
static class Node {
String data;
Node next;
boolean marked = false; // GC mark bit
Node(String data) { this.data = data; }
}
// Simulating the MARK phase
static void markReachable(Node root) {
if (root == null || root.marked) return;
root.marked = true; // Mark this object as reachable
markReachable(root.next); // Traverse to next
}
// Simulating the SWEEP phase
static void sweepUnreachable(List<Node> heap) {
heap.removeIf(node -> !node.marked);
// In real GC, this reclaims memory
// Unmarked objects are dead and removed
}
}
Common Mistakes & Pitfalls
- Treating the teaching model as every JVM collector: A basic non-compacting mark-and-sweep scans and frees unmarked areas, but production collectors use different regions and phases.
- Assuming marking must all stop the world: Concurrent collectors can mark while application threads run, using barriers and short synchronization pauses to preserve correctness.
- Forgetting fragmentation: A non-compacting sweep can leave separated free regions. Copying, compaction, or region-based allocation can address that cost in collector-specific ways.
Check your understanding
Answer these without looking back at the article.
- What is heap fragmentation and how does GC compaction help?
- What is the difference between mark-sweep and mark-sweep-compact?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.