Java Garbage Collection Explained From Generations Up
How the JVM finds and frees unreachable objects, why most collectors are generational, how G1 and ZGC differ and what pause and throughput really mean.

Java programs never free memory. They allocate with new, drop references and trust the garbage collector to reclaim whatever nothing can reach. That arrangement removes a whole class of bugs, the double free and the use after free, and replaces it with a performance question: when does the collector run, how long does it stop your threads, and how much work does it do? You can answer those questions from a log line, and once you can read the log, most tuning advice becomes obvious or unnecessary.
This post builds the model from the ground up: what counts as garbage, why the heap is split into generations, what a collection costs, how the collectors differ and what you do in code to help. The programs ran on JDK 17.0.1 on a 10-core laptop; the model is unchanged in Java 25, apart from the collector defaults noted below.
What counts as garbage
Reachability, not reference counting, decides. The collector starts from a set of roots (local variables in every thread's stack, static fields, active threads, JNI references) and follows references. Everything it reaches is live. Everything else is garbage, including objects that still refer to each other.
This is easy to prove. The program creates two nodes that point at each other, keeps a WeakReference to one of them as a probe (a weak reference does not keep its target alive), and calls System.gc() before and after dropping the variables:
import java.lang.ref.WeakReference;
public class Reach {
static class Node {
Node other;
byte[] pad = new byte[1024];
}
public static void main(String[] args) {
Node a = new Node();
Node b = new Node();
a.other = b;
b.other = a; // a cycle: each refers to the other
WeakReference<Node> probe = new WeakReference<>(a);
System.gc();
System.out.println("while a is a local variable: " + (probe.get() != null ? "alive" : "collected"));
a = null;
b = null; // no root reaches the cycle any more
System.gc();
System.out.println("after both references dropped: " + (probe.get() != null ? "alive" : "collected"));
}
}while a is a local variable: alive
after both references dropped: collectedThe cycle survived while a stack variable pointed at it and died the moment the last root went. A reference-counting scheme would have kept both nodes forever, since each has one incoming reference. The corollary is the more important one for production: a memory leak in Java is not memory the collector forgot about. It is an object that something still reaches, usually a static map or a listener list, so the collector correctly keeps it. See capturing a heap dump for finding the root that holds it.
The generational hypothesis
Measure the lifetime of objects in almost any program and you find the same shape: most die almost immediately (a temporary string, an iterator, a request-scoped DTO), and a small fraction live for a long time (caches, connection pools, configuration). This observation is called the generational hypothesis, and every production collector in HotSpot is built on it.
The heap is divided accordingly. New objects go into the young generation. A young collection runs when it fills: the collector finds what is still reachable in that area, copies the survivors elsewhere and declares the whole region free. After surviving enough young collections, an object is promoted to the old generation, which is collected far less often.
The key to the economics is that a copying collection costs time proportional to the live objects, not to the garbage. If a young area holds 68 MB and 3 MB of it survives, the collector copies 3 MB and reclaims 65 MB for free. Here is that, from the GC log of a program that allocates short-lived arrays and keeps one in forty:
java -Xmx256m -XX:+UseSerialGC -Xlog:gc Churn[0.034s][info][gc] GC(0) Pause Young (Allocation Failure) 68M->3M(247M) 2.066ms
[0.057s][info][gc] GC(1) Pause Young (Allocation Failure) 71M->64M(247M) 12.685msRead the first line left to right. "Pause Young" is the kind of collection, "Allocation Failure" is the trigger (the young area was full, which is the normal reason), 68M->3M is the heap occupied before and after, (247M) is the heap's total committed size and 2.066ms is how long the application was stopped. A young pause of 2 ms freed 65 MB. The second line shows the other side of the cost: this time 64 MB survived, because the program's retained list grew, and the pause cost 12.7 ms. The collector's work followed the survivors, not the garbage.
Pauses and throughput
Two numbers describe collector behavior, and they pull against each other.
Pause time is how long your threads stop while the collector works. It shows up as latency: one request, once every few minutes, taking 400 ms longer than the rest.
Throughput is the fraction of total time spent running your code instead of the collector's. A collector that does more of its work while the application runs (concurrently) has shorter pauses, but it spends CPU on bookkeeping, which lowers throughput.
A batch job wants maximum throughput and does not care about one long stop. An interactive service wants pauses small enough to hide inside normal request variation. That is the whole design space, and the choice of collector is a choice of where you sit in it.
The collectors in one paragraph each
- Serial collects with one thread and stops the world. It has the smallest footprint and is the automatic choice on machines with fewer than two CPUs.
- Parallel does the same with many threads, which gives the best throughput and the longest pauses. It suits batch work.
- G1 is the default since Java 9. It divides the heap into regions, collects the ones with the most garbage first and tries to meet a pause goal (
-XX:MaxGCPauseMillis, 200 ms by default). It is the right starting point for most services. - ZGC does nearly all its work concurrently, giving pauses of a millisecond or less independent of heap size, at some cost in CPU. It became generational in JDK 21 and generational by default in JDK 23.
- Shenandoah has the same aim by a different mechanism, and ships in many distributions.
The comparison with measurements from a benchmark is in G1 against ZGC, Shenandoah and Parallel.
What allocation looks like
Allocation in HotSpot is cheap, and understanding why helps you stop worrying about new. Each thread has a thread-local allocation buffer (TLAB), a private slice of the young generation. Allocating an object is a pointer bump inside that slice, roughly a handful of instructions with no lock. When the slice is full the thread asks for another. When the young area is full, a collection runs. This is why creating a short-lived object is close to free, and why the cost of a hot allocation shows up elsewhere: more allocation means more frequent young collections, and each one promotes a few more objects.
You can see how much your code allocates without any special tool. Compare heap usage across a loop:
long before = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
// ... run the code under test many times ...
long after = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();That is crude, because a collection may run in between. For real numbers, record with Java Flight Recorder and read the allocation events:
java -XX:StartFlightRecording=duration=60s,filename=app.jfr -jar app.jar
jfr print --events jdk.ObjectAllocationSample app.jfr | head -30The samples name the stack trace that allocated the most. The first line of the top stack is where to look.
What you can do as a developer
You do not tune the collector from application code, but you decide what it has to do. In order of payoff:
- Allocate less in hot paths. Avoid boxing in loops (
longinstead ofLong), build strings with aStringBuilderinstead of repeated concatenation, and reuse buffers rather than allocating one per call. - Keep object lifetimes either very short or very long. The expensive case is the medium-lived object that survives a few young collections and then dies in the old generation, such as a 30 second cache entry in a 5 second collection cycle. Tune the cache size and TTL, not the GC.
- Do not hold what you do not need. A reference in a static field or a long-lived collection keeps the whole graph beneath it alive.
- Avoid finalizers and
Cleanerfor anything that is not a last-resort safety net; they delay reclamation. Usetry-with-resources for files and connections. - Prefer streaming to materializing. Reading a result set row by row keeps memory flat;
findAll()followed by aListof ten million entities does not. - Set the heap size deliberately. Fix
-Xmsequal to-Xmxin production services so the heap does not resize, and leave headroom of two to three times the live set. The error you meet when you do not is covered in GC overhead limit exceeded.
Where this overview stops
This is the model, not a tuning guide. How to read the log lines for real problems is in reading GC logs, the memory outside the heap that a collector does not manage is in JVM memory areas, and the flag-level documentation is in the HotSpot garbage collection tuning guide. For the generational ZGC design see JEP 439. If your workload allocates nothing in steady state, such as a tight numeric loop, the collector is not your problem and this post can end here.


