How to Tune G1 GC Without Cargo Culting Flags in Java
Tune G1 by sizing the heap from the container, setting a pause goal and fixing humongous allocations, and leave out the flags that only make it worse.

A list of JVM flags in a launch script usually has a history: a problem once, a search, a paste. Years later nobody knows which flags matter, and some of them prevent the collector from doing its job. G1 is designed to tune itself against a pause goal. This post gives the short list worth setting, the order to change things in and the flags to remove. Know what the collector does first: Java garbage collection explained. And choose it on evidence: G1 vs ZGC vs Shenandoah vs Parallel.
Step 0: measure
Without a GC log you are guessing. Turn it on (-Xlog:gc*:file=gc.log) and read it with reading GC logs. The questions: what is the longest pause, how often do collections happen, is there a Full GC, and what is the heap after collection? If the answers are acceptable, stop. Nothing needs tuning.
Step 1: size the heap from the container
java -XX:MaxRAMPercentage=65 -jar app.jarIn a container, the JVM reads the memory limit and takes the given percentage as the maximum heap. That leaves the rest for Metaspace, thread stacks, the code cache and direct buffers, which add up as described in JVM memory areas. A value between 50 and 75 percent is the usual range; measure the non-heap usage to choose. A fixed -Xmx copied from another service ignores the limit and is the most common cause of container kills, as in OOMKilled Java containers.
Step 2: set a realistic pause goal
-XX:MaxGCPauseMillis=200200 ms is the default, so setting it changes nothing. If your latency budget needs shorter pauses, lower it gradually, for example to 100, and check the log. G1 meets a lower goal by shrinking the young generation, which makes collections more frequent and raises the CPU cost. A goal of 10 ms on G1 is unrealistic for a large heap; if you need that, consider ZGC.
Step 3: fix humongous allocations
An object larger than half of a G1 region is humongous. It is allocated directly in old space and can trigger early collections. In the log you see G1 Humongous Allocation as a cause. Region size is chosen from the heap size (1 MB to 32 MB). Options:
- Allocate smaller pieces: stream data instead of reading it into one array.
- Reuse large buffers.
- Increase the region size with
-XX:G1HeapRegionSize=16mso the object is no longer humongous. The value must be a power of two, and bigger regions reduce the number of regions.
Do this only if the log shows the cause repeatedly.
Step 4: pre-touch and warm-up flags, only when measured
For a latency-sensitive service that suffers page faults as the heap grows, -Xms equal to -Xmx avoids resizing, and -XX:+AlwaysPreTouch commits the pages at startup. Both lengthen startup and use memory immediately. Use them when the log or monitoring shows resizing or first-touch costs.
Flags to remove unless measured
| Flag | Why it hurts |
|---|---|
-Xmn, -XX:NewSize, -XX:NewRatio | Fix the young generation size, defeating adaptive sizing |
-XX:InitiatingHeapOccupancyPercent | Adaptive by default; a fixed value can cause Full GCs |
-XX:ParallelGCThreads | The JVM sets it from the CPU count; wrong values waste CPU |
-XX:+UseStringDeduplication | Costs CPU; only useful with a lot of duplicate strings |
-XX:-UseAdaptiveSizePolicy | A Parallel-collector flag with no use under G1 |
-XX:+DisableExplicitGC | Hides System.gc() calls, but breaks direct buffer cleanup patterns |
If you inherit a script, remove the flags in groups and compare the GC log under the same load. Many scripts contain flags that are the default or that apply to collectors no longer used.
A baseline
For a typical service in a container, this is a complete configuration:
java -XX:MaxRAMPercentage=65 -Xlog:gc*:file=gc.log:time,uptime,level,tags -jar app.jarEverything else is a response to something the log showed.
A program to experiment with
Tuning advice is easiest to judge on a workload you can rerun. This program mimics a service with a steady allocation rate, a bounded cache of long-lived objects and an occasional large buffer:
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.ThreadLocalRandom;
public class AllocationWorkload {
static final Deque<byte[]> cache = new ArrayDeque<>();
public static void main(String[] args) throws Exception {
long end = System.nanoTime() + Long.parseLong(args[0]) * 1_000_000_000L;
long iterations = 0;
while (System.nanoTime() < end) {
byte[] request = new byte[ThreadLocalRandom.current().nextInt(512, 8192)];
if (iterations % 50 == 0) {
cache.addLast(new byte[32 * 1024]);
if (cache.size() > 20_000) {
cache.removeFirst();
}
}
if (iterations % 100_000 == 0) {
byte[] large = new byte[12 * 1024 * 1024]; // humongous with small regions
large[0] = 1;
}
iterations++;
}
System.out.println("iterations: " + iterations);
}
}Run it for 60 seconds with a fixed heap, and treat the GC log as the result:
java -Xmx1g -Xlog:gc*:file=base.log:time,uptime,level,tags AllocationWorkload.java 60The 12 MB buffers allocate directly in old space on a 1 GB heap with the default 1 MB regions, so base.log contains G1 Humongous Allocation causes. That gives you a real symptom to treat in the next step.
Change one thing and compare
Each experiment is the same command with exactly one difference, and a log file named for it:
java -Xmx1g -XX:G1HeapRegionSize=16m -Xlog:gc*:file=region16.log:time,uptime,level,tags AllocationWorkload.java 60
java -Xmx1g -XX:MaxGCPauseMillis=50 -Xlog:gc*:file=pause50.log:time,uptime,level,tags AllocationWorkload.java 60Then compare the same three numbers from each log: the longest pause, the total paused time and the count of collections.
for f in base region16 pause50; do
echo -n "$f: "
grep -E "Pause (Young|Full|Remark|Cleanup)" $f.log \
| awk '{ms=$NF; sub("ms","",ms); t+=ms; if (ms>m) m=ms; n++} END {printf "collections=%d total=%.0f ms max=%.1f ms\n", n, t, m}'
doneThe result is a small table you can paste into a pull request: the flag, what the log showed before and after, and the workload used. A flag that cannot show a better row in that table does not belong in the launch script. This is also the answer to "who added this flag": the commit that adds it carries its evidence.
Check what you are actually running
Before and after any change, confirm the JVM received what you meant and chose the collector you expect. Ergonomics can pick Serial on a machine it considers small, and containers with under two CPUs or about 1.8 GB of memory are the common case:
java -XX:+PrintFlagsFinal -XX:MaxRAMPercentage=65 -version 2>/dev/null \
| grep -E "UseG1GC|UseSerialGC|MaxHeapSize|G1HeapRegionSize|MaxGCPauseMillis"jcmd <pid> VM.flags | tr ' ' '\n' | grep -E "UseG1GC|UseSerialGC|G1HeapRegionSize"If a service with one CPU shows UseSerialGC in the output, no G1 flag in your script is doing anything. Force the collector with -XX:+UseG1GC only when you have decided a pause-goal collector is right for that size, and note that on such a small container the right move may be a second CPU, not a flag.
Concurrent cycles that start too late
Full GCs in a G1 log often come from marking that starts too late for the allocation rate. The log shows to-space exhausted or a Pause Full (G1 Compaction Pause) after Concurrent Mark Cycle lines that began when the heap was already nearly full. Before touching the initiating threshold, ask whether the live set fits at all. This sketch shows how to read it from the log you already have:
grep -E "Pause Full|to-space|Concurrent Mark Cycle|Pause Young \(Concurrent Start\)" base.log | head -20If the heap after a concurrent cycle is above 70 percent of the maximum, the heap is too small for the live set, and the honest fix is a larger heap or less retained data. If the heap after collections is low and Full GCs still occur, the allocation rate outruns marking, and lowering the heap occupancy threshold or giving the concurrent threads more CPU is a reasonable, measured experiment. The decision comes from the number after the arrow in the log, not from a recipe.
When the answer is a different collector
If the tail latency target is a few milliseconds and the heap is large, tuning G1 is the wrong exercise. Generational ZGC aims for sub-millisecond pauses with a small configuration surface:
java -XX:+UseZGC -Xmx8g -Xlog:gc:file=zgc.log -jar app.jarRun the same workload and compare. ZGC trades some throughput and memory overhead for pause time, so the comparison must include your CPU use and total latency distribution, not only the pause line. If the table says ZGC wins on the metric you care about, switch the collector and delete the G1 flags, which are meaningless under it. A collector change backed by numbers is less risky than twenty flags backed by a forum post.
Where this does not apply
A memory leak or a bad allocation pattern is not fixed by tuning; reduce retention first. On heaps beyond many gigabytes with strict tail latency, switch collectors rather than tune. The G1 tuning chapter of the HotSpot guide explains each setting, and the [java command reference](https://docs.oracle.com/en/java/javase/25/docs/specs/man/java.html) lists defaults.


