Garbage collection
Mid-level Frequently asked 6 min
On this page
The question
How does the garbage collector decide what to collect?
30-second answer
It traces reachability, not age or usefulness. Starting from the GC roots, such as thread stacks and static fields, it follows references and marks every object it reaches. Anything unmarked can never be used again, so its memory can be reclaimed. That is why an unreachable cycle is freed, and why an unused object that is still referenced is not.
Understand it
Objects moving through the generations
Step by stepNew objects start in Eden: A to E here. The young and old generation layout is the classic model; G1 and generational ZGC organize it as regions.
View as text
A heap drawn as rows: Eden and the survivor spaces S0 and S1 make up the young generation, and the old generation sits below. Each object is a box with a letter and its age, the number of minor GCs it survived.
New objects start in Eden: A to E here. The young and old generation layout is the classic model; G1 and generational ZGC organize it as regions. The old generation already holds two long-lived objects, P and Q.
Eden fills, so a minor GC copies the live A, C and E to survivor space S0 at age 1. Dead B and D are simply freed. They stay behind in Eden, dashed and marked freed.
The next minor GC copies the live objects from Eden and S0 into S1, adding 1 to each age. C and the new G died, so they are freed. A and E are now age 2, and the new F lands in S1 at age 1.
A and E reached the tenuring threshold, 2 here, so the next minor GC promotes them to the old generation. HotSpot's default maximum is 15. F is copied back to S0 at age 2, and the dead H is freed from Eden.
When the old generation fills, a major GC marks every object reachable from the GC roots and frees the rest, here A and Q. It is rarer and slower. Arrows lead from the GC roots to P and E, which are marked and drawn as live.
A heap drawn as rows: Eden and the survivor spaces S0 and S1 make up the young generation, and the old generation sits below. Each object is a box with a letter and its age, the number of minor GCs it survived.
New objects start in Eden: A to E here. The young and old generation layout is the classic model; G1 and generational ZGC organize it as regions. The old generation already holds two long-lived objects, P and Q.
Eden fills, so a minor GC copies the live A, C and E to survivor space S0 at age 1. Dead B and D are simply freed. They stay behind in Eden, dashed and marked freed.
The next minor GC copies the live objects from Eden and S0 into S1, adding 1 to each age. C and the new G died, so they are freed. A and E are now age 2, and the new F lands in S1 at age 1.
A and E reached the tenuring threshold, 2 here, so the next minor GC promotes them to the old generation. HotSpot's default maximum is 15. F is copied back to S0 at age 2, and the dead H is freed from Eden.
When the old generation fills, a major GC marks every object reachable from the GC roots and frees the rest, here A and Q. It is rarer and slower. Arrows lead from the GC roots to P and E, which are marked and drawn as live.
Takeaway: Most objects die young, so the JVM collects the young generation often and cheaply, and promotes long-lived survivors to the old generation, which it collects rarely.
What the GC roots keep alive
Tap the partsSelect a part to see what it does.
Tap a part to see why the GC keeps it or frees it.
View as text
Two GC roots at the top, each with arrows to the objects it reaches, and two objects at the bottom that nothing reaches.
Thread stacks: the local variable order in main() is a root, with an arrow to an Order object, which has an arrow to a Customer object.
Static fields: the static field CACHE is a root, with an arrow to a HashMap.
Reachable object: Order and Customer are marked reachable, because a chain of references leads to each from a root.
Leaking cache: the HashMap has arrows to two Session objects marked unused. They are never used again, but they stay reachable, so the GC must keep them.
Unreachable cycle: Cart and Item, drawn dashed and marked unreachable, have arrows to each other but no arrow from a root, so the GC frees both.
Two GC roots at the top, each with arrows to the objects it reaches, and two objects at the bottom that nothing reaches.
Thread stacks: the local variable order in main() is a root, with an arrow to an Order object, which has an arrow to a Customer object.
Static fields: the static field CACHE is a root, with an arrow to a HashMap.
Reachable object: Order and Customer are marked reachable, because a chain of references leads to each from a root.
Leaking cache: the HashMap has arrows to two Session objects marked unused. They are never used again, but they stay reachable, so the GC must keep them.
Unreachable cycle: Cart and Item, drawn dashed and marked unreachable, have arrows to each other but no arrow from a root, so the GC frees both.
Takeaway: The GC frees only what no root can reach. A cycle does not save an object, but a forgotten reference, like a static cache entry, does.
In code
record Session(String user, byte[] data) {}
class Sessions {
private static final Map<String, Session> CACHE = new HashMap<>();
static void login(String user) {
CACHE.put(user, new Session(user, new byte[1_000_000]));
}
static void logoutLeaky(String user) {
Wrong System.out.println(user + " logged out"); // the entry stays in CACHE
}
static void logout(String user) {
Right CACHE.remove(user); // no reference left
}
}class Node { Node next; }
Node a = new Node(), b = new Node();
a.next = b;
b.next = a; // a cycle
var probe = new WeakReference<>(a); // does not keep a alive
a = null;
b = null; // no root reaches the cycle now
System.gc(); // a request, not a guarantee
System.out.println(probe.get()); // typically nulljava -XX:+UseG1GC -Xms2g -Xmx2g -Xlog:gc*:file=gc.log -jar app.jar # G1 (Garbage-First): the default since Java 9
java -XX:+UseZGC -Xmx16g -jar app.jar # ZGC (Z Garbage Collector): sub-millisecond pauses on large heapsSolve it
The heap grows for days, then OutOfMemoryError: find the leak
An order service runs fine after a deploy, but three days later it fails with “Java heap space”. Restarting fixes it for another three days. Find the cause and prove the fix.
- Tell a leak from a small heap. In the GC log, look at the heap right after each full or mixed collection. If that floor keeps rising under steady load, live objects accumulate: a leak.
- Capture the evidence. Start with
-XX:+HeapDumpOnOutOfMemoryError, or take a dump from the running process withjcmd. - Read the dump. Open it in Eclipse MAT (Memory Analyzer Tool) or VisualVM. The dominator tree shows a
HashMapheld by a static field, a GC root, with millions of entries that are never removed. - Fix the owner. Bound the cache by size or age, or remove entries when they stop being needed.
- Prove it. Run the same load for hours: the floor after each collection now stays flat.
jcmd 4242 GC.heap_dump /tmp/orders.hprof # 4242 is the process id from `jcmd -l`
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp -jar orders.jarclass LruCache<K, V> extends LinkedHashMap<K, V> {
private final int max;
LruCache(int max) { super(16, 0.75f, true); this.max = max; } // true: access order
@Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > max; }
}
static final Map<String, Session> SESSIONS = Collections.synchronizedMap(new LruCache<>(10_000));How to answer
- GC roots include local variables on thread stacks and the static fields of loaded classes.
- An object is live if a chain of references leads to it from a root.
- A cycle with no path from a root is garbage, because tracing never counts references.
- Reachable does not mean needed: a forgotten reference keeps an object alive.
- The JVM (Java Virtual Machine) chooses when to collect, so you cannot predict when an object is freed.
Common mistakes
- Saying an object is freed when its reference count reaches zero.
- Saying that setting a variable to null frees the object immediately.
Follow-up questions
What are the generations of the Java heap, and why do they exist?
Most objects die young, so the heap is split by age. New objects start in Eden, in the young generation. A minor GC copies the few survivors to a survivor space, which is cheap because dead objects are never copied. Objects that survive long enough are promoted to the old generation, which a major GC collects less often.
- The classic young generation is Eden plus two survivor spaces, one of them empty between collections.
- Each minor GC an object survives adds 1 to its age.
- At the tenuring threshold, at most 15 by default in HotSpot, the object is promoted.
- G1 and generational ZGC keep the generations but organize them as regions.
See it in the infographic: Objects moving through the generations
How do G1 and ZGC differ, and when would you choose each?
G1, the default since Java 9 on server-class machines, collects regions in stop-the-world pauses aimed at a target, 200 ms by default. ZGC does nearly all its work concurrently, so pauses typically stay under a millisecond even on large heaps, at the cost of extra CPU and memory. Start with G1; choose ZGC when latency matters most.
MaxGCPauseMillisdefaults to 200 in G1, and it is a goal, not a guarantee.- ZGC relocates objects while the application keeps running.
- Generational ZGC arrived in Java 21 behind
-XX:+ZGenerational, became the default mode in 23 and the only mode in 24. - Select ZGC with
-XX:+UseZGC, and measure on your own workload before switching.
See it in the infographic: Objects moving through the generations
Can a Java program leak memory even with garbage collection?
Yes. The GC frees only what is unreachable, so an object you no longer need but still reference stays. The classic case is a static collection that only grows, such as a cache with no eviction. The symptom is old generation use climbing after every collection, and eventually an OutOfMemoryError.
- A Java memory leak is a reachable object that nothing will use again.
- Common sources are static collections, listeners never removed and
ThreadLocalvalues on pooled threads. - Fix it by removing entries or bounding the cache with eviction.
- Diagnose it with a heap dump, following the path from the object to its GC root.
class GrowForever {
private static final Map<Integer, byte[]> CACHE = new HashMap<>();
public static void main(String[] args) {
for (int i = 0; ; i++) CACHE.put(i, new byte[1_000_000]);
}
}
// java -Xmx64m GrowForever: OutOfMemoryError: Java heap space Does System.gc() force a collection?
No, it is a request. The Javadoc promises only a best effort, and -XX:+DisableExplicitGC turns the call into a no-op. By default G1 answers it with a full, stop-the-world collection, which is a good reason not to call it in production code.
Why doesn't Java use reference counting?
Counting cannot free a cycle, because each object in it keeps the other's count above zero. It also adds a counter update to every reference assignment, which is costly when threads share objects. Tracing handles cycles and does its work during collections.
Check yourself
Show answers
- A collection can free both: Correct. Tracing starts at the roots, so neither object is reached.
- They stay until one reference is set to null: Incorrect. References between unreachable objects do not count.
- The JVM throws an error at the next collection: Incorrect. A cycle is ordinary garbage, and nothing is thrown.
Show answers
- In the old generation: Correct. Reaching the threshold means the object is promoted.
- Back in Eden: Incorrect. Eden receives only new objects, and collection leaves it empty.
- In the other survivor space: Incorrect. That is what happens before the threshold, not at it.