Skip to lesson

Garbage collection practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Garbage collection becomes clear once you can do three things by hand: count what becomes garbage after each line, explain why something stays reachable, and read what the collector did in a real log. Each section below gives you a worked program for one of them, and the Practice tab has more.

Count eligible objects after each line

Keep a running count. After each line, cross out every reference the line removed or replaced, then follow the remaining references from the local variables and static fields. Any object you cannot reach is eligible, together with everything reachable only through it.

Example 1 · Counting eligible objects in a train booking

EligibleCountDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.HashSet;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;import java.util.TreeSet;
class Obj {    String name;    Map<String, Obj> fields = new LinkedHashMap<>();
    Obj(String name) {        this.name = name;    }}
class Tracker {    List<Obj> created = new ArrayList<>();    Map<String, Obj> vars = new LinkedHashMap<>();
    Obj create(String name) {        Obj o = new Obj(name);        created.add(o);        return o;    }
    Set<String> garbage() {        Set<Obj> marked = new HashSet<>();        Deque<Obj> toVisit = new ArrayDeque<>();        for (Obj root : vars.values()) {            if (root != null) {                toVisit.push(root);            }        }        while (!toVisit.isEmpty()) {            Obj o = toVisit.pop();            if (marked.add(o)) {                for (Obj next : o.fields.values()) {                    if (next != null) {                        toVisit.push(next);                    }                }            }        }        Set<String> dead = new TreeSet<>();        for (Obj o : created) {            if (!marked.contains(o)) {                dead.add(o.name);            }        }        return dead;    }
    void after(int line) {        Set<String> dead = garbage();        System.out.println("after line " + line + ": eligible = " + dead.size() + " " + dead);    }}
public class EligibleCountDemo {    public static void main(String[] args) {        Tracker t = new Tracker();        Obj pnr1 = t.create("PNR1");        t.vars.put("b1", pnr1);        pnr1.fields.put("passenger", t.create("Asha"));        t.after(2);        Obj pnr2 = t.create("PNR2");        t.vars.put("b2", pnr2);        pnr2.fields.put("passenger", t.create("Bala"));        t.after(3);        t.vars.put("b1", t.vars.get("b2"));                       // line 4: b1 = b2        t.after(4);        pnr2.fields.put("passenger", null);                       // line 5: b2.passenger = null        t.after(5);        t.vars.put("b2", null);        t.after(6);        t.vars.put("b1", null);                                   // line 7: b1 = null        t.after(7);    }}
Output
after line 2: eligible = 0 []
after line 3: eligible = 0 []
after line 4: eligible = 2 [Asha, PNR1]
after line 5: eligible = 3 [Asha, Bala, PNR1]
after line 6: eligible = 3 [Asha, Bala, PNR1]
after line 7: eligible = 4 [Asha, Bala, PNR1, PNR2]

What this code does

  • Line 4 points b1 at PNR2, so PNR1 loses its only path, and Asha with it: two objects at once. Line 5 cuts the only path to Bala.
  • Line 6 changes nothing, because b1 still refers to PNR2. Only line 7 removes its last path. Write the comments in your own traces the same way: line, change, new count.
  • Lines 1 to 3 build the heap: b1 gets new Booking("PNR1") with passenger Asha, and b2 gets new Booking("PNR2") with passenger Bala.

The model below does exactly that with a small tracker: vars holds the local variables (the roots), fields holds each object's references, and garbage() marks from the roots. It is a model of the rules, not of HotSpot itself, but it gives the same answers you should get by hand.

Reachability through static fields and collections

A static field is a GC root, and a collection keeps every element it holds reachable. So static List<Report> reports keeps every report in it alive for as long as the class is loaded, which in most programs means until the JVM stops.

Example 2 · A static cache in a college ERP keeps every report alive

ReportCacheDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
class Report {    static int created = 0;    String batch;    int[] marks = new int[1000];
    Report(String batch) {        this.batch = batch;        created++;    }}
public class ReportCacheDemo {    static Map<String, List<Report>> cache = new HashMap<>();     // a static field: a root
    static void runBatch(String batch, int students) {        List<Report> reports = new ArrayList<>();        for (int i = 0; i < students; i++) {            reports.add(new Report(batch));        }        cache.put(batch, reports);    }
    static int reachable() {        int count = 0;        for (List<Report> list : cache.values()) {            count += list.size();        }        return count;    }
    public static void main(String[] args) {        runBatch("CSE-2025", 120);        runBatch("ECE-2025", 90);        runBatch("MECH-2025", 60);        System.out.println("Reports created: " + Report.created + ", reachable: " + reachable());
        cache.remove("CSE-2025");                                  // removes one path        System.out.println("After removing CSE: reachable " + reachable());
        cache.clear();                                             // removes all paths        System.out.println("After clear: reachable " + reachable());    }}
Output
Reports created: 270, reachable: 270
After removing CSE: reachable 150
After clear: reachable 0

What this code does

  • Each batch's list is a local in runBatch, but cache.put stores it in a static map, so all 270 reports (each with a 1,000-mark array) stay reachable after the method returns.
  • Only remove and clear cut the path from the static root. A cache that only ever grows is how a college ERP batch job ends in OutOfMemoryError after many batches.

Removing an element from the collection removes that path; clearing the collection removes all of them. The question to ask is not "is the variable still in scope?" but "does any root still lead here, through any field or any collection?". Long-lived collections are the most common place where unused objects stay reachable.

Watch young and full collections with -Xlog:gc

Run a program twice: once with the default heap and once with a small one such as -Xmx24m, both with -Xlog:gc (Java 9 and later). Then count the Pause Young and Pause Full lines and compare the "after" values.

Example 3 · An exam-results rush to watch with -Xlog:gc

ResultRushDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class ResultRushDemo {    public static void main(String[] args) {        Deque<String> recentPages = new ArrayDeque<>();     // pages kept for quick re-views        long chars = 0;        for (int i = 0; i < 1_500_000; i++) {            String page = "Result for roll " + i + ": " + "PASS ".repeat(20);            chars += page.length();            recentPages.addLast(page);            if (recentPages.size() > 50_000) {            // keep only the latest 50,000 pages                recentPages.removeFirst();            }        }        System.out.println("Pages served: 1500000");        System.out.println("Pages kept: " + recentPages.size());        System.out.println("Characters sent: " + chars);    }}
Output
Pages served: 1500000
Pages kept: 50000
Characters sent: 186388890

What this code does

  • 1.5 million result pages are built, but only the latest 50,000 are kept, about 8 MB of live data at any moment. Everything older is garbage.
  • String.repeat is Java 11 and later. The program is safe to run plainly; the next example runs it with GC logging and two heap sizes.

Example 4 · Default heap versus -Xmx24m

Terminal
java -Xlog:gc ResultRushDemojava -Xmx24m -Xlog:gc ResultRushDemo
Sample output
[0.016s][info][gc] Using G1
[0.212s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->8M(118M) 12.374ms
[0.238s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 22M->14M(118M) 9.009ms
[0.283s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 45M->20M(118M) 8.985ms
[0.333s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 85M->23M(118M) 8.359ms
[0.369s][info][gc] GC(4) Pause Young (Normal) (G1 Evacuation Pause) 84M->23M(287M) 8.306ms
[0.522s][info][gc] GC(5) Pause Young (Normal) (G1 Evacuation Pause) 186M->23M(287M) 5.577ms
Pages served: 1500000
Pages kept: 50000
Characters sent: 186388890
...
[0.302s][info][gc] GC(23) Pause Young (Concurrent Start) (G1 Evacuation Pause) 18M->17M(24M) 1.501ms
[0.303s][info][gc] GC(24) Concurrent Mark Cycle
[0.305s][info][gc] GC(25) Pause Young (Normal) (G1 Evacuation Pause) 19M->19M(24M) 1.280ms
[0.306s][info][gc] GC(26) Pause Young (Normal) (G1 Evacuation Pause) 20M->19M(24M) 1.170ms
[0.319s][info][gc] GC(27) Pause Full (G1 Compaction Pause) 19M->8M(24M) 12.875ms
...
[1.087s][info][gc] GC(197) Concurrent Mark Cycle 10.895ms

What this code does

  • With the default heap: 6 young pauses, no mixed and no full GC, and the run ended after about 0.5 s. With -Xmx24m: 152 young and 22 full GCs, and the run took over 1 s.
  • Every full GC ends near 8M: the live data (the 50,000 kept pages) is steady, so there is no leak. The heap is just too small for comfortable young and mixed collections. Your counts will differ.

With room to spare you should see only young pauses. When the live data is close to the heap size, G1 runs out of free regions and full GCs appear, each leaving roughly the same amount of live data behind. That flat "after" value tells you the program is not leaking; it simply needs more memory than you gave it.

Interview questions on generations and pauses

These come up again and again. Say each answer in two or three sentences; the Interview tab has model answers.

  • Why is the heap split into young and old, and what are eden and the survivor spaces?
  • When is an object promoted, and what is premature promotion?
  • What is the difference between minor, mixed and full GC in G1?
  • What is a stop-the-world pause, and what can run concurrently?

Finish up

Mark complete & continue

Next: Serial, Parallel, G1 and ZGC at a glance