Sub topic 4
How collectors reclaim memory
This chapter assumes you know basic Java, the difference between an object and a reference, and the heap and reachability ideas from the previous chapters. It covers the three core algorithms that every HotSpot collector builds on: mark-sweep, mark-compact, and copying. It also covers the stop-the-world pause and the trade-offs that decide which algorithm fits which job.
The two questions every collector answers
A garbage collector solves two separate problems:
- Which objects are dead? An object is dead when no chain of references leads to it from a GC root. This is the marking phase, and all three algorithms share it.
- What happens to the space the dead objects occupied? Here the algorithms differ. They can leave the space where it is and track it, slide live objects together, or move live objects somewhere else entirely.
The collector never searches for garbage directly. It finds what is live and treats everything else as free. This is why the cost of marking depends on the amount of live data, not on the amount of garbage.
Marking: tracing from the roots
Marking starts at the GC roots: thread stacks, static fields, JNI references, and similar entry points. The collector visits each root, follows every reference it finds, and flags each object it reaches. An object that is already flagged is skipped, so reference cycles do not cause infinite loops.
The following program is a toy mark-sweep over a small object graph. It is a model of the idea, not how HotSpot is implemented. Objects D and E reference each other but nothing reachable references them, so they are collected despite the cycle.
import java.util.ArrayList;
import java.util.List;
public class MarkSweepDemo {
static class Node {
final String name;
final List<Node> refs = new ArrayList<>();
boolean marked;
Node(String name) {
this.name = name;
}
}
static void mark(Node n) {
if (n == null || n.marked) {
return;
}
n.marked = true;
for (Node child : n.refs) {
mark(child);
}
}
public static void main(String[] args) {
Node a = new Node("A");
Node b = new Node("B");
Node c = new Node("C");
Node d = new Node("D");
Node e = new Node("E");
a.refs.add(b);
b.refs.add(c);
d.refs.add(e);
e.refs.add(d); // cycle, but unreachable from the root
List<Node> heap = new ArrayList<>(List.of(a, b, c, d, e));
List<Node> roots = List.of(a);
// Mark phase
for (Node root : roots) {
mark(root);
}
// Sweep phase
heap.removeIf(n -> {
if (!n.marked) {
System.out.println("Swept: " + n.name);
return true;
}
n.marked = false; // reset for the next cycle
return false;
});
System.out.print("Live:");
for (Node n : heap) {
System.out.print(" " + n.name);
}
System.out.println();
}
}The output is:
Swept: D
Swept: E
Live: A B CA real collector uses an explicit mark stack or work queue instead of recursion. A deep linked list would overflow the Java stack with the recursive version above.
Mark-sweep
Mark-sweep runs the mark phase, then walks the whole heap and returns every unmarked region to a free list.
- Strength: live objects never move, so references stay valid and no object needs updating.
- Weakness: fragmentation. Freed regions are scattered between live objects. The heap can have plenty of free bytes in total and still be unable to satisfy a request for one large array, because no single gap is big enough.
- Cost of allocation: the allocator must search the free list for a fitting gap, which is slower than simply advancing a pointer.
- Cost of sweeping: the sweep touches the whole heap, so its time grows with heap size, not with live data size.
Mark-compact
Mark-compact adds a third phase after marking. It slides all live objects toward one end of the heap so they sit side by side, then updates every reference that pointed at a moved object.
- Strength: no fragmentation. Free space becomes one contiguous block, and allocation reduces to bumping a pointer.
- Weakness: compaction is expensive. The collector must compute new addresses, rewrite every reference, and copy the data. Typical implementations make several passes over the heap, and the application must be paused while references are being rewritten.
Copying
A copying collector divides memory into two halves, usually called from-space and to-space. Allocation happens in from-space. When it fills, the collector copies each live object into to-space, leaving a forwarding address behind so that other references to the object can be fixed. When copying finishes, the roles swap, and the old from-space is considered empty in one step.
- Strength: the cost is proportional to the amount of live data. Dead objects are never visited, and the result is compact with no fragmentation.
- Weakness: it needs spare room. A naive two-half design wastes half of the memory. The approach is only attractive when most objects are dead, because then little has to be copied.
That last condition is exactly why copying suits newly created objects, which usually die young. The generational heap in the next chapter applies this idea.
Comparing the three
| Property | Mark-sweep | Mark-compact | Copying |
|---|---|---|---|
| Moves live objects | No | Yes | Yes |
| Fragmentation | Yes | No | No |
| Work proportional to | Whole heap (sweep) | Live data plus heap passes | Live data only |
| Extra memory needed | Little | Little | Reserve space for copies |
| Allocation speed | Slower (free list) | Fast (bump pointer) | Fast (bump pointer) |
| Best when | Most data is long-lived | Long-lived data needs defragmenting | Most objects die quickly |
Stop-the-world pauses
Moving an object while the application reads or writes it would corrupt data. The simplest fix is a stop-the-world (STW) pause: the JVM brings all application threads to a safepoint, runs the collector, then resumes them.
Pause length is the main cost users feel, and it depends on the phase:
- Marking must see a consistent view of the object graph. Tracing a large live set while the application keeps changing references is hard.
- Compacting and copying move objects, so references have to be updated before the application resumes.
Collectors reduce pauses in three ways:
- Parallel: several GC threads do the work at once, which shortens the pause but still stops the application.
- Concurrent: GC threads run alongside application threads for part of the work, usually marking. This needs extra bookkeeping, such as write barriers that record references the application changes during marking.
- Incremental: the work is split into many small pieces, so no single pause is long.
None of these is free. Concurrent collectors use more CPU and often more memory, and they can fall behind. If the application allocates faster than the collector can keep up, the JVM falls back to a long pause or throws an error.
Seeing the algorithms in a real log
You can observe collections with unified logging, which later chapters cover in detail. This command prints each collection as it happens:
java -Xlog:gc -Xmx64m MarkSweepDemoThe demo is too small to trigger a collection, so a program that allocates in a loop is a better target. For now, note what a log line reports: the type of pause, the heap size before and after, and the pause time in milliseconds. A large drop from "before" to "after" means many objects were dead. A small drop with a long pause means most of the heap was live, so the collector did a lot of work to free little.
Common mistakes and edge cases
- Assuming a cycle prevents collection. It does not. Reachability is what matters, as the demo shows. Reference counting systems have this problem, but tracing collectors do not.
- Expecting free memory to mean allocation succeeds. With a non-compacting collector, a large allocation can fail even when the total free space is large, because the free space is fragmented.
- Blaming the collector for a slow program. Pause time and throughput are different measures. A collector that pauses rarely but briefly can still consume more CPU in total than one that stops the application for short regular bursts.
- Thinking collection frees memory back to the operating system. The collector frees space inside the heap. Whether the JVM returns pages to the operating system is a separate decision, tied to heap sizing settings.
- Forgetting that finalization and references add work. Objects with finalizers or special reference types need extra processing after marking, which lengthens collection. The reference types chapter covers this.
Choosing between the approaches
Use these questions to reason about a workload:
- How much of the data survives? If most objects die young, copying is cheap. If most survive, copying wastes effort and a compacting or sweeping approach fits better.
- How sensitive is the application to pauses? A batch job can accept long pauses in return for high throughput. An interactive service usually needs short ones, which favors concurrent work.
- How much spare memory is available? Copying and concurrent collection both need headroom. A tight heap makes them less effective.
- How large is the live set? A large live set makes any full-heap marking or compacting step expensive.
Exercise
A heap has 1 GB of memory, but only 50 MB of it holds live objects. Which costs more to collect with, mark-sweep or copying, and why?
Show answer
Copying costs less here. Its work is proportional to the 50 MB of live data, because dead objects are never visited. Mark-sweep must still sweep through the entire 1 GB to find unmarked regions, so its sweep cost grows with heap size. Mark-sweep would also leave the free space fragmented, while copying leaves it contiguous.
Exercise
In the MarkSweepDemo program, what would happen to node C if you added the line d.refs.add(c); before the mark phase, and why?
Show answer
Node C was already live through A and B, so it stays live. Node D still is not reachable from the root A, so D and E are swept as before. Nothing changes in the output, because a reference from a dead object does not make its target live. Only references reachable from a root count.
Exercise
Why does a mark-compact collector have to update references after moving objects, but a mark-sweep collector does not?
Show answer
Mark-compact changes the address of live objects, so every reference that held the old address must be rewritten to the new one. Mark-sweep never moves live objects, so every existing reference remains valid and only the free list changes.