Choosing a garbage collector
suggest changeHotSpot ships with several garbage collectors. They all do the same job, freeing objects your program can no longer reach, but they make different trade-offs between three things:
- throughput: how much CPU time goes to your code rather than to the GC
- latency: how long your threads are stopped while the GC works (pause time)
- footprint: how much memory beyond the live data the GC needs to work well
No collector wins on all three. This article shows the collectors in JDK 25, how to select and observe them, and how to choose one.
| Collector | Flag | Pauses | Best for |
|---|---|---|---|
| G1 | -XX:+UseG1GC (default) |
short, mostly proportional to young gen | almost everything; the balanced default |
| Parallel | -XX:+UseParallelGC |
longer, stop-the-world | batch jobs where total time matters, not pauses |
| ZGC | -XX:+UseZGC |
under a millisecond, independent of heap size | latency-sensitive services, large heaps |
| Shenandoah | -XX:+UseShenandoahGC |
under a few milliseconds | same niche as ZGC |
| Serial | -XX:+UseSerialGC |
stop-the-world, single thread | small heaps, 1 CPU, small containers |
| Epsilon | -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC |
none, never collects | tests, very short-lived programs |
What changed recently:
| Release | Change |
|---|---|
| Java 21 | Generational ZGC (JEP 439), opt-in with -XX:+ZGenerational |
| Java 23 | Generational mode becomes ZGC's default (JEP 474) |
| Java 24 | Non-generational ZGC removed (JEP 490); -XX:+ZGenerational is ignored with a warning. Generational Shenandoah added as experimental (JEP 404) |
| Java 25 | Generational Shenandoah is a product feature (JEP 521); compact object headers are a product feature (JEP 519) |
All examples are single-file programs, compiled with javac -d out and run with Temurin 25.0.4.1. For the background on how a tracing collector works, see Garbage collection. For heap flags in general, see Setting the Heap PermGen and Stack sizes and JVM Flags.
Which collector am I running?
The JVM picks a collector at startup. You can ask which one through the GarbageCollectorMXBeans, since each collector registers beans with its own names:
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
public class WhichGc {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.println("CPUs: " + rt.availableProcessors());
System.out.println("Max heap: " + rt.maxMemory() / (1024 * 1024) + " MB");
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
System.out.println("GC bean: " + gc.getName());
}
}
}
Run it with no GC flag and a 2 GB heap:
java -Xmx2g -cp out WhichGc
CPUs: 24
Max heap: 2048 MB
GC bean: G1 Young Generation
GC bean: G1 Concurrent GC
GC bean: G1 Old Generation
The same program with each of the other flags prints:
| Flag | Max heap reported | Bean names |
|---|---|---|
-XX:+UseSerialGC |
1979 MB | Copy, MarkSweepCompact |
-XX:+UseParallelGC |
1820 MB | PS MarkSweep, PS Scavenge |
-XX:+UseZGC |
2048 MB | ZGC Minor Cycles, ZGC Minor Pauses, ZGC Major Cycles, ZGC Major Pauses |
-XX:+UseShenandoahGC |
2048 MB | Shenandoah Pauses, Shenandoah Cycles |
| Epsilon | 2048 MB | Epsilon Heap |
Two details:
Runtime.maxMemory()isn't always-Xmx. Serial and Parallel leave one survivor space out of the count, because at any moment one of the two survivor spaces is empty.- ZGC and Shenandoah have separate "Cycles" and "Pauses" beans. The cycle beans measure whole concurrent collections, most of which run alongside your threads. If you want stop-the-world time, read the "Pauses" beans.
You can also print the selected collector without writing code:
java -XX:+PrintFlagsFinal -version | grep -E "Use(G1|Parallel|Serial|Z|Shenandoah)GC "
bool UseG1GC = true {product} {ergonomic}
bool UseParallelGC = false {product} {default}
bool UseSerialGC = false {product} {default}
bool UseShenandoahGC = false {product} {default}
bool UseZGC = false {product} {default}
{ergonomic} means the JVM chose the value itself.
How the default is chosen
G1 is the default only on what HotSpot calls a "server-class machine": at least 2 CPUs and at least about 1792 MB of memory. Otherwise the JVM picks Serial. You can simulate a small machine with -XX:ActiveProcessorCount and -XX:MaxRAM:
java -XX:ActiveProcessorCount=1 -XX:MaxRAM=1g -cp out WhichGc
CPUs: 1
Max heap: 247 MB
GC bean: Copy
GC bean: MarkSweepCompact
This matters in containers. A pod limited to one CPU gets Serial, which is often what you want there, but it surprises people who expect G1 everywhere. If you care which collector runs, say so with a flag instead of relying on ergonomics.
Measuring the difference
To compare collectors, here is a program that allocates 60 million small objects and keeps a rotating table of 2 million of them alive, so there is both short-lived garbage and a medium-lived working set. A watchdog thread sleeps for 1 ms in a loop and records how late it wakes up. A long delay usually means a stop-the-world pause, but it can also be the OS scheduler or GC threads competing with your threads for CPU.
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.concurrent.atomic.AtomicLong;
public class GcBench {
static final int LIVE = 2_000_000; // long-lived objects kept in the table
static final long OPS = 60_000_000L; // total allocations
record Order(long id, String customer, double[] prices) {}
public static void main(String[] args) throws Exception {
// Watchdog: sleeps 1 ms in a loop and records how late it wakes up.
// A long stall usually means a stop-the-world GC pause.
AtomicLong worstStallNs = new AtomicLong();
Thread watchdog = Thread.ofPlatform().daemon().start(() -> {
while (true) {
long t0 = System.nanoTime();
try { Thread.sleep(1); } catch (InterruptedException e) { return; }
long late = System.nanoTime() - t0 - 1_000_000;
worstStallNs.accumulateAndGet(late, Math::max);
}
});
Order[] table = new Order[LIVE];
long start = System.nanoTime();
long checksum = 0;
for (long i = 0; i < OPS; i++) {
Order o = new Order(i, "customer-" + (i % 1000), new double[4]);
checksum += o.customer().length();
if (i % 8 == 0) {
table[(int) (i / 8 % LIVE)] = o; // 1 in 8 survives for a while
}
}
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
long count = 0, timeMs = 0;
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
if (gc.getName().contains("Cycles")) continue; // ZGC/Shenandoah: count pauses only
count += gc.getCollectionCount();
timeMs += gc.getCollectionTime();
}
System.out.printf("elapsed %d ms, GC pauses %d, pause time %d ms, worst stall %d ms (%d)%n",
elapsedMs, count, timeMs, worstStallNs.get() / 1_000_000, checksum % 10);
}
}
Each collector gets the same 1 GB heap:
java -XX:+UseG1GC -Xmx1g -cp out GcBench
elapsed 2163 ms, GC pauses 22, pause time 350 ms, worst stall 25 ms (0)
The full set from one run of each, back to back:
| Flags | Elapsed | Pauses | Total pause time | Worst stall |
|---|---|---|---|---|
-XX:+UseSerialGC |
2766 ms | 28 | 1726 ms | 377 ms |
-XX:+UseParallelGC |
1746 ms | 39 | 588 ms | 97 ms |
-XX:+UseG1GC |
2163 ms | 22 | 350 ms | 25 ms |
-XX:+UseZGC |
3434 ms | 99 | 0 ms | 18 ms |
-XX:+UseShenandoahGC |
3509 ms | 108 | 14 ms | 10 ms |
-XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational |
4341 ms | 124 | 24 ms | 15 ms |
Read these numbers with care. They come from a shared, busy machine on which the JVM reported 24 available processors (Runtime.availableProcessors()), and the same command varied by 20-40% between runs. They are one short micro-benchmark, not a verdict. The shape is still typical:
- Serial is single-threaded, so with many cores available it is the slowest, with the longest pauses.
- Parallel finishes first. It stops your threads more often, but uses all cores to collect as fast as possible.
- G1 is close to Parallel in total time with much shorter pauses. That's why it's the default.
- ZGC and Shenandoah reduce stop-the-world time to almost nothing (ZGC's pause beans report under 1 ms in total), but the program takes longer. Concurrent collectors pay for short pauses with barriers on every reference load or store, and with GC threads that compete with yours for CPU.
- The "worst stall" for ZGC and Shenandoah isn't zero, even though their pauses are. On a busy machine, the OS doesn't always wake a thread on time. Short GC pauses don't fix scheduling delays.
To learn how your application behaves, measure it under realistic load, with tools like those in Profiling, and compare GC logs.
Reading GC logs
Unified logging (-Xlog, Java 9+) replaced the old -XX:+PrintGC* flags. -Xlog:gc prints one line per collection. This small program allocates 390 MB in 1 KB arrays and keeps 10% of them:
import java.util.ArrayList;
import java.util.List;
public class Churn {
public static void main(String[] args) {
List<byte[]> keep = new ArrayList<>();
long sum = 0;
for (int i = 0; i < 400_000; i++) {
byte[] b = new byte[1024]; // 1 KB of garbage per iteration...
sum += b.length;
if (i % 10 == 0) keep.add(b); // ...and 10% of it stays reachable
}
System.out.println("allocated " + sum / (1024 * 1024) + " MB, kept " + keep.size());
}
}
With G1:
java -XX:+UseG1GC -Xms64m -Xmx256m -Xlog:gc -cp out Churn
[0.025s][info][gc] Using G1
[0.100s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 35M->4M(66M) 7.703ms
[0.107s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 31M->7M(66M) 2.838ms
[0.114s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 37M->10M(66M) 2.435ms
[0.123s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 43M->13M(66M) 3.258ms
[0.131s][info][gc] GC(4) Pause Young (Normal) (G1 Evacuation Pause) 45M->17M(138M) 3.554ms
[0.159s][info][gc] GC(5) Pause Young (Normal) (G1 Evacuation Pause) 95M->24M(138M) 2.760ms
[0.175s][info][gc] GC(6) Pause Young (Normal) (G1 Evacuation Pause) 95M->32M(138M) 6.173ms
[0.189s][info][gc] GC(7) Pause Young (Normal) (G1 Evacuation Pause) 106M->40M(138M) 3.873ms
allocated 390 MB, kept 40000
Each line reads: uptime, GC number, type of pause and its cause, heap used before -> after (committed heap size), and pause duration. 35M->4M(66M) 7.703ms means the heap went from 35 MB used to 4 MB, with 66 MB committed, and your threads were stopped for 7.7 ms. Watch the "after" value: it's roughly your live data. Here it grows steadily because the program keeps 10% of what it allocates. In a long-running service, an "after" value that keeps climbing is a sign of a memory leak.
Other collectors log differently. Parallel says why it collected:
[0.016s][info][gc] Using Parallel
[0.085s][info][gc] GC(0) Pause Young (Allocation Failure) 17M->2M(61M) 2.774ms
[0.091s][info][gc] GC(1) Pause Young (Allocation Failure) 18M->4M(77M) 2.103ms
...
[0.182s][info][gc] GC(7) Pause Young (Allocation Failure) 91M->38M(99M) 12.387ms
ZGC logs the start and end of each collection. The duration there is the whole concurrent cycle, not a pause:
[0.020s][info][gc] Using The Z Garbage Collector
[0.116s][info][gc] GC(0) Major Collection (Warmup)
[0.123s][info][gc] GC(0) Major Collection (Warmup) 26M(10%)->20M(8%) 0.008s
...
[0.196s][info][gc] GC(3) Minor Collection (Allocation Rate)
[0.208s][info][gc] GC(3) Minor Collection (Allocation Rate) 122M(48%)->74M(29%) 0.012s
"Minor" collections cover only the young generation, "Major" ones the whole heap. To see ZGC's actual pauses, add the gc+phases tag:
java -XX:+UseZGC -Xms64m -Xmx256m -Xlog:gc+phases -cp out Churn
[0.051s][info][gc,phases] GC(0) Y: Young Generation
[0.051s][info][gc,phases] GC(0) Y: Pause Mark Start (Major) 0.013ms
[0.052s][info][gc,phases] GC(0) Y: Concurrent Mark 1.333ms
[0.053s][info][gc,phases] GC(0) Y: Pause Mark End 0.010ms
[0.053s][info][gc,phases] GC(0) Y: Concurrent Mark Free 0.001ms
[0.053s][info][gc,phases] GC(0) Y: Concurrent Reset Relocation Set 0.002ms
[0.053s][info][gc,phases] GC(0) Y: Concurrent Select Relocation Set 0.211ms
[0.053s][info][gc,phases] GC(0) Y: Pause Relocate Start 0.005ms
[0.054s][info][gc,phases] GC(0) Y: Concurrent Relocate 1.562ms
[0.054s][info][gc,phases] GC(0) Y: Young Generation 26M(10%)->20M(8%) 0.003s
The three Pause phases take 5-13 microseconds. Everything marked Concurrent runs while your threads keep working.
Shenandoah prints every phase at the gc level. With generational mode, and the Concurrent lines removed:
[0.020s][info][gc] Using Shenandoah
[0.088s][info][gc] Trigger (Young): Learning 1 of 5. Free (175M) is below initial threshold (179M)
[0.089s][info][gc] GC(0) Pause Init Mark (Young) 0.044ms
[0.093s][info][gc] GC(0) Pause Final Mark (Young) 0.481ms
[0.096s][info][gc] GC(0) Pause Init Update Refs 0.007ms
[0.097s][info][gc] GC(0) Pause Final Update Refs 0.073ms
Logging to a file in production
For a real service, log everything GC-related to a rotating file:
java -XX:+UseG1GC -Xmx256m "-Xlog:gc*:file=gc.log:uptime,level,tags:filecount=3,filesize=10m" -cp out Churn
The syntax is -Xlog:<tags>:<output>:<decorators>:<output options>. gc* means every tag set that starts with gc. The file keeps up to 3 rotated files of 10 MB each, which costs little and is invaluable when something goes wrong. Quote the argument on Windows and in shells where * would expand. One G1 collection in that file:
[0.082s][info][gc,start ] GC(0) Pause Young (Normal) (G1 Evacuation Pause)
[0.083s][info][gc,task ] GC(0) Using 6 workers of 18 for evacuation
[0.085s][info][gc,phases ] GC(0) Pre Evacuate Collection Set: 0.12ms
[0.085s][info][gc,phases ] GC(0) Merge Heap Roots: 0.07ms
[0.085s][info][gc,phases ] GC(0) Evacuate Collection Set: 1.58ms
[0.085s][info][gc,phases ] GC(0) Post Evacuate Collection Set: 0.27ms
[0.085s][info][gc,phases ] GC(0) Other: 0.43ms
[0.085s][info][gc,heap ] GC(0) Eden regions: 47->0(111)
[0.085s][info][gc,heap ] GC(0) Survivor regions: 0->6(6)
[0.085s][info][gc,heap ] GC(0) Old regions: 2->2
[0.085s][info][gc,heap ] GC(0) Humongous regions: 0->0
[0.085s][info][gc,metaspace] GC(0) Metaspace: 95K(320K)->95K(320K) NonClass: 91K(192K)->91K(192K) Class: 4K(128K)->4K(128K)
[0.086s][info][gc ] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 48M->6M(256M) 3.042ms
[0.086s][info][gc,cpu ] GC(0) User=0.00s Sys=0.00s Real=0.00s
The start of the file (gc,init lines) records the configuration the JVM actually used: collector, heap min/initial/max, region size, number of parallel and concurrent GC threads, and whether compressed oops and compact object headers are on. Check it first when a setting doesn't seem to take effect.
Things to look for in a G1 log:
Pause Young (Concurrent Start)andPause Remark/Pause Cleanup: the old generation is being marked concurrently. Normal.Pause Young (Mixed): G1 is collecting old regions along with young ones. Normal after a marking cycle.Humongous regionsgrowing: objects of half a region or more (here 512 KB) are allocated directly in the old generation. Lots of them can trigger extra collections.Pause Full: G1 ran out of space and fell back to a full, stop-the-world compaction. If you see these regularly, the heap is too small or the live set is too big.To-space exhaustedorEvacuation Failure: there was no room to copy surviving objects. Same remedy.
Epsilon: the collector that doesn't collect
Epsilon allocates memory and never frees it. When the heap is full, the JVM exits with OutOfMemoryError. It's still experimental, so it needs -XX:+UnlockExperimentalVMOptions:
java -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC -Xmx1g -Xlog:gc -cp out Churn
[0.019s][info][gc] Using Epsilon
[0.021s][info][gc] Consider setting -Xms equal to -Xmx to avoid resizing hiccups
[0.021s][info][gc] Consider enabling -XX:+AlwaysPreTouch to avoid memory commit hiccups
[0.065s][info][gc] Heap: 1024M reserved, 1019M (99.59%) committed, 55000K (5.25%) used
...
[0.139s][info][gc] Heap: 1024M reserved, 1019M (99.59%) committed, 365M (35.71%) used
allocated 390 MB, kept 40000
[0.165s][info][gc] Heap: 1024M reserved, 1019M (99.59%) committed, 401M (39.23%) used
With -Xmx256m, the same program dies once 256 MB have been allocated, even though only 40 MB is live:
...
[0.091s][info][gc] Heap: 256M reserved, 256M (100.00%) committed, 249M (97.54%) used
Terminating due to java.lang.OutOfMemoryError: Java heap space
Uses for Epsilon: measuring how much a program allocates in total, performance tests that need to rule out GC as a source of noise, and short command-line tools that finish before they'd fill the heap.
Tuning knobs worth knowing
Most applications need only a heap size and a collector. Each collector has one or two main settings beyond that:
| Collector | Main settings |
|---|---|
| G1 | -XX:MaxGCPauseMillis=200 (default): a pause-time target, not a guarantee. Lower values make young generations smaller, so you get more, shorter collections |
| Parallel | -XX:GCTimeRatio=N: aim to spend at most 1/(1+N) of the time in GC; -XX:MaxGCPauseMillis |
| ZGC | -Xmx matters most: ZGC needs headroom to collect concurrently. -XX:SoftMaxHeapSize sets a limit ZGC tries to stay under; -XX:+ZUncommit (on by default) returns unused memory to the OS |
| Shenandoah | -XX:ShenandoahGCMode=generational (Java 25) or satb (default); -XX:ShenandoahGCHeuristics=adaptive (default) |
| all | -Xms / -Xmx, -XX:+AlwaysPreTouch (touch heap memory at startup so the first collections don't pay for it), -XX:+UseStringDeduplication (G1, Parallel, Serial, ZGC, Shenandoah) |
Change one setting at a time and compare GC logs before and after. Old tuning advice (-XX:NewRatio, -XX:SurvivorRatio, CMS flags) is usually counter-productive with G1 and irrelevant for ZGC. CMS itself was removed in Java 14. Once a flag has been fully removed, the JVM refuses to start, so old scripts fail loudly:
java -XX:+UseConcMarkSweepGC -version
Unrecognized VM option 'UseConcMarkSweepGC'
Error: Could not create the Java Virtual Machine.
During the transition period, an obsolete option only produces a warning. -XX:+ZGenerational is in that state in Java 25:
OpenJDK 64-Bit Server VM warning: Ignoring option ZGenerational; support was removed in 24.0
Heap sizing in containers
Since Java 10 the JVM reads cgroup limits on Linux (-XX:+UseContainerSupport, on by default). In a container, "physical memory" means the container's memory limit, and availableProcessors() reflects the CPU limit. Without -Xmx, the default max heap is MaxRAMPercentage (25%) of that memory.
25% is a cautious default for a container whose only job is to run your JVM. Use -XX:MaxRAMPercentage to give the heap a share of whatever the limit is, so the same image works at any size. You can try it outside a container by setting -XX:MaxRAM, which stands in for physical memory:
java -XX:MaxRAM=4g -XX:MaxRAMPercentage=75 -cp out WhichGc
CPUs: 24
Max heap: 3072 MB
GC bean: G1 Young Generation
GC bean: G1 Concurrent GC
GC bean: G1 Old Generation
Guidelines:
- Leave room outside the heap: metaspace, thread stacks, the JIT's code cache, direct buffers and GC data structures all use native memory. 75% is a common upper limit for
MaxRAMPercentage. Go lower if you use many threads or a lot of off-heap memory. - Remember the CPU rule from earlier. With fewer than 2 CPUs or less than about 1792 MB of memory, you get Serial unless you ask for something else. On a single CPU that's the right choice, since concurrent collectors need spare cores.
- Concurrent collectors (ZGC, Shenandoah) need a bigger heap than G1 or Parallel for the same live set, because the application keeps allocating while the GC runs.
- On Linux,
java -XshowSettings:system -versionprints the container limits the JVM detected. On Windows it prints "No metrics available for this platform".
Compact object headers
Every Java object starts with a header. On a 64-bit JVM with compressed class pointers it's 12 bytes: an 8-byte "mark word" (locking, hash code, GC age) and a 4-byte class pointer. Java 25 makes compact object headers a product feature (JEP 519), which packs both into 8 bytes. They are off by default, and turned on with -XX:+UseCompactObjectHeaders. They work with every collector.
For small objects, 4 bytes per object add up. This program creates 10 million two-int records and measures the heap after a full GC:
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
public class Headers {
record Point(int x, int y) {}
static long usedAfterGc(MemoryMXBean mem) {
System.gc();
return mem.getHeapMemoryUsage().getUsed();
}
public static void main(String[] args) {
MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
int n = 10_000_000;
long before = usedAfterGc(mem);
Point[] points = new Point[n];
for (int i = 0; i < n; i++) points[i] = new Point(i, -i);
long after = usedAfterGc(mem);
long perObject = (after - before) / n - 4; // minus the 4-byte array slot
System.out.printf("%,d points: %,d MB, about %d bytes per Point%n",
n, (after - before) / (1024 * 1024), perObject);
System.out.println(points[n - 1]);
}
}
java -XX:+UseG1GC -Xmx2g -cp out Headers
java -XX:+UseG1GC -XX:+UseCompactObjectHeaders -Xmx2g -cp out Headers
10,000,000 points: 268 MB, about 24 bytes per Point
Point[x=9999999, y=-9999999]
10,000,000 points: 191 MB, about 16 bytes per Point
Point[x=9999999, y=-9999999]
A Point is a 12-byte header plus two 4-byte ints, 20 bytes, padded to 24 because objects are 8-byte aligned. With an 8-byte header it's exactly 16. The heap shrank by about 29%. Real applications have a mix of object sizes and typically save less, but a smaller heap also means less work for any collector. You can confirm the setting in the gc,metaspace log lines, which print UseCompactObjectHeaders 1 when it's on.
How to choose
- Start with the default (G1) and a sensible
-Xmx. Turn on GC logging to a file. For most services and applications, you're done. - If total throughput matters and pauses don't, for example batch jobs, ETL or build tools, try Parallel. It usually gives the most work per CPU second.
- If tail latency matters, for example request handlers with tight p99 targets or heaps of tens of GB where G1's pauses grow, try ZGC (generational in Java 21+, the only mode from 24). Shenandoah is a comparable alternative. Its generational mode is a product feature in Java 25, and Shenandoah is included in most OpenJDK builds (including Temurin), but not in Oracle's JDK. Give either one more heap and spare CPU.
- If the heap is small (a few hundred MB) or you have one CPU, Serial has the lowest overhead and footprint. The JVM already picks it for you in that case.
- If the program allocates little and exits quickly, or you're testing, Epsilon removes GC from the picture.
- Whatever you pick, consider
-XX:+UseCompactObjectHeaderson Java 25 if your heap holds many small objects. It's independent of the collector.
Then measure with your real workload. The micro-benchmark above shows the trade-off, but where your application ends up depends on its allocation rate, live-set size and how many cores it really gets.
Summary
- JDK 25 has six collectors: G1 (default), Parallel, ZGC, Shenandoah, Serial and Epsilon. Choose with
-XX:+Use<Name>GC; Epsilon also needs-XX:+UnlockExperimentalVMOptions. - Check which one is running with
GarbageCollectorMXBeannames,-XX:+PrintFlagsFinalor the first line of-Xlog:gc. - G1 is the default only with 2+ CPUs and about 1792+ MB of memory; otherwise the JVM picks Serial. This matters in small containers.
- Parallel favors throughput, ZGC and Shenandoah favor low pauses at some CPU and memory cost, and G1 sits in between.
- ZGC is generational since Java 21 and only generational since 24 (
-XX:+ZGenerationalis ignored). Generational Shenandoah (-XX:ShenandoahGCMode=generational) is a product feature in Java 25. - Read GC logs with
-Xlog:gc; in production use-Xlog:gc*:file=gc.log:uptime,level,tags:filecount=...,filesize=.... The "after" heap size approximates the live set; regularPause Fulllines mean the heap is too small. - In containers, size the heap with
-XX:MaxRAMPercentageand leave room for native memory. -XX:+UseCompactObjectHeaders(Java 25) shrinks object headers from 12 to 8 bytes and works with every collector.