Mark, sweep and compact
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every tracing garbage collector does the same three jobs in some form: mark the live objects, reclaim the space of the others, and often move the live ones together so new objects can be placed quickly. HotSpot's collectors mix these steps in different ways, but the ideas are the same.
Mark: find all reachable objects
Mark and sweep is a way to collect garbage in two steps. Mark sets a mark on every object reachable from the roots; sweep then turns the space of every unmarked object into free space.
The mark phase starts at the GC roots, follows every reference, and sets a mark on each object it reaches. The mark is a bit stored in the object's header or in a separate table (a mark bitmap), depending on the collector.
A 10-slot heap through mark, sweep, compact and a new allocation (simplified)
Step 1 of 5
Example 1 · Mark on a 10-slot model heap
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import java.util.TreeSet;
class MiniHeap { String[] slots; Map<String, List<String>> refs = new HashMap<>(); List<String> roots = new ArrayList<>(); Set<String> marked = new TreeSet<>();
MiniHeap(String... objects) { slots = objects; }
void ref(String from, String to) { refs.computeIfAbsent(from, k -> new ArrayList<>()).add(to); }
void mark() { Deque<String> toVisit = new ArrayDeque<>(roots); while (!toVisit.isEmpty()) { String o = toVisit.pop(); if (marked.add(o)) { toVisit.addAll(refs.getOrDefault(o, List.of())); } } }
String show() { StringBuilder sb = new StringBuilder("["); for (int i = 0; i < slots.length; i++) { sb.append(i == 0 ? "" : " ").append(slots[i] == null ? "." : slots[i]); } return sb.append("]").toString(); }}
public class MarkDemo { public static void main(String[] args) { MiniHeap heap = new MiniHeap("A", "B", "C", "D", "E", "F", "G", "H", null, null); heap.roots.add("A"); // a local variable in main() heap.roots.add("D"); // a static field heap.ref("A", "C"); heap.ref("D", "G"); heap.ref("E", "B"); // garbage may point anywhere, even at live A heap.ref("E", "F"); heap.ref("F", "E"); heap.ref("H", "A"); System.out.println("Heap: " + heap.show()); heap.mark(); System.out.println("Marked: " + heap.marked);
List<String> unmarked = new ArrayList<>(); for (String s : heap.slots) { if (s != null && !heap.marked.contains(s)) { unmarked.add(s); } } System.out.println("Unmarked: " + unmarked); }}Heap: [A B C D E F G H . .] Marked: [A, C, D, G] Unmarked: [B, E, F, H]
What this code does
- This is a simplified model, not HotSpot code: each slot holds one object, and
refsrecords which object points to which.mark()visits only objects reachable from the roots A and D. - E, F and H all point at other objects (H even points at the live A), but nothing reachable points at them, so they stay unmarked. The diagram above shows the same heap.
When marking ends, every live object carries a mark and every garbage object does not. Marking costs time in proportion to the number of live objects and references, because garbage is never visited.
Order of execution
Put the collection steps in order
Tap the steps in the order the collector does them.
Sweep: reclaim the rest
Sweep walks through the heap and turns the space of every unmarked object into free space. A sweeping collector usually records the free gaps in a free list: a list of where each gap starts and how big it is.
Example 2 · Sweep leaves free space in pieces
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import java.util.TreeSet;
class MiniHeap { String[] slots; Map<String, List<String>> refs = new HashMap<>(); List<String> roots = new ArrayList<>(); Set<String> marked = new TreeSet<>();
MiniHeap(String... objects) { slots = objects; }
void ref(String from, String to) { refs.computeIfAbsent(from, k -> new ArrayList<>()).add(to); }
void mark() { Deque<String> toVisit = new ArrayDeque<>(roots); while (!toVisit.isEmpty()) { String o = toVisit.pop(); if (marked.add(o)) { toVisit.addAll(refs.getOrDefault(o, List.of())); } } }
String show() { StringBuilder sb = new StringBuilder("["); for (int i = 0; i < slots.length; i++) { sb.append(i == 0 ? "" : " ").append(slots[i] == null ? "." : slots[i]); } return sb.append("]").toString(); } void sweep() { for (int i = 0; i < slots.length; i++) { if (slots[i] != null && !marked.contains(slots[i])) { slots[i] = null; } } }}
public class SweepDemo { public static void main(String[] args) { MiniHeap heap = new MiniHeap("A", "B", "C", "D", "E", "F", "G", "H", null, null); heap.roots.add("A"); // a local variable in main() heap.roots.add("D"); // a static field heap.ref("A", "C"); heap.ref("D", "G"); heap.ref("E", "B"); // garbage may point anywhere, even at live A heap.ref("E", "F"); heap.ref("F", "E"); heap.ref("H", "A"); heap.mark(); heap.sweep(); System.out.println("After sweep: " + heap.show());
List<String> freeList = new ArrayList<>(); int free = 0, largest = 0; for (int i = 0; i < heap.slots.length; ) { if (heap.slots[i] != null) { i++; continue; } int start = i; while (i < heap.slots.length && heap.slots[i] == null) { i++; } int size = i - start; freeList.add("slot " + start + " size " + size); free += size; largest = Math.max(largest, size); } System.out.println("Free list: " + freeList); System.out.println("Free slots: " + free + ", largest gap: " + largest); System.out.println("Can place a 4-slot array? " + (largest >= 4)); }}After sweep: [A . C D . . G . . .] Free list: [slot 1 size 1, slot 4 size 2, slot 7 size 3] Free slots: 6, largest gap: 3 Can place a 4-slot array? false
What this code does
- Sweep only clears the unmarked slots; the live objects A, C, D and G stay where they were, so no reference has to change.
- Six slots are free, but the free list has three separate gaps and the largest is 3. A 4-slot array does not fit: this is fragmentation.
Sweeping does not move anything, so references stay valid and the work is simple. The cost is that the free space ends up in many small pieces between the live objects.
Compact and copy: move live objects together
Compaction slides live objects toward one end of the heap so the free space becomes one large block. Copying moves live objects into a separate empty area instead, and then treats the whole old area as free.
Example 3 · Compaction slides live objects and fixes references
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import java.util.TreeSet;
class MiniHeap { String[] slots; Map<String, List<String>> refs = new HashMap<>(); List<String> roots = new ArrayList<>(); Set<String> marked = new TreeSet<>();
MiniHeap(String... objects) { slots = objects; }
void ref(String from, String to) { refs.computeIfAbsent(from, k -> new ArrayList<>()).add(to); }
void mark() { Deque<String> toVisit = new ArrayDeque<>(roots); while (!toVisit.isEmpty()) { String o = toVisit.pop(); if (marked.add(o)) { toVisit.addAll(refs.getOrDefault(o, List.of())); } } }
String show() { StringBuilder sb = new StringBuilder("["); for (int i = 0; i < slots.length; i++) { sb.append(i == 0 ? "" : " ").append(slots[i] == null ? "." : slots[i]); } return sb.append("]").toString(); } void sweep() { for (int i = 0; i < slots.length; i++) { if (slots[i] != null && !marked.contains(slots[i])) { slots[i] = null; } } } int compact() { // returns the new "top" Map<String, Integer> newSlot = new HashMap<>(); int top = 0; for (int i = 0; i < slots.length; i++) { if (slots[i] != null) { if (i != top) { System.out.println(" move " + slots[i] + ": slot " + i + " -> slot " + top); } newSlot.put(slots[i], top); slots[top++] = slots[i]; } } for (int i = top; i < slots.length; i++) { slots[i] = null; } for (String from : marked) { // fix references to moved objects for (String to : refs.getOrDefault(from, List.of())) { System.out.println(" reference " + from + " -> " + to + " now points to slot " + newSlot.get(to)); } } return top; }}
public class CompactDemo { public static void main(String[] args) { MiniHeap heap = new MiniHeap("A", "B", "C", "D", "E", "F", "G", "H", null, null); heap.roots.add("A"); heap.roots.add("D"); heap.ref("A", "C"); heap.ref("D", "G"); heap.ref("E", "B"); // garbage may point anywhere, even at live A heap.ref("E", "F"); heap.ref("F", "E"); heap.ref("H", "A"); heap.mark(); heap.sweep(); System.out.println("After sweep: " + heap.show()); int top = heap.compact(); System.out.println("After compact: " + heap.show()); System.out.println("Free space: one block from slot " + top + ", size " + (heap.slots.length - top)); }}After sweep: [A . C D . . G . . .] move C: slot 2 -> slot 1 move D: slot 3 -> slot 2 move G: slot 6 -> slot 3 reference A -> C now points to slot 1 reference D -> G now points to slot 3 After compact: [A C D G . . . . . .] Free space: one block from slot 4, size 6
What this code does
- Live objects slide toward slot 0 in their old order. Three objects moved, so every reference to them must be rewritten: A must now find C in slot 1, not slot 2.
- In a real JVM this rewriting is why the program cannot use the moving objects at the same time. In return, the six free slots become one block that can hold anything up to 6 slots.
- As before,
Ais a root because it is a local variable inmain(), andDbecause it is a static field.
Example 4 · A real program whose young collections copy (evacuate) live objects
import java.util.ArrayList;import java.util.List;
public class ReceiptDemo { public static void main(String[] args) { List<String> kept = new ArrayList<>(); long totalLength = 0; for (int i = 0; i < 3_000_000; i++) { String receipt = "Order-" + i + "-paid-by-UPI"; // garbage after this step totalLength += receipt.length(); if (i % 1000 == 0) { kept.add(receipt); // 1 in 1000 is kept } } System.out.println("Receipts kept: " + kept.size()); System.out.println("Total length: " + totalLength); }}Receipts kept: 3000 Total length: 73888890
What this code does
- Three million receipts are created and almost all die at once; only 3,000 stay reachable through
kept. That is the ideal case for a copying collector. - Run it with
-Xlog:gc(next example) to see each collection copy the few live receipts and free everything else.
Example 5 · The GC log names the copying step
java -Xlog:gc ReceiptDemo[0.013s][info][gc] Using G1 [0.169s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->0M(118M) 3.169ms [0.195s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 37M->0M(118M) 2.324ms [0.253s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 69M->0M(118M) 2.342ms [0.295s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 69M->0M(118M) 1.948ms Receipts kept: 3000 Total length: 73888890
What this code does
- "G1 Evacuation Pause" means live objects were copied out and their old space freed as a whole.
69M->0Mreads: 69 MB used before, under 1 MB after (the log rounds down). - Each pause took 2 to 3 ms although tens of megabytes were freed: copying costs depend on the few live objects, not on the garbage. Your times and sizes will differ (this run: HotSpot, Java 21).
Both must update every reference to an object that moved, so the program cannot run normally during that work. Copying needs spare space to copy into, but its cost depends only on the live objects; dead objects are never touched. In HotSpot's G1 collector (Java 17 and 21), a young collection copies live objects out of their regions; the log calls this an evacuation. A full GC in G1 compacts the whole heap ("G1 Compaction Pause").
Fragmentation and fast bump-pointer allocation
Fragmentation means the free memory is split into small gaps, so a big object may not fit even when the total free space is large. With a free list, every allocation also has to search for a gap that is big enough.
Example 6 · Free-list search versus bump-pointer allocation (simulation)
import java.util.ArrayList;import java.util.List;
public class AllocationDemo { // first-fit free list: gaps as {start, size} static int checks = 0;
static int firstFit(List<int[]> gaps, int size) { for (int[] gap : gaps) { checks++; if (gap[1] >= size) { int at = gap[0]; gap[0] += size; gap[1] -= size; return at; } } return -1; }
public static void main(String[] args) { List<int[]> gaps = new ArrayList<>(); for (int start = 0; start < 100; start += 10) { gaps.add(new int[] {start, 2}); // ten small gaps of 2 slots each } gaps.add(new int[] {100, 50});
int[] sizes = {3, 3, 1, 3}; for (int size : sizes) { System.out.println("free list: size " + size + " at slot " + firstFit(gaps, size)); } System.out.println("free list: gaps checked = " + checks);
int top = 0; // bump pointer after compaction for (int size : sizes) { System.out.println("bump: size " + size + " at slot " + top); top += size; } }}free list: size 3 at slot 100 free list: size 3 at slot 103 free list: size 1 at slot 0 free list: size 3 at slot 106 free list: gaps checked = 34 bump: size 3 at slot 0 bump: size 3 at slot 3 bump: size 1 at slot 6 bump: size 3 at slot 7
What this code does
- With a fragmented free list, each 3-slot request walks past ten 2-slot gaps before it finds the big one: 34 checks for four allocations, and the checks grow with fragmentation.
- With one free block, allocation is "place at
top, add the size". HotSpot does exactly this inside each TLAB, which is why creating an object is so cheap.
After compaction or copying, the free space is one block. Allocating then needs only a bump pointer: the address where free space starts. The new object goes at that address, and the pointer moves forward by the object's size. That is why new in Java is usually very cheap, often cheaper than malloc in C.
Thread-local allocation buffers (TLABs)
A thread-local allocation buffer (TLAB) is a small chunk of the area where new objects are created, handed to one thread for its own use. Inside its TLAB, a thread bump-allocates without any lock, because no other thread allocates there.
java -XX:+PrintFlagsFinal -version | grep UseTLAB bool UseTLAB = true {product} {default}When a TLAB is full, the thread asks for a new one; only that request touches shared state. Objects too large for a TLAB are allocated outside it. HotSpot turns TLABs on by default (UseTLAB is true on Java 17 and 21), and resizes them per thread as the program runs.
findstr UseTLAB instead of grep UseTLAB.Next step
Check your understanding
12 quick questions