Skip to content

How the garbage collector finds garbage

Working knowledgeUnder the hood

You call new all day and never free anything, yet a Java program can run for months. The garbage collector does not look for garbage at all: it finds everything still reachable and reclaims the rest, and it is cheapest for objects that die young.

01 The question

In this handler, most orders become useless the moment handle returns. A few are kept in CACHE for good. Nobody writes free(order). How does the JVM tell the two apart?

Shop.java
class Shop {
static final List<Order> CACHE = new ArrayList<>();
void handle(Request req) {
Order order = new Order(req); // garbage once handle() returns...
if (order.isVip()) {
CACHE.add(order); // ...unless something keeps it
}
}
}

The answer is not "the object is no longer used". The JVM cannot know what you will use. It uses a stricter, checkable rule: can the program still reach this object?

02 Start from the roots

A root is a reference the program can use directly, without going through another object. Everything reachable by following references from a root is live. Everything else is garbage, because no line of your code can ever get to it again.

  • Local variables and parameters in the frames of every running thread, such as order above.
  • Static fields of loaded classes, such as CACHE.
  • A few the JVM holds itself: references held by native code through JNI, objects used as locks right now, and similar.

Note what is not on the list: the object's own fields. An object that refers to others but is not itself reachable keeps nothing alive.

03 Mark what is reachable, sweep the rest

The classic algorithm has two phases. Mark: walk the references from every root and set a mark bit on each object reached. Sweep: go through the heap and free every object without a mark. Here it is on a heap of seven objects.

Mark from the roots, then sweep
Step 1 of 10
Freed 0
heap · roots on the left
orderlocal
CACHEstatic
A
B
C
D
E
F
G
mark stack
Empty
  • root
  • not marked
  • marked live
  • scanning its fields
  • just pushed
  • freed

A collection starts. Every object's mark bit is clear, and the mark stack is empty. The two roots are a local variable order in a running frame and a static field CACHE.

0 marked

The sweep drawn here is the textbook version, which leaves free gaps scattered across the heap. HotSpot's current collectors (G1, Parallel, ZGC) instead move the live objects together, by compacting or copying, so free space stays in one piece. The marking is the same idea.

04 Why cycles are no problem

F and G kept references to each other and were still freed. A collector that counts references would have kept them forever.

Counting referencesLeaks cyclesF and G each have one incoming reference, so neither count reaches zero. CPython counts references and needs a separate cycle detector for this case.
Tracing from rootsFrees cyclesNo root leads to F or G, so neither gets a mark, however they point at each other. The JVM traces.

05 Why young objects are cheap

Look at the cost of marking: it follows live objects only. Dead objects are never visited. That pays off because of a pattern seen in almost every program, the weak generational hypothesis: most objects die very young. Think of the order above, iterators, temporary strings, boxed numbers.

So HotSpot splits the heap in two. New objects go into a young generation, collected often and fast. Objects that survive several young collections (at most 15 by default, -XX:MaxTenuringThreshold) are promoted to the old generation, which is collected far less often. Here is the classic young layout, as in the Serial and Parallel collectors; G1 does the same with the young generation split into regions.

A minor GC in the young generation
Step 1 of 11
Copied 0
Eden · new objects
top0
1
2
3
4
5
Survivor space
0
1
2
  • just allocated or copied
  • allocated
  • reached: live
  • unreached: dead
  • copied out
  • free

A fresh Eden. Allocation keeps one pointer, top, at the first free byte.

0 of 6 eden used

One catch: an old object may point at a young one, and that young object must survive. Scanning the whole old generation each time would undo the savings, so the JVM records old-to-young references as they are written (a card table, with a small write barrier on every reference store) and treats those as extra roots.

Collecting the whole heapWork grows with live dataEvery live object everywhere is marked, including long-lived caches that never change.
Minor GC of the young genWork grows with survivorsIf 98 of 100 new objects are dead, it copies 2 and frees the other 98 by resetting a pointer.

06 Watch the collector work

-Xlog:gc (JDK 9 and later) prints one line per collection. This program makes about half a gigabyte of short-lived arrays while keeping only 16 alive at a time:

Garbage.java
public class Garbage {
static byte[][] recent = new byte[16][];
public static void main(String[] args) {
for (int i = 0; i < 5_000_000; i++) {
// Each array stays reachable for 16 rounds, then becomes garbage.
recent[i % 16] = new byte[100];
}
System.out.println("done");
}
}
Shell
$ javac Garbage.java
$ java -Xmx64m -Xlog:gc Garbage
[0.004s][info][gc] Using G1
[0.020s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->1M(64M) 0.278ms
[0.022s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 38M->1M(64M) 0.184ms
[0.023s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 38M->1M(64M) 0.134ms
...
done

Read a line as: young collection number 0, heap use went from 23 MB to 1 MB (out of 64 MB), and the program was paused for about a quarter of a millisecond. Almost everything in the young generation was dead, so each pause was tiny. Timings vary by machine; this run was JDK 17 on a laptop, where G1 is the default collector.

If you write byte[] tmp = new byte[100]; and never let tmp leave the loop, you may see no GC lines at all. HotSpot's JIT can prove the array never escapes and skip the heap entirely (escape analysis). Storing it in a field, as above, forces a real allocation.

07 When it bites

A Java memory leak is not memory the JVM lost track of. It is memory you still refer to. The collector will never free an object a root can reach, however useless it is to you.

static Map<Id, Session> SESSIONSCaches that only growA static field is a root, so everything in the map stays live forever. Remove entries, bound the size, or use a cache library with eviction.
button.addListener(this)Listeners never removedThe long-lived object keeps a reference to every listener, and each listener keeps everything it refers to.
threadLocal.set(bigObject)ThreadLocals in thread poolsPool threads live as long as the pool, and so does their thread-local value. Call remove() when the task ends.
System.gc()Asking for a collectionIt is only a request, and it usually triggers a full, slow collection. The JVM already collects when it needs to.
protected void finalize()Relying on finalizersThey may run late or never, and they delay freeing. Deprecated since JDK 9. Use try-with-resources to release files and sockets.

08 Check yourself

Question

Objects F and G refer only to each other. No root reaches either. What happens at the next collection that covers them?

Question

A minor GC runs on a young generation of 1,000 objects. 10 are still reachable. Its work is closest to proportional to…

Question

A heap dump shows a static HashMap holding millions of old entries. Why doesn't the collector free them?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?