Garbage collection review: trace the garbage
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Garbage collection questions in tests and interviews come down to one skill: following references from the roots, line by line, and knowing which popular beliefs about GC are wrong. With those two, the rest of the module (generations, kinds of collections, pauses) fits into place.
Mark which objects become garbage line by line
Go through the code one line at a time and ask one question after each line: which objects just lost their last path from a root? Those, and everything reachable only through them, are now eligible for collection.
Example 1 · Tracing a hostel allotment line by line
import java.util.ArrayList;import java.util.List;
class Student { String name; Room room;
Student(String name) { this.name = name; }}
class Room { static int created = 0; String number; Student occupant;
Room(String number) { this.number = number; created++; }}
public class HostelTraceDemo { static List<Room> allotted = new ArrayList<>();
static Room allot(String name, String number) { Student s = new Student(name); Room r = new Room(number); r.occupant = s; s.room = r; return r; }
public static void main(String[] args) { Room a = allot("Asha", "A-101"); Room b = allot("Bala", "B-202"); allotted.add(a); b = null; // line 4: B-202 + Bala: an island, eligible Room c = allot("Chitra", "C-303"); c = allot("Dev", "D-404"); // line 6: C-303 + Chitra eligible a = null; // line 7: A-101 still in the static list
List<String> reachable = new ArrayList<>(); for (Room r : allotted) { reachable.add(r.number + " (" + r.occupant.name + ")"); } reachable.add(c.number + " (" + c.occupant.name + ")"); System.out.println("Rooms created: " + Room.created); System.out.println("Reachable: " + reachable); System.out.println("Eligible rooms: " + (Room.created - reachable.size())); }}Rooms created: 4 Reachable: [A-101 (Asha), D-404 (Dev)] Eligible rooms: 2
What this code does
- Line 4 makes B-202 and Bala an island of isolation: they still point at each other, but no root reaches them. Line 6 does the same to C-303 and Chitra by pointing
cat a new room. - Line 7 removes one path to A-101, yet the static list
allottedstill holds it, so Asha's room stays. Note the program counts rooms instead of listing all of them: a list of every room would itself keep them reachable. - Line 3 adds A-101 to the static list, so it now has two paths: the local
aand the list.
Watch for these cases:
- Reassigning or nulling a variable removes one path; the object is eligible only if no other path is left.
- When a method returns, its locals disappear, but an object it returned or stored in a field or collection lives on.
- Objects that refer only to each other are an island of isolation: a group with references inside it but no path from a root. The whole island is garbage.
- String literals stay reachable while their class is loaded, so a literal like
"Asha"does not become garbage when a variable stops using it.
Common wrong ideas: setting to null everywhere, calling System.gc()
Setting every variable to null at the end of a method does nothing useful: the locals disappear when the method returns anyway.
Example 2 · Where null really matters: an array-based stack
class OrderStack { private Object[] items = new Object[10]; private int size = 0; private final boolean clearOnPop;
OrderStack(boolean clearOnPop) { this.clearOnPop = clearOnPop; }
void push(Object order) { items[size++] = order; }
Object pop() { Object order = items[--size]; if (clearOnPop) { items[size] = null; // drop the stack's own reference } return order; }
int staleSlots() { // popped orders the array still holds int count = 0; for (int i = size; i < items.length; i++) { if (items[i] != null) { count++; } } return count; }}
public class StaleReferenceDemo { public static void main(String[] args) { for (boolean clear : new boolean[] {false, true}) { OrderStack stack = new OrderStack(clear); for (int i = 1; i <= 5; i++) { stack.push("Order-" + i); } for (int i = 0; i < 3; i++) { stack.pop(); } System.out.println("clearOnPop=" + clear + ": popped orders still held = " + stack.staleSlots()); } }}clearOnPop=false: popped orders still held = 3 clearOnPop=true: popped orders still held = 0
What this code does
- After three pops, the leaky stack still keeps the three popped orders in its array. The program can never use them again, but they are reachable through the stack, so the collector must keep them.
- Setting
items[size] = nullinpopis the kind of nulling that matters: the reference lives in a long-lived array, not in a local that is about to disappear.ArrayList.removedoes the same inside the JDK.
Example 3 · The cost of calling System.gc() in a loop
import java.util.ArrayList;import java.util.List;
public class GcCallCostDemo { public static void main(String[] args) { List<int[]> marks = new ArrayList<>(); for (int i = 0; i < 100; i++) { marks.add(new int[25_000]); // about 10 MB of live data in all }
long start = System.nanoTime(); for (int i = 0; i < 20; i++) { System.gc(); // "helping" the GC: a full GC each time } long ms = (System.nanoTime() - start) / 1_000_000; System.out.println("20 calls to System.gc(): " + ms + " ms"); System.out.println("Live arrays kept: " + marks.size()); }}20 calls to System.gc(): 34 ms Live arrays kept: 100
What this code does
- Nothing became garbage, yet 20 calls cost 34 ms, close to 2 ms each: each one ran a full, stop-the-world GC that marked and compacted the 10 MB of live arrays again. In a server, every call would freeze all request threads.
- Times differ per machine (this run: HotSpot, Java 21, G1). With
-XX:+DisableExplicitGCthe same loop printed 0 ms. A bigger live heap makes every call slower.
Nulling matters only for references that outlive their use: a slot in your own array-based stack or cache, a field of a long-lived object, or a big local in a method that keeps running for a long time. Calling System.gc() does not "help" the collector. On HotSpot with G1 each call usually runs a full, stop-the-world collection of the whole heap, so a loop of such calls just adds pauses. Leave the timing to the JVM. Other beliefs to drop: "objects in a cycle leak" (they do not), "memory is freed as soon as an object is unreachable" (only at the next collection that covers it), "finalize() is a good place to clean up" (it is deprecated and may never run), and "a bigger heap fixes memory problems" (it hides a leak for a while).
Find the bug
Spot the useless or harmful line
Tap the line that is wrong, then check the fix.
Which line does nothing useful?
Round 1 of 3Mixed questions across the module
The whole module in one chain, the way a GC log tells it:
- New objects are bump-allocated in eden, inside each thread's TLAB.
2.
Example 4 · Reading a G1 log end to end
public class LogReviewDemo { static String advice(String line) { if (line.contains("Pause Full (System.gc())")) { return "full GC from System.gc(): remove the call"; } else if (line.contains("Pause Full")) { return "full GC: check live data size and leaks"; } else if (line.contains("Evacuation Failure")) { return "no room to copy: heap nearly full"; } else if (line.contains("(Mixed)")) { return "mixed: young plus old regions, normal"; } else if (line.contains("Concurrent Start")) { return "young, and old-generation marking starts"; } else if (line.contains("Pause Young")) { return "young (minor): normal"; } else if (line.contains("Pause Remark") || line.contains("Pause Cleanup")) { return "short marking pause, normal"; } return "concurrent work, no pause"; }
public static void main(String[] args) { String[] log = { "GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->20M(64M) 13.625ms", "GC(2) Pause Young (Concurrent Start) (G1 Evacuation Pause) 39M->40M(64M) 6.770ms", "GC(3) Concurrent Mark Cycle", "GC(9) Pause Young (Normal) (G1 Evacuation Pause) (Evacuation Failure) 61M->62M(64M) 1.248ms", "GC(11) Pause Full (G1 Compaction Pause) 64M->19M(64M) 5.868ms", "GC(14) Pause Remark 44M->26M(64M) 0.486ms", "GC(16) Pause Young (Mixed) (G1 Evacuation Pause) 38M->38M(64M) 5.800ms", "GC(2) Pause Full (System.gc()) 40M->0M(8M) 3.228ms" }; for (int i = 0; i < log.length; i++) { System.out.println("line " + (i + 1) + ": " + advice(log[i])); } }}line 1: young (minor): normal line 2: young, and old-generation marking starts line 3: concurrent work, no pause line 4: no room to copy: heap nearly full line 5: full GC: check live data size and leaks line 6: short marking pause, normal line 7: mixed: young plus old regions, normal line 8: full GC from System.gc(): remove the call
What this code does
- Lines 1 to 7 are real lines from the 64 MB run of DeliverySessionsDemo in the previous lessons, and line 8 is from the System.gc() demo in the first lesson. Read them in order: young pauses, then marking, then mixed or, when the heap is too small, evacuation failure and a full GC.
- The order of the
ifchecks matters:System.gc()full GCs and evacuation failures are tested before the general cases, just as you would read the cause before the kind.
When eden fills, a young (minor) collection marks from the roots plus remembered sets, copies live objects to a survivor space or, at the tenuring threshold, to the old generation.
- When the old generation fills past a level, G1 marks it concurrently, then runs mixed collections that also evacuate the old regions with the most garbage.
- If G1 runs out of room first, it falls back to a full GC: the whole heap, compacted in one long pause.
- Every pause stops all application threads at a safepoint; marking runs beside them. When a question mixes ideas, place each idea on this chain first.
Interview drill on GC basics
Practise saying these answers out loud in two or three sentences each. The Interview tab has the full versions.
- How the GC finds garbage: tracing from roots (locals, statics, live threads, JNI); unreachable, including cycles, is garbage.
- Why generations: most objects die young, so cleaning the young generation often is cheap.
- Minor, mixed and full: young only; young plus some old regions; the whole heap in one pause.
- Pauses: threads stop at safepoints; G1 marks concurrently; latency, throughput and footprint trade off.
Next step
Check your understanding
12 quick questions