free(), and a program that creates millions of objects does not run out of memory, because a part of the JVM called the garbage collector (GC) finds objects that nothing can reach any more and reuses their space. That works so well that most developers never look at it until something goes wrong: a request that sometimes takes half a second instead of ten milliseconds, a container killed for using too much memory, an OutOfMemoryError in the middle of the night.
This article explains it in the order a first-time reader needs it: where objects live, how the collector decides that something is garbage, why the heap is split by age, what the collectors that ship with the JDK do differently, and what happens when the same program runs under each of them. Everything here was run on real JVMs: JDK 25 (the current long-term-support release), JDK 27, and an early-access build of JDK 28. It is a rewrite of the article that used to live at this address, and the last section lists what the old version got wrong.
What was run, and what was not. Every number and every console block below comes from a file in the companion module (asmhatre/javademos, module gc-basics), regenerated by one script. Versions: Temurin 25.0.5.1 (LTS), Temurin 27.0.1.1 (GA 15 September 2026), and Temurin 28+25, an early-access build of JDK 28 (GA is scheduled for March 2027, so anything seen only there can still change). Timings came from a 2 vCPU sandbox, so read them as shape, not as results. Container behaviour was tested with real docker run --cpus --memory limits. What was not run: multi-terabyte heaps, a real Spring application, and Windows or macOS. Statements about JEPs and release plans come from the OpenJDK and InfoQ pages linked at the end and are marked as documentation, not as observations.
Local variables live on the stack, objects live on the heap, and only the heap needs a collector
When the JVM runs your program it keeps two main kinds of memory for your data. Each thread gets its own stack: a pile of frames, one for every method call that is currently in progress. A frame holds that method’s local variables, which are either plain numbers such asint localValue or references, the addresses of objects. When the method returns, its frame is thrown away at once. Nothing has to go looking for garbage there.
Every object you create with new goes on the heap, one pool of memory shared by all threads. Objects on the heap do not disappear when the method that created them returns. They stay until nothing can reach them any more. That is the only memory the garbage collector manages.
String it holds only an address. The text lives on the heap. When myMethod() returns, the frame vanishes immediately, and the String becomes garbage only if nothing else still points at it. The snippet is in StackAndHeap.java and prints what you would expect:
public void myMethod() {
int localValue = 10; // stored directly on the stack for this method's frame
String message = "Hello"; // the *reference* 'message' is on the stack...
// ...but the String object itself is on the heap (a literal lives in the string pool, also on the heap).
System.out.println(localValue + " " + message);
} // the frame is popped here; 'localValue' and 'message' (the reference) are gone
10 Hello
That output is in 13-small-demos.txt. Once you can see where the collector’s job begins, the next question is how it decides what to remove.
Going deeper: the heap is not the whole process
The heap size you set with -Xmx limits only the heap. The JVM needs more memory than that: space for compiled code, thread stacks, class metadata, and the collector’s own bookkeeping. You can ask a running JVM for the breakdown with -XX:NativeMemoryTracking=summary and jcmd <pid> VM.native_memory summary. Here is a JVM with a 512 MB heap, running G1 on JDK 25, with a 150 MB live set:
Total: reserved=1973775KB, committed=597955KB
Java Heap (reserved=524288KB, committed=524288KB)
GC (reserved=47599KB, committed=47599KB)
Code (reserved=247794KB, committed=7650KB)
Thread (reserved=20545KB, committed=1053KB)
Metaspace (reserved=65548KB, committed=268KB)
Shared class space (reserved=16384KB, committed=13928KB, readonly=0KB)
resident set size of the process, from /proc: 549.477 MB
The collector itself reserved about 47599 KB, close to a tenth of the heap, for its own data structures. In this small program the process uses a little more than its heap, because few classes were loaded. A big Spring application loads many more, so its non-heap share is larger. This is why a container limit must be set higher than -Xmx. The transcript is 16-native-memory.txt.
- How to size heap and limits for containers: JVM Flags for Spring Boot in Containers (JDK 25/27)
- What the JVM is made of: JDK vs JRE vs JVM
- Reference: HotSpot Garbage Collection Tuning Guide, release 25
An object is garbage when no chain of references leads to it from a root
How does the collector know that nobody needs an object? It does not count who points at it. It starts from a small set of always-alive references called GC roots (local variables on thread stacks, static fields, and a few references held by the JVM itself) and follows every reference it finds, marking each object it reaches as alive. This is the mark step. Whatever was never reached is garbage.A is reachable from a local variable, B from a static field, and C through A. D has nothing pointing at it. X and Y point at each other, but no path from a root leads to either of them, so they are garbage too. The program Reach.java builds exactly this graph and then asks, through a WeakReference (a reference that does not keep its target alive), which objects survived a collection:
import java.lang.ref.WeakReference;
/**
* Reachability, observed. A WeakReference does not keep its target alive, so after a full collection
* "get() == null" means "the collector found it unreachable from the roots".
*/
public class Reach {
static class MyObject {
final String name;
MyObject child;
MyObject(String name) { this.name = name; }
}
public static MyObject staticObj; // a GC root: a static field
static WeakReference<MyObject> weak(MyObject o) { return new WeakReference<>(o); }
public static void main(String[] args) throws Exception {
MyObject localObj = new MyObject("A"); // a GC root: a local variable
staticObj = new MyObject("B");
localObj.child = new MyObject("C"); // 'C' is reachable from 'A'
MyObject unreachable = new MyObject("D"); // referenced by nothing once we drop the variable
// An "island": two objects that point at each other, with no path from any root.
MyObject x = new MyObject("X");
MyObject y = new MyObject("Y");
x.child = y;
y.child = x;
var refs = new WeakReference[] { weak(localObj), weak(staticObj), weak(localObj.child), weak(unreachable), weak(x), weak(y) };
String[] names = { "A (local variable)", "B (static field)", "C (child of A)", "D (no references)", "X (cycle with Y, no root)", "Y (cycle with X, no root)" };
unreachable = null;
x = null;
y = null;
System.gc(); // for the demonstration only; see "Forget System.gc() exists" in the article
for (int i = 0; i < refs.length; i++) {
System.out.printf("%-28s %s%n", names[i], refs[i].get() != null ? "alive" : "collected");
}
System.out.println("A and C are still used here: " + localObj.name + " -> " + localObj.child.name);
}
}
A (local variable) alive
B (static field) alive
C (child of A) alive
D (no references) collected
X (cycle with Y, no root) collected
Y (cycle with X, no root) collected
A and C are still used here: A -> C
Transcript: 05-reachability.txt. The System.gc() call is there only to force a collection for the demonstration; the practical-advice section below explains why you should not do it in real code.
A cycle is not a leak. Because the collector asks “can I get there from a root?” and not “does anything point at me?”, two objects that reference each other are still collected. A Java memory leak is the opposite situation: an object you no longer need that is still reachable, for example because it sits in a static list nobody clears. The out-of-memory section below reproduces one.
Going deeper: weak, soft and phantom references, and what counts as a root
A WeakReference is cleared by the next collection once its target has no strong path from a root, which is what the demo above relies on. A SoftReference is, per the documentation, cleared only when the JVM needs memory, which makes it a candidate for caches, and a PhantomReference lets you run cleanup after an object is gone (the Cleaner class is the friendly wrapper). Only the weak reference was executed for this article; the other two are described from the java.lang.ref documentation.
The roots listed above are the ones you meet in everyday code. The JVM also treats things such as loaded classes and native (JNI) references as roots. The old version of this article described the same mark step but called the surviving objects “marked” and then moved straight to a sweep, which is only one of the ways memory is reclaimed afterwards. That comes in two sections.
- Seeing what is reachable in a real application: Debugging OutOfMemoryError: Heap Dumps, Eclipse MAT, and the Five Leak Patterns
- Why
finalize()is not the cleanup you want: final vs finally vs finalize in Java
Most objects die young, so the heap is split by age
Marking the whole heap every time would be slow, so the JVM’s designers made use of an observation known as the weak generational hypothesis: most objects die very soon after they are created (the temporary strings and small objects of a single request), and the few that survive tend to live a long time. So the heap is split by age. New objects are born in the young generation, in a space called Eden. When Eden fills up, the collector runs a short young collection that copies the few live objects into survivor space, or, once they have survived a few rounds, promotes them to the old generation, which is collected rarely.[0.004s][info][gc] Using G1
[0.044s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 26M->25M(512M) 12.661ms
[0.209s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 205M->164M(512M) 88.487ms
[0.244s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 283M->175M(512M) 17.136ms
[0.268s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 318M->176M(512M) 1.967ms
[0.298s][info][gc] GC(4) Pause Young (Normal) (G1 Evacuation Pause) 340M->176M(512M) 2.303ms
[0.332s][info][gc] GC(5) Pause Young (Normal) (G1 Evacuation Pause) 356M->176M(512M) 2.059ms
From 06-g1-log.txt. Reading one line: GC(10) is the eleventh collection since start, Pause Young (Normal) (G1 Evacuation Pause) says it was a routine young collection, and 447M->177M(512M) 8.525ms says the heap went from 447M used to 177M used, out of 512M in total, and the application was stopped for 8.525 ms. In this three-second run G1 did 88 such young collections.
The first pause is the expensive one. Look at GC(1): 205M->164M took 88.487 ms, several times longer than every pause after it. At that moment the program had just built a 150 MB live set, all of it alive, so the collector had to copy all of it out of the young generation. Every later pause reclaimed hundreds of megabytes of dead objects in a few milliseconds, because the work of a young collection is proportional to the survivors, not to the garbage. That one-off cost comes back later, because my first benchmark of the collectors measured only this.
Going deeper: fixed generations, G1 regions, and what jcmd GC.heap_info shows
Serial and Parallel split the heap into fixed spaces: Eden, two survivor spaces (“from” and “to”) and the old generation. Their default proportions are visible as flags (NewRatio=2 means the old generation is twice the young generation, SurvivorRatio=8 means Eden is eight times one survivor space). G1 does not use fixed spaces: it cuts the heap into equal-sized regions and decides each cycle which regions play the part of Eden, survivor or old. ZGC and Shenandoah are also region based. jcmd <pid> GC.heap_info shows the layout of a live process, and it looks different for every collector (full transcript: 09-heap-info.txt):
## -XX:+UseParallelGC
PSYoungGen total 163328K, used 67168K [0x00000000f5580000, 0x0000000100000000, 0x0000000100000000)
eden space 152064K, 37% used [0x00000000f5580000,0x00000000f8c783c8,0x00000000fea00000)
from space 11264K, 96% used [0x00000000ff500000,0x00000000fffa0000,0x0000000100000000)
to space 11264K, 0% used [0x00000000fea00000,0x00000000fea00000,0x00000000ff500000)
ParOldGen total 349696K, used 216440K [0x00000000e0000000, 0x00000000f5580000, 0x00000000f5580000)
object space 349696K, 61% used [0x00000000e0000000,0x00000000ed35e2e0,0x00000000f5580000)
## -XX:+UseG1GC
garbage-first heap total reserved 524288K, committed 524288K, used 214460K [0x00000000e0000000, 0x0000000100000000)
region size 1024K, 24 young (24576K), 15 survivors (15360K)
Parallel prints its fixed spaces (young generation total 163,328 KB of a 512 MB heap, old generation 349,696 KB, roughly the one-to-two split the flag promises). G1 prints only its region size (1024K here) and how many regions are currently young and survivor. The flag defaults below were read from the same JDK 25:
$ java -Xmx1g -XX:+UseG1GC -XX:+PrintFlagsFinal -version | grep ...
uint ConcGCThreads = 1 {product} {ergonomic}
size_t G1HeapRegionSize = 1048576 {product} {ergonomic}
uint InitiatingHeapOccupancyPercent = 45 {product} {default}
uintx MaxGCPauseMillis = 200 {product} {default}
uint ParallelGCThreads = 2 {product} {default}
$ java -Xmx1g -XX:+UseSerialGC -XX:+PrintFlagsFinal -version | grep -E 'NewRatio|SurvivorRatio|MaxTenuringThreshold'
uint MaxTenuringThreshold = 15 {product} {default}
uintx NewRatio = 2 {product} {default}
uintx SurvivorRatio = 8 {product} {default}
That is a 200 ms pause goal for G1, not a promise, and a concurrent cycle that starts when the old generation is 45 percent full. Transcripts: 09-heap-info.txt and 17-flag-defaults.txt. The same command for ZGC and Shenandoah is in the first file.
- Choosing and tuning each collector: HotSpot Garbage Collection Tuning Guide
- Generational ZGC measured against G1: Generational ZGC on JDK 25: Benchmarks vs G1
After marking, a collector can sweep, slide or copy, and the modern ones copy
Marking only tells the collector which objects are alive. What it does next decides how long your application waits. The old textbook answer is sweep: free the dead objects where they sit. That leaves holes between the survivors, so allocating a large object may fail even when there is plenty of free space in total. A second answer is mark-compact: slide all the live objects together so the free space becomes one block. The third is to copy (the JVM calls it evacuate or relocate): copy the live objects into empty memory and then treat everything they left behind as free, with no per-object work for the dead ones.pause counts by type:
38 Pause Young (Normal)
5 Pause Young (Mixed)
5 Pause Young (Concurrent Start)
4 Pause Young (Prepare Mixed)
1 Pause Full (G1 Compaction Pause)
The Concurrent Start pauses begin a marking cycle of the old generation that runs alongside the application and is not a pause. After it, Prepare Mixed and Mixed collections clean up old regions together with young ones. The last line, Pause Full, is the failure mode of every collector in this article. It gets its own section below.
Stop-the-world versus concurrent. A pause (stop-the-world) is a moment when every application thread is stopped so that the collector can work safely. Work a collector does concurrently happens while your threads keep running, at the cost of using CPU cores and of extra checks in your code’s memory accesses. Serial and Parallel do everything in pauses. G1 does most of its marking concurrently but copies in pauses. ZGC and Shenandoah do almost everything concurrently.
Going deeper: why the pause is proportional to what survives
A young collection must find the live young objects fast without scanning the old generation. G1 does it by remembering, for each region, which other regions point into it (remembered sets, kept up to date by a small check on every pointer write). That bookkeeping is part of the “GC” memory category in the native-memory table in the first section. It is also why a program that keeps overwriting pointers in the old generation, such as the graph workload of the next section, costs a collector more than one that fills a big array once. This is the documented design; this article did not instrument the remembered sets themselves.
- G1 and its pause-time goal: Garbage-First (G1) chapter of the tuning guide
- What the three Shenandoah and ZGC pauses are for: the Shenandoah log lines are shown in the section on concurrent collectors below
Five collectors ship in the JDK, and since JDK 27 the JVM picks G1 for you everywhere
HotSpot, the JVM in the JDK, includes five collectors that you choose with a flag. The names in the last column are what the JVM itself reports throughGarbageCollectorMXBean; the small program Which.java prints them, so they are observations, not documentation.
| Collector | Flag | Aim | Names the JVM reports |
|---|---|---|---|
| Serial | -XX:+UseSerialGC | small heaps, one thread, simplest | Copy, MarkSweepCompact |
| Parallel | -XX:+UseParallelGC | throughput: several threads collect in pauses | PS Scavenge, PS MarkSweep |
| G1 | -XX:+UseG1GC | balance, with a pause-time goal; the default | G1 Young Generation, G1 Concurrent GC, G1 Old Generation |
| ZGC | -XX:+UseZGC | very short pauses, almost all work concurrent | ZGC Minor Cycles, ZGC Minor Pauses, ZGC Major Cycles, ZGC Major Pauses |
| Shenandoah | -XX:+UseShenandoahGC | short pauses, concurrent copying | Shenandoah Pauses, Shenandoah Cycles |
## eclipse-temurin:25-jre
--cpus=1 --memory=4g -> UseSerialGC
--cpus=2 --memory=1g -> UseSerialGC
--cpus=2 --memory=1500m -> UseSerialGC
--cpus=2 --memory=1791m -> UseSerialGC
--cpus=2 --memory=1792m -> UseG1GC
--cpus=2 --memory=1800m -> UseG1GC
--cpus=2 --memory=2g -> UseG1GC
## eclipse-temurin:27-jre
--cpus=1 --memory=4g -> UseG1GC
--cpus=2 --memory=1g -> UseG1GC
--cpus=2 --memory=1500m -> UseG1GC
--cpus=2 --memory=1791m -> UseG1GC
--cpus=2 --memory=1792m -> UseG1GC
--cpus=2 --memory=1800m -> UseG1GC
--cpus=2 --memory=2g -> UseG1GC
On JDK 25 the answer flips from Serial to G1 between 1791 MB and 1792 MB of container memory, and a single CPU gets Serial no matter how much memory there is. So the old rule was: at least two CPUs and at least 1792 MB, otherwise Serial. On JDK 27 every row says G1. That is JEP 523, “Make G1 the Default Garbage Collector in All Environments”, which the JDK 27 release coverage confirms shipped with GA on 15 September 2026. The CPU half can also be checked without Docker by pretending to have fewer processors (01-default-collector.txt):
## JDK 25: OpenJDK Runtime Environment Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS)
$ java -XX:ActiveProcessorCount=1 Which
collector MXBeans : Copy | MarkSweepCompact
$ java -XX:ActiveProcessorCount=2 Which
collector MXBeans : G1 Young Generation | G1 Concurrent GC | G1 Old Generation
$ java -XX:ActiveProcessorCount=4 Which
collector MXBeans : G1 Young Generation | G1 Concurrent GC | G1 Old Generation
## JDK 27: OpenJDK Runtime Environment Temurin-27.0.1.1+4 (build 27.0.1.1+4)
$ java -XX:ActiveProcessorCount=1 Which
collector MXBeans : G1 Young Generation | G1 Concurrent GC | G1 Old Generation
$ java -XX:ActiveProcessorCount=2 Which
collector MXBeans : G1 Young Generation | G1 Concurrent GC | G1 Old Generation
$ java -XX:ActiveProcessorCount=4 Which
collector MXBeans : G1 Young Generation | G1 Concurrent GC | G1 Old Generation
A trap when you test small containers on 27 or later. The usual way to pretend a machine has less memory is-XX:MaxRAM. That no longer works: JDK 27 ignores it with a warning and the JDK 28 early-access build refuses to start. A test that used it would silently test the wrong thing. Use real container limits as above (02-maxram.txt):OpenJDK 64-Bit Server VM warning: Ignoring option MaxRAM; support was removed in 27.0Unrecognized VM option 'MaxRAM=1g'
Going deeper: Serial is not going away, and what the switch costs
JEP 523 does not deprecate Serial. You can still ask for it with -XX:+UseSerialGC, and the JEP says that some applications in constrained environments may still do best with it. It also argues that G1’s native memory use has been reduced to levels comparable to Serial’s. That is the JEP’s claim and was not re-measured here; the only footprint number I measured is the G1 bookkeeping line in the first section (about 47 MB for a 512 MB heap on JDK 25). If you run many tiny single-CPU containers, test your own memory and start-up before upgrading, and pin -XX:+UseSerialGC if the result is worse.
- The JEP: JEP 523: Make G1 the Default Garbage Collector in All Environments
- What else changed in memory on JDK 27: JDK 27 Memory Changes: Compact Object Headers by Default and G1 Everywhere
- Every JEP in the release: Java 27 Is Out: Every JEP, Plus the Java 26 Changes You Skipped
The same program under five collectors: the shape of the live data decides
To compare collectors I wrote a small service simulator, Churn.java. It keeps a live set in memory, then handles a stream of “requests” that each allocate some short-lived garbage. A second thread, the ticker, repeatedly asks to sleep for 1 ms and records how late it wakes up, so any stall the application feels, from a pause or from anything else, shows up as lateness. The heart of it: /** Runs the request loop for the given time. */
static void serve(long nanos) {
var rnd = ThreadLocalRandom.current();
long end = System.nanoTime() + nanos;
allocatedBytes = 0;
ops = 0;
while (System.nanoTime() < end) {
// short-lived garbage: a few small arrays per "request"
for (int k = 0; k < 8; k++) {
byte[] b = new byte[256 + rnd.nextInt(768)];
ring[slot] = b;
slot = (slot + 1) & (ring.length - 1);
allocatedBytes += b.length;
}
// some requests replace one piece of the live set, so some objects live a while and then die
if (graphMode) { if ((ops & 1) == 0) graph.put(rnd.nextInt(graphKeys), new byte[48]); }
else if (ops % 200 == 0) live.set(rnd.nextInt(live.size()), new byte[1024]);
ops++;
}
}
I ran it first with the simplest live set: one list of 1 KB byte arrays, which contain no pointers and are cheap to copy. On a 512 MB heap with 150 MB live, the worst stall the ticker saw was (14-flat-live-set-baseline.txt):
| Collector | Worst stall (ms), one run | Requests completed |
|---|---|---|
| Serial | 8.6 | 10,735,539 |
| Parallel | 5.0 | 13,025,302 |
| G1 | 7.2 | 8,873,404 |
| ZGC | 6.3 | 13,262,536 |
| Shenandoah (generational) | 5.3 | 9,827,770 |
| Collector | Worst stall in each of 3 runs (ms) | Requests completed (runs 1 to 3) |
|---|---|---|
| Serial | 576, 595, 586 | 2.1M, 2.0M, 1.9M |
| Parallel | 539, 554, 537 | 1.0M, 0.9M, 0.9M |
| G1 | 566, 576, 515 | 3.2M, 3.3M, 3.1M |
| ZGC | 12.4, 8.3, 13.0 | 5.2M, 5.7M, 5.6M |
| Shenandoah (generational) | 11.1, 11.2, 5.0 | 1.7M, 1.7M, 1.7M |
A mistake I made first, and what it taught me. My first version of this benchmark showed G1 stalling for about 80 ms and everything else for 5 to 30 ms. That was wrong. The ticker had started while the collector was still copying the freshly built live set out of the young generation, the same one-off pause asGC(1)in the earlier log. After I added a 1.5 second warm-up before the ticker starts, that stall disappeared, and with the flat live set no collector showed any real difference at all. The workload that does separate them is the pointer-heavy one above, and the lesson holds for your own measurements: start measuring after warm-up, and make the test data look like your real data. (Theringarray in the code keeps recent garbage reachable, because without it the JIT compiler removes the allocations and the benchmark measures nothing.)
Going deeper: how to read the ticker, and why this is not JMH
The ticker measures lateness of a 1 ms sleep, so it reports the longest period during which a thread that wanted to run could not. A stop-the-world pause is one cause; a concurrent collector competing for the two CPUs of this sandbox is another. That is why the section on concurrent collectors below compares the stall with the collector’s own pause log. For measuring a method’s speed use JMH, not this. This program measures application-visible stalls under a collector, not the speed of any code.
- How to benchmark code properly: JMH Tutorial: Writing Java Microbenchmarks That Don’t Lie
- Source for every number in this section: Churn.java, transcripts 07-five-collectors.txt and 14-flat-live-set-baseline.txt
Why three of them stalled for half a second: the heap was too tight, and a full collection is the escape hatch
The three longest pauses in each G1 run explain the half second (15-g1-pause-types.txt, run 1 shown):three longest pauses:
GC(51) Pause Full (G1 Compaction Pause) 1024M->464M(1024M) 467.261ms
GC(2) Pause Young (Normal) (G1 Evacuation Pause) 409M->409M(1024M) 109.383ms
GC(49) Pause Young (Mixed) (G1 Evacuation Pause) (Evacuation Failure: Allocation) 971M->975M(1024M) 106.895ms
Read it from the bottom. A Mixed collection hit Evacuation Failure: Allocation: G1 was copying survivors and ran out of empty space to copy them into, with the heap at 971M of 1024M. When that happens G1 gives up on its incremental plan and runs Pause Full (G1 Compaction Pause), which stops the whole application and compacts the entire heap. It took 467.261 ms. This happened once in every one of the three runs. The live set was 450 MB in a 1 GB heap, and with that little free space and a program that keeps allocating, every collector with a stop-the-world compaction fallback ends up there. The same experiment with 2 GB of heap, which is 22 percent live instead of 45 percent (19-headroom-2g.txt):
| Collector | Worst stall, 1 GB heap (median of 3) | Worst stall, 2 GB heap (one run) |
|---|---|---|
| Serial | 586 | 122 |
| Parallel | 539 | 52.3 |
| G1 | 566 | 132 |
| ZGC | 12.4 | 8.1 |
| Shenandoah (generational) | 11.1 | 6.9 |
Headroom beats collector choice. Doubling the heap took Serial from about 586 ms to 122 ms and G1 from about 566 ms to 132 ms, with no change of collector. If your logs showPause FullorEvacuation Failure, the first fix is usually more heap or less live data, not a different collector. And if your container limit leaves no room for a bigger heap, no collector will save you.
Going deeper: reading the warning signs in a G1 log
Pause Full (G1 Compaction Pause)orPause Full (Allocation Failure): the incremental collection could not keep up, and the whole heap was compacted while everything waited. Treat every one of these as a bug to fix, not as noise.Evacuation Failureon a young or mixed pause: no free regions to copy into. It usually comes right before a full collection.Pause Young (Concurrent Start)followed byPause Young (Prepare Mixed)andMixedpauses: healthy. The old generation is being cleaned incrementally.Pause Full (System.gc()): someone calledSystem.gc(). See the practical-advice section.
Enable the log with -Xlog:gc (one line per collection) and add -Xlog:gc* only when you need the phase details. Transcript for the table: 19-headroom-2g.txt. Related: JVM Flags for Spring Boot in Containers.
ZGC and Shenandoah avoid long pauses by copying while your code runs, and both are generational now
ZGC and Shenandoah are the two low-latency collectors. Instead of stopping the application to copy objects, they copy them while the application runs, and the pauses they do need are tiny. Both started without generations. Both are generational now, and the history is short enough to fit in a picture.## JDK 25, no mode flag
$ java -XX:+UseShenandoahGC -Xlog:gc+init -version | grep Mode
[0.008s][info][gc,init] Mode: Snapshot-At-The-Beginning (SATB)
## JDK 27, no mode flag
$ java -XX:+UseShenandoahGC -Xlog:gc+init -version | grep Mode
[0.007s][info][gc,init] Mode: Snapshot-At-The-Beginning (SATB)
## JDK 28, no mode flag
$ java -XX:+UseShenandoahGC -Xlog:gc+init -version | grep Mode
[0.014s][info][gc,init] Mode: generational
## JDK 25: generational mode without -XX:+UnlockExperimentalVMOptions
$ java -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -Xlog:gc+init -version
[0.011s][info][gc,init] Mode: Generational
## JDK 25: ask for the old mode
$ java -XX:+UseZGC -XX:-ZGenerational -version
OpenJDK 64-Bit Server VM warning: Ignoring option ZGenerational; support was removed in 24.0
openjdk version "25.0.5.1" 2026-11-17 LTS
Three things follow. Shenandoah’s generational mode needs no unlock flag on JDK 25 (JEP 521 made it a product feature) but is not the default there: the default is still the single-generation mode. On the JDK 28 early-access build the default is generational, which matches JEP 535 as InfoQ reports it for JDK 28. ZGC has been generational only since JDK 24 removed the old mode, as the warning shows. The same build also has three ZGC flags that JDK 27 does not (ZAdaptiveHeapSizing, ZGCIntensity, ZMemoryHeating), consistent with the adaptive-heap-sizing and faster-start-up JEPs targeted at JDK 28.
only on 28:
ZAdaptiveHeapSizing
ZGCIntensity
ZMemoryHeating
## its default on 28
size_t SoftMaxHeapSize = 1449551462 {manageable} {ergonomic}
bool ZAdaptiveHeapSizing = false {product} {default}
A short pause is not the same as a smooth application, though, and the same workload showed it. Here is generational Shenandoah on the three JDKs, with the collector’s own log next to what the application felt (21-shenandoah-allocation-stalls.txt):
## JDK 25
allocation stalls logged : 0
longest allocation stalls :
longest stop-the-world pause: 0.913ms
ticker max stall: 5.2 ms; wakeups >10 ms: 0; >50 ms: 0
## JDK 27
allocation stalls logged : 0
longest allocation stalls :
longest stop-the-world pause: 1293.419ms
ticker max stall: 1292.7 ms; wakeups >10 ms: 15; >50 ms: 15
## JDK 28
allocation stalls logged : 83
longest allocation stalls :
Allocation Stall (main) 285.067ms
Allocation Stall (main) 282.400ms
longest stop-the-world pause: 0.372ms
ticker max stall: 281.3 ms; wakeups >10 ms: 28; >50 ms: 22
A pause-free log is not a stall-free application. On JDK 28 early access, Shenandoah’s longest stop-the-world pause was under half a millisecond, yet the allocating thread was stalled for hundreds of milliseconds, 83 times. That is an allocation stall: the program asked for memory faster than the concurrent collector could free it, and the collector made the thread wait instead of pausing everyone. On JDK 27 the same run fell back to degenerated and full collections of about 1.3 seconds (20-shenandoah-pause-types.txt), and on JDK 25 it did neither. Three JDKs, three behaviours, one program. I did not investigate why they differ, and this is a 2 CPU sandbox with a deliberately tight heap, so it is not a verdict on any collector. It is a reason to watch the stall your application sees, not only the pause the GC log reports, and to test on the JDK you will actually run. ZGC, in the same experiment, stayed between 8.3 and 13.0 ms at 1 GB and was 8.1 ms at 2 GB.
Going deeper: the pause types behind those three behaviours
## JDK 25
pause counts by type:
42 Pause Final Mark
41 Pause Init Mark
38 Pause Init Update Refs
38 Pause Final Update Refs
three longest pauses:
GC(15) Pause Final Mark (Young) 5.844ms
GC(8) Pause Final Update Refs 1.035ms
GC(14) Pause Final Update Refs 0.412ms
## JDK 27
pause counts by type:
16 Pause Init Mark
15 Pause Degenerated GC
5 Pause Final Mark
3 Pause Full
three longest pauses:
GC(27) Pause Full 993M->434M(1024M) 1304.922ms
GC(18) Pause Full 993M->434M(1024M) 1210.941ms
GC(9) Pause Full 1024M->433M(1024M) 1152.424ms
Degenerated GC and Full are Shenandoah’s stop-the-world fallbacks when its concurrent cycle loses the race against allocation, the counterpart of G1’s full collection. Transcript: 20-shenandoah-pause-types.txt. The mode-by-JDK matrix is in 18-shenandoah-by-jdk.txt.
- Generational ZGC against G1: Generational ZGC on JDK 25: Benchmarks vs G1
- Generational Shenandoah by default: Generational Shenandoah by Default in JDK 28 (JEP 535)
- ZGC in JDK 28: ZGC in JDK 28: Adaptive Heap Sizing and Faster Startup
- JEP 521: Generational Shenandoah; JEP 404: Generational Shenandoah (Experimental); JEP 439: Generational ZGC
- The InfoQ reports on what is targeted for JDK 28: JEP 535 for Shenandoah and JEP 546 and JEP 545 for ZGC
When the heap really is full: what an OutOfMemoryError means
If the collector cannot free enough memory for an allocation even after a full collection, the JVM throwsjava.lang.OutOfMemoryError: Java heap space. It does not mean the heap is full of garbage. It means the heap is full of things that are still reachable. The program Leak.java is the classic cause, a static collection that only ever grows:
import java.util.ArrayList;
import java.util.List;
/** A classic leak: a static collection that only ever grows. Argument "big" keeps 1 MB arrays, "small" keeps tiny objects. */
public class Leak {
static final List<Object> CACHE = new ArrayList<>(); // a GC root: nothing ever removes from it
public static void main(String[] args) {
boolean big = args.length > 0 && args[0].equals("big");
long n = 0;
try {
while (true) {
CACHE.add(big ? new byte[1 << 20] : new int[8]);
n++;
}
} catch (OutOfMemoryError e) {
int kept = CACHE.size();
CACHE.clear(); // give the JVM room to print
System.out.println("kept " + kept + (big ? " arrays of 1 MB" : " tiny objects") + " then: java.lang.OutOfMemoryError: " + e.getMessage());
}
}
}
## G1, 1 MB arrays
kept 31 arrays of 1 MB then: java.lang.OutOfMemoryError: Java heap space
## G1, tiny objects
kept 1215487 tiny objects then: java.lang.OutOfMemoryError: Java heap space
## Parallel, tiny objects
kept 1160801 tiny objects then: java.lang.OutOfMemoryError: Java heap space
Transcript: 10-out-of-memory.txt, run with -Xmx64m. The program catches the error and clears the list so that it has room to print; a real application would not catch it, and with a nearly full heap even the stack trace may fail to print. I tried the tiny-object variant with the Parallel collector too, hoping to show the other well-known message, GC overhead limit exceeded. It did not appear: Parallel also reported Java heap space. I am reporting that as observed and not claiming when the other message appears.
Going deeper: finding what is holding the memory
The fix for a leak is never a different collector: something is holding references you no longer need, and a heap dump shows you what. Start the JVM with -XX:+HeapDumpOnOutOfMemoryError (documented, not run here) and open the dump in a tool such as Eclipse MAT. The usual suspects are static caches without a size limit, listeners that were never removed, and per-request data stored in a long-lived map.
- The full walkthrough with five real leak patterns: Debugging OutOfMemoryError: Heap Dumps, Eclipse MAT, and the Five Leak Patterns in Spring Apps
The practical advice, re-checked against real runs
The earlier version of this article gave three tips. Two of them were too loose, and checking them against real runs is what this rewrite is for.Forget that System.gc() exists
The old article said System.gc() is “merely a suggestion” the JVM is free to ignore. In practice, with default flags, HotSpot runs a full collection. SysGc.java holds 150 MB of live data and calls it three times under G1 (11-system-gc.txt):
## default
[0.187s][info][gc] GC(7) Pause Full (System.gc()) 156M->154M(267M) 22.122ms
System.gc() #1 took 22.5 ms
[0.224s][info][gc] GC(8) Pause Full (System.gc()) 155M->154M(267M) 18.764ms
System.gc() #2 took 18.9 ms
[0.238s][info][gc] GC(9) Pause Full (System.gc()) 155M->154M(267M) 13.827ms
System.gc() #3 took 14.0 ms
live chunks still referenced: 153600
## -XX:+DisableExplicitGC
System.gc() #1 took 0.1 ms
System.gc() #2 took 0.0 ms
System.gc() #3 took 0.0 ms
live chunks still referenced: 153600
## -XX:+ExplicitGCInvokesConcurrent
[0.203s][info][gc] GC(7) Pause Young (Concurrent Start) (System.gc()) 168M->168M(267M) 8.496ms
System.gc() #1 took 34.4 ms
[0.261s][info][gc] GC(9) Pause Young (Concurrent Start) (System.gc()) 168M->169M(285M) 4.044ms
System.gc() #2 took 31.7 ms
[0.290s][info][gc] GC(11) Pause Young (Concurrent Start) (System.gc()) 169M->168M(287M) 0.919ms
System.gc() #3 took 22.5 ms
live chunks still referenced: 153600
By default each call was a Pause Full (System.gc()), the application stopped for 14 to 22 ms with only 150 MB of live data. A flag, -XX:+DisableExplicitGC, does make the call a no-op, and -XX:+ExplicitGCInvokesConcurrent turns it into a concurrent cycle, though the calling thread still waited for it (22 to 34 ms above). Libraries sometimes call System.gc() on your behalf, so if a log shows Pause Full (System.gc()) and you did not write it, that is where it comes from.
Do not use finalize() to release resources
The old article said finalize() has been deprecated since Java 9. It has, and it is now deprecated for removal. The compiler says so, and the JVM can switch it off entirely. Finalize.java on JDK 25, 27 and the 28 early-access build (12-finalize.txt):
## what javac says (JDK 25, -Xlint:deprecation)
src/Finalize.java:13: warning: [removal] finalize() in Object has been deprecated and marked for removal
protected void finalize() { // deliberately not suppressed: javac prints a removal warning
^
1 warning
## JDK 25, default
finalize() ran
main done
## JDK 25, --finalization=disabled
main done
finalize() still runs by default on all three JDKs, and --finalization=disabled stops it (the transcript shows the same for 27 and 28). It is deprecated, not removed, so old code keeps working, but you cannot rely on it. The reliable way to release a file or socket is try-with-resources, which closes the resource at a known moment. The file TryWithResources.java is the old article’s example made runnable:
try (FileInputStream fis = new FileInputStream(file.toFile())) {
System.out.println("read byte count: " + fis.readAllBytes().length);
} catch (IOException e) {
System.out.println("handle exception here: " + e);
} // fis.close() has already run here, whether or not an exception was thrown
read byte count: 5
stream closed deterministically at the end of the try block
Transcript: 13-small-demos.txt.
Keep objects reachable for as short a time as you can
The third tip was to keep variables in a tight scope. The better way to put it is the one the reachability section demonstrated: what the collector cares about is reachability, not scope. A big temporary object stored in a field, a static map, a cache or a long-lived list stays alive for as long as that holder does, however small the method that created it was. Letting references go out of reach, or clearing them, is what makes objects collectable. Declaring a variable inside a loop is a good habit, but the memory is only freed once no root can reach the object.finalize()is not the same asCleaner. If you need a safety net for a native resource, usejava.lang.ref.Cleaner, which is built on phantom references (documented, not run here), and keeptry-with-resourcesas the main mechanism.
Going deeper: every flag and command used in this article
| Need | Flag or command | Verified in |
|---|---|---|
| Pick a collector | -XX:+UseSerialGC / UseParallelGC / UseG1GC / UseZGC / UseShenandoahGC | 01, 07 |
| Shenandoah generational mode | -XX:ShenandoahGCMode=generational (no unlock flag on 25) | 03 |
| One log line per collection | -Xlog:gc | 06, 15 |
| Heap layout of a live JVM | jcmd <pid> GC.heap_info | 09 |
| Native memory by category | -XX:NativeMemoryTracking=summary then jcmd <pid> VM.native_memory summary | 16 |
Make System.gc() a no-op | -XX:+DisableExplicitGC | 11 |
| Turn finalization off | --finalization=disabled | 12 |
| Heap dump on out of memory | -XX:+HeapDumpOnOutOfMemoryError | documented, not run |
The numbers refer to the files in output/ of the companion module.
Which collector should you use?
Start with the default, look at the log, and change something only when the log or your users tell you to. The table is a starting point for what to test, not a ranking.| If your situation is… | Try… | Because (from this article) |
|---|---|---|
| You run JDK 27 or later and have not chosen | the default, G1 | it is now the default on every machine |
| JDK 25 or earlier, 1 CPU or under 1792 MB | check what you actually get; add -XX:+UseG1GC or -XX:+UseSerialGC on purpose | the JVM silently picked Serial here, so an upgrade to 27 changes it |
Logs show Pause Full or Evacuation Failure | more heap or less live data first | doubling the heap cut G1 and Serial stalls to a fraction |
| Short pauses matter, you have spare cores and headroom | ZGC, or Shenandoah in generational mode, on the JDK you will run | ZGC stayed near 10 ms here; Shenandoah behaved differently on each JDK |
| Batch job, only total run time matters | Parallel or G1 | long pauses do not matter if nobody is waiting; measure the total |
| A tiny, single-CPU, short-lived container | measure Serial against G1 for memory and start-up | JEP 523 says G1 is comparable; it is a claim to check on your workload |
Should you tune the collector at all? Probably not first. In these runs the biggest effects were the heap size relative to the live data and the shape of the data, not the collector name, and the collectors even behaved differently across JDK versions on the same program. So: keep the defaults, read-Xlog:gcfrom a realistic load test, fixPause Fullwith headroom or by reducing what you keep alive, and only then compare collectors on your workload on the JDK you will ship. Do not copy flag lists from blog posts, including this one. JDK 27 is not an LTS release; the next LTS is Java 29 in September 2027, so JDK 25 is the one most production systems will be on.
What the earlier version of this article got wrong
- “G1 is the default since Java 9.” True only on machines the JVM judged big enough. Below two CPUs or 1792 MB it picked Serial until JDK 27, as the container test shows.
- ZGC and Shenandoah are “for massive, multi-terabyte heaps”. They are not limited to that. ZGC held a 1 GB heap at about 10 ms stalls here. I did not test terabyte heaps. The text also never mentioned that both are generational now.
- Mark, sweep, compact as the one way a collector works. Sweeping is only one option; the collectors you would actually run mostly copy.
System.gc()is merely a suggestion the JVM may ignore. With default flags HotSpot ran a full collection every time.finalize()is deprecated since Java 9. It is now deprecated for removal and can be turned off with a flag, though it still runs by default.
Further reading
- The companion code and every transcript: asmhatre/javademos, module gc-basics
- Related measurements on this site: Generational ZGC on JDK 25 vs G1, Generational Shenandoah by Default in JDK 28, ZGC in JDK 28, What Actually Got Faster in JDK 27
- Operations: JVM Flags for Spring Boot in Containers and Debugging OutOfMemoryError
- JEP 523: Make G1 the Default Garbage Collector in All Environments
- JEP 521: Generational Shenandoah and JEP 439: Generational ZGC
- HotSpot Virtual Machine Garbage Collection Tuning Guide, release 25
No Comments yet!