GC deep dive: G1, ZGC, Shenandoah and the rest
HotSpot ships five garbage collectors with different trade-offs between pause time, throughput and memory. This page first explains how a tracing collector finds garbage and how the collectors differ, then runs the same allocation-heavy program under each one on JDK 25 and compares pauses and CPU, reads a G1 log, and measures what too little heap headroom does.
Contents
How a garbage collector works
A garbage collector frees memory that the program can no longer reach. HotSpot's collectors are tracing collectors: they start from the GC roots (local variables on thread stacks, static fields, JNI references and a few JVM-internal ones), follow every reference, and treat everything they did not reach as garbage. Unlike reference counting, this frees cycles of objects that point only at each other.
The collectors differ in how they do three jobs, and when:
- Marking finds the live objects. It can run with the application stopped, or concurrently while the application keeps changing references, which needs barriers: small pieces of code the JIT adds to reference writes (G1, Shenandoah) or reads (ZGC) so the collector learns about changes.
- Reclaiming frees the dead space, either by copying the live objects elsewhere (evacuation) or by compacting them in place, so the free memory is contiguous and allocation stays a fast pointer bump.
- Generations: most objects die young (the weak generational hypothesis), so collecting the young objects often and the old ones rarely is efficient. Serial, Parallel and G1 are generational, ZGC has been generational only since JDK 24, and Shenandoah has an optional generational mode.
Any work done with the application stopped happens at a safepoint, a point where every Java thread has paused. Serial and Parallel do all their work at safepoints. G1 divides the heap into equal regions, marks concurrently, and copies at safepoints, choosing how many regions to copy to meet a pause target. ZGC and Shenandoah also move objects concurrently, so their safepoints are short and nearly independent of heap size.
| Collector | Since | Stop-the-world work | Best for |
|---|---|---|---|
| Serial | Java 1.3 | Everything, on one thread | Small heaps, one CPU |
| Parallel | Java 1.4 | Everything, on all cores | Batch throughput |
| G1 | Java 7, default since 9 (JEP 248) | Copying (evacuation) | General-purpose servers |
| Shenandoah | Java 12 experimental, product in 15 (JEP 379) | Short phase starts and ends | Low latency |
| ZGC | Java 11 experimental, product in 15 (JEP 377) | Short phase starts and ends | Low latency, very large heaps |
CMS, the earlier concurrent collector, was removed in JDK 14 (JEP 363). All measurements on this page were made on JDK 25 on a 2-core Linux machine shared with other work, so absolute numbers vary between runs; the patterns described were the same in every run.
What counts as garbage
Reachability, not scope or age, decides what is collected. The program builds three 1 MB objects that differ only in how they can be reached: a cycle with no outside reference, an object in a static list, and an object held by a local variable that is used later. Weak references observe whether each one survives a full collection.
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
// What counts as garbage: objects not reachable from a GC root
public class Reachability {
static final class Node {
Node next;
final byte[] payload = new byte[1024 * 1024]; // 1 MB, so the effect is visible
}
static final List<Node> ROOT = new ArrayList<>(); // a static field is a GC root
public static void main(String[] args) {
// A cycle: a -> b -> a. Reference counting could never free it; tracing can
Node a = new Node();
Node b = new Node();
a.next = b;
b.next = a;
WeakReference<Node> cycle = new WeakReference<>(a);
// Reachable from a static field
Node kept = new Node();
ROOT.add(kept);
WeakReference<Node> rooted = new WeakReference<>(kept);
// Only reachable from a local variable that is still used later
Node local = new Node();
WeakReference<Node> onStack = new WeakReference<>(local);
a = null;
b = null;
kept = null;
System.gc(); // a full collection on G1
System.out.println("cycle with no outside reference collected: " + (cycle.get() == null));
System.out.println("object held by a static list collected: " + (rooted.get() == null));
System.out.println("object held by a live local collected: "
+ (onStack.get() == null));
System.out.println("local still in use: " + (local.payload.length / 1024) + " KB");
}
}
Output (run with G1, where System.gc()
cycle with no outside reference collected: true
object held by a static list collected: false
object held by a live local collected: false
local still in use: 1024 KB
- The cycle was collected although
anda still point at each other: no path leads to them from a root. Tracing collectors handle cycles for free.b - The object in the static list survived. Static fields are roots, which is why a forgotten static collection is the most common memory leak; see
memory leaks . - The object held by the live local survived, because thread stacks are roots. The JIT may treat a local as dead after its last use, so do not rely on a local keeping an object alive beyond that point.
is only a request. It is useful in a demonstration like this, but in production code it usually just adds a full pause.System.gc()
The test workload
The program imitates a service with a large cache: about 300 MB of long-lived arrays, plus a constant stream of short-lived arrays between 64 bytes and 4 KB, and occasional replacement of cache entries so that some old objects die too. It runs for 6 seconds (or the number of seconds given as an argument) and reports how many batches of work it completed, a rough measure of throughput, and the CPU time the whole JVM used, GC threads included.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
// An allocation-heavy service: a large long-lived cache plus constant short-lived garbage
public class Workload {
static volatile Object sink;
public static void main(String[] args) {
int liveMb = 300;
List<byte[]> cache = new ArrayList<>();
for (int i = 0; i < liveMb * 16; i++) {
cache.add(new byte[64 * 1024]); // ~300 MB that stays alive
}
long seconds = args.length > 0 ? Long.parseLong(args[0]) : 6;
long start = System.nanoTime();
long batches = 0;
while (System.nanoTime() - start < seconds * 1000000000L) {
for (int i = 0; i < 1000; i++) {
sink = new byte[ThreadLocalRandom.current().nextInt(64, 4096)];
}
// Replace a cache entry now and then so old objects die too
cache.set(ThreadLocalRandom.current().nextInt(cache.size()), new byte[64 * 1024]);
batches++;
}
System.out.println("work done: " + batches);
// CPU time of the whole JVM, GC threads included
var os = (com.sun.management.OperatingSystemMXBean)
java.lang.management.ManagementFactory.getOperatingSystemMXBean();
System.out.println("cpu ms: " + os.getProcessCpuTime() / 1000000);
}
}
Comparing pause times
Every stop-the-world pause happens at a safepoint, where all application threads are stopped. Logging safepoints (-Xlog:safepoint
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// Runs Workload under each collector in a child JVM and reads pause times from the GC log
public class CompareCollectors {
// Every stop-the-world pause is a safepoint; the log line ends with its total time
static final Pattern PAUSE = Pattern.compile("Safepoint \"(\\w+)\".*Total: (\\d+) ns");
public static void main(String[] args) throws Exception {
String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
String cp = System.getProperty("java.class.path");
String[] gcs = {"UseSerialGC", "UseParallelGC", "UseG1GC", "UseZGC",
"UseShenandoahGC"};
System.out.printf("%-13s %7s %9s %9s %10s %11s %9s%n", "collector", "pauses", "max ms",
"p50 ms", "total ms", "work done", "CPU ms");
for (String gc : gcs) {
Process p = new ProcessBuilder(java, "-XX:+" + gc, "-Xms1g", "-Xmx1g",
"-Xlog:safepoint:stdout", "-cp", cp, "Workload")
.redirectErrorStream(true).start();
List<Double> pauses = new ArrayList<>();
long work = 0;
long cpu = 0;
try (BufferedReader r = new BufferedReader(new InputStreamReader(
p.getInputStream()))) {
String line;
while ((line = r.readLine()) != null) {
Matcher m = PAUSE.matcher(line);
if (m.find()) {
pauses.add(Long.parseLong(m.group(2)) / 1e6);
} else if (line.startsWith("work done: ")) {
work = Long.parseLong(line.substring(11));
} else if (line.startsWith("cpu ms: ")) {
cpu = Long.parseLong(line.substring(8));
}
}
}
p.waitFor();
Collections.sort(pauses);
double total = pauses.stream().mapToDouble(Double::doubleValue).sum();
System.out.printf("%-13s %7d %9.2f %9.2f %10.1f %,11d %,9d%n", gc.substring(3),
pauses.size(), pauses.get(pauses.size() - 1),
pauses.get(pauses.size() / 2), total, work, cpu);
}
}
}
Output (JDK 25 on a 2-core machine; numbers vary from run to run, but the pattern was the same in every run):
collector pauses max ms p50 ms total ms work done CPU ms
SerialGC 135 147.49 6.37 1279.0 17,827 5,920
ParallelGC 135 114.62 4.30 1100.1 19,541 6,380
G1GC 134 77.08 8.73 1203.4 17,178 6,570
ZGC 527 7.98 0.10 353.7 19,795 6,310
ShenandoahGC 464 11.43 0.14 196.3 16,770 6,360
- Serial, Parallel and G1 move live objects while the application is stopped. Their longest pauses were tens of milliseconds and more, and their total time paused was around a second out of six. Serial uses one GC thread and had the longest pauses.
- ZGC and Shenandoah do marking and compaction concurrently. They paused more often, but their median pause was well under a millisecond, and their total paused time was well below the others'.
- Their maximum pause depends on the machine. In an earlier run on a quieter machine it stayed below a millisecond; in this run, with the 2 cores shared with other processes, single pauses reached several milliseconds. A safepoint's total includes the time for every thread to reach it, and on an overloaded machine a thread may first have to wait for a CPU.
- Pause time is not the whole cost. The CPU column is the JVM's total CPU time; the concurrent collectors' GC threads work alongside the application and use CPU there. The "work done" figures moved by tens of percent between runs on this shared machine, so treat them as noise here. On dedicated hardware, Parallel usually gives the best throughput for batch work, and the concurrent collectors the best latency.
Reading a G1 log
-Xlog:gc
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Path;
// Shows what G1's own log says about the same workload
public class G1Log {
public static void main(String[] args) throws Exception {
String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
Process p = new ProcessBuilder(java, "-XX:+UseG1GC", "-Xms1g", "-Xmx1g",
"-Xlog:gc", "-cp", System.getProperty("java.class.path"), "Workload")
.redirectErrorStream(true).start();
int young = 0;
int mixed = 0;
int concurrent = 0;
int shown = 0;
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = r.readLine()) != null) {
if (line.contains("Pause Young (Normal)")) {
young++;
} else if (line.contains("Pause Young (Mixed)")) {
mixed++;
} else if (line.contains("Concurrent Mark Cycle") && line.endsWith("ms")) {
concurrent++;
}
// Print the first lines, without the timestamp prefix
if (line.contains("GC(") && shown < 8) {
System.out.println(line.substring(line.indexOf("GC(")));
shown++;
}
}
}
p.waitFor();
System.out.println("young pauses: " + young + ", mixed pauses: " + mixed
+ ", concurrent mark cycles: " + concurrent);
}
}
Output:
GC(0) Pause Young (Normal) (G1 Evacuation Pause) 52M->51M(1024M) 19.605ms
GC(1) Pause Young (Normal) (G1 Evacuation Pause) 284M->284M(1024M) 123.954ms
GC(2) Pause Young (Normal) (G1 Evacuation Pause) 479M->324M(1024M) 27.428ms
GC(3) Pause Young (Normal) (G1 Evacuation Pause) 580M->332M(1024M) 19.136ms
GC(4) Pause Young (Normal) (G1 Evacuation Pause) 619M->341M(1024M) 9.310ms
GC(5) Pause Young (Normal) (G1 Evacuation Pause) 753M->353M(1024M) 15.443ms
GC(6) Pause Young (Normal) (G1 Evacuation Pause) 786M->365M(1024M) 26.011ms
GC(7) Pause Young (Normal) (G1 Evacuation Pause) 836M->378M(1024M) 28.665ms
young pauses: 18, mixed pauses: 23, concurrent mark cycles: 22
Each line reads: collection number, type, cause, heap used before and after, total heap, and pause duration. In this run:
happened while the cache was being filled. Before and after are the same: everything allocated so far was still alive, so nothing could be freed, and copying all of it made this the longest pause.GC(1)- From
on, the heap drops back to a little above 300M after each young collection: the short-lived garbage dies young, as the generational hypothesis predicts. The slowly rising "after" value is cache entries being promoted to the old generation.GC(2) - Mixed pauses also collect some old regions. They follow a concurrent mark cycle, which G1 starts when old-generation occupancy crosses the IHOP threshold (initiating heap occupancy percent, adaptive by default).
Warning signs in a G1 log are Pause FullTo-space exhausted
Heap headroom: why size matters
A collector needs free space to work in. The program runs the workload, which keeps about 300 MB alive, for 3 seconds with different maximum heap sizes, and counts collections, full GCs and ZGC allocation stalls, which happen when the application allocates faster than the concurrent collector frees memory.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
// Runs the same workload (300 MB live) with different heap sizes and counts GC events
public class Headroom {
public static void main(String[] args) throws Exception {
run("G1", "512m", "-XX:+UseG1GC");
run("G1", "1g", "-XX:+UseG1GC");
run("G1", "2g", "-XX:+UseG1GC");
run("ZGC", "1g", "-XX:+UseZGC");
run("ZGC", "450m", "-XX:+UseZGC");
}
static void run(String name, String heap, String gcFlag) throws Exception {
String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
List<String> cmd = new ArrayList<>(List.of(java, gcFlag, "-Xms" + heap, "-Xmx" + heap,
"-Xlog:gc", "-cp", System.getProperty("java.class.path"), "Workload", "3"));
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
int collections = 0;
int full = 0;
int stalls = 0;
double stallMs = 0;
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = r.readLine()) != null) {
// G1 logs one line per pause; ZGC logs a start line and an end line ending in "s"
if (line.contains("Pause Young") || line.contains("Pause Remark")
|| (line.contains("Collection (") && line.endsWith("s"))) {
collections++;
}
if (line.contains("Pause Full")) {
full++;
}
if (line.contains("Allocation Stall (") && line.endsWith("ms")) {
stalls++;
stallMs += Double.parseDouble(line.substring(line.lastIndexOf(' ') + 1,
line.length() - 2));
}
}
}
p.waitFor();
System.out.printf("%-4s -Xmx%-5s collections %4d full GCs %2d allocation stalls %4d"
+ " (%6.1f ms in total)%n", name, heap, collections, full, stalls, stallMs);
}
}
Output:
G1 -Xmx512m collections 187 full GCs 0 allocation stalls 0 ( 0.0 ms in total)
G1 -Xmx1g collections 50 full GCs 0 allocation stalls 0 ( 0.0 ms in total)
G1 -Xmx2g collections 19 full GCs 0 allocation stalls 0 ( 0.0 ms in total)
ZGC -Xmx1g collections 58 full GCs 0 allocation stalls 0 ( 0.0 ms in total)
ZGC -Xmx450m collections 425 full GCs 0 allocation stalls 13 ( 36.3 ms in total)
- G1 with 512 MB had to collect many times more often than with 2 GB, because each young collection could only start once the small free area filled up. More heap means fewer collections, not shorter ones.
- No configuration fell back to a full GC: G1 coped even with 512 MB for 300 MB live data. Below that,
lines appear, and then anPause Full .OutOfMemoryError - ZGC with 1 GB had no allocation stalls, or a handful in some runs. With 450 MB it collected almost continuously and stalled the allocating thread repeatedly, between 13 and 69 times in the runs made for this page. A stall is a pause in all but name: the thread waits for the collector. Concurrent collectors trade pause time for headroom and CPU, so give them generous heaps.
Choosing a collector
Start with the default, G1, and change only when measurements show a problem it cannot meet. These are the usual reasons:
| Collector | Flag | Pauses | Best for |
|---|---|---|---|
| G1 | -XX:+UseG1GC | Tens of ms, target set with MaxGCPauseMillis | General-purpose servers |
| ZGC | -XX:+UseZGC | Below a millisecond, independent of heap size | Latency-sensitive services, very large heaps |
| Shenandoah | -XX:+UseShenandoahGC | Below a few milliseconds | Latency-sensitive services; included in most OpenJDK builds, not Oracle JDK |
| Parallel | -XX:+UseParallelGC | Long, with all cores working | Batch jobs where only total throughput matters |
| Serial | -XX:+UseSerialGC | Long, one thread | Small heaps and single-CPU containers; up to JDK 26 the JVM picks it automatically there, while JDK 27 picks G1 (JEP 523) |
- Pauses above your latency budget with G1, on a heap with room to spare: try ZGC or Shenandoah.
- A batch job where only the total run time counts: try Parallel.
- Frequent collections or full GCs: give the heap more room before changing the collector.
- Verify every change with GC logs under realistic load, as on this page.
Recent changes worth knowing: ZGC became production-ready in JDK 15 (JEP 377), gained a generational mode in JDK 21 (JEP 439), which became its only mode in JDK 24 (JEP 490). Shenandoah's generational mode became a product feature in JDK 25 (JEP 521), enabled with -XX:ShenandoahGCMode=generational