Sub topic 11
Heap Sizing and Basic Tuning
This chapter assumes you know the generational heap, the main HotSpot collectors (Serial, Parallel, G1, ZGC), and how to read basic GC log lines. It covers how to size the heap, which flags matter, and how to tune in a measured way. The examples target JDK 11 and later.
Tuning starts with a goal
Tuning without a goal produces flag collections that nobody can explain. Pick the goal first. Three metrics describe most goals, and they pull against each other.
| Metric | Meaning | Typical target |
|---|---|---|
| Throughput | Share of time spent running application code rather than GC | 95% or more for batch jobs |
| Latency | Length of individual pauses | p99 pause under 100 ms for services |
| Footprint | Memory the process uses | Fits the container or host limit |
A bigger heap usually improves throughput and reduces pause frequency, but it raises footprint. A collector that works concurrently lowers pauses and costs some throughput and CPU. You cannot maximize all three, so decide which one matters for this application.
Measure before changing anything
Run the application under realistic load with GC logging on, as described in the previous chapter. Then collect three numbers:
- Live set: the heap occupied after a full or mixed collection finishes. This is the data the application really needs.
- Allocation rate: how fast the application creates objects, in MB per second.
- Pause times and frequency: from the log.
The Runtime class gives a quick look at the current sizes from inside the process:
public class MemoryInfo {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
long mb = 1024 * 1024;
System.out.println("Max heap: " + rt.maxMemory() / mb + " MB");
System.out.println("Total heap: " + rt.totalMemory() / mb + " MB");
System.out.println("Free heap: " + rt.freeMemory() / mb + " MB");
}
}Run it twice and compare:
java MemoryInfo
java -Xms256m -Xmx512m MemoryInfoWith no flags, the JVM picks defaults from the machine's memory. Max heap is one quarter of physical RAM, and the initial heap is one sixty-fourth. With flags, Max heap reports roughly 512 MB, and Total heap starts near 256 MB. The reported values can be slightly lower than the flags, because some collectors reserve space that maxMemory() does not count.
The core sizing flags
| Flag | Effect |
|---|---|
| `-Xms<size>` | Initial heap size |
| `-Xmx<size>` | Maximum heap size |
| `-Xmn<size>` | Fixed young generation size |
| `-XX:NewRatio=n` | Old generation is n times the young generation |
| `-XX:SurvivorRatio=n` | Eden is n times each survivor space |
| `-XX:MaxMetaspaceSize=size` | Upper bound for class metadata |
| `-Xss<size>` | Stack size for each thread |
| `-XX:MaxRAMPercentage=p` | Maximum heap as a percentage of available RAM |
Sizes accept the suffixes k, m, and g.
Setting -Xms equal to -Xmx
In servers, the common practice is to set -Xms and -Xmx to the same value. The heap then never resizes, which avoids the pauses and extra full collections that come with growth and shrinkage, and the JVM fails at startup rather than later if the memory is not available. The cost is that the process holds the whole heap from the start. For small tools, desktop applications, or dense container packing, a smaller -Xms is reasonable.
Picking -Xmx
A starting rule is to set the maximum heap to between 2 and 4 times the live set measured after full collections. Less than that and the collector runs constantly. More than that gives diminishing returns and a larger footprint.
Remember that the heap is not the only memory the process uses. The total resident size also includes:
- Metaspace and the code cache
- Thread stacks (
-Xsstimes the number of threads) - Direct byte buffers and native libraries
- GC data structures, which can be sizable for G1 and ZGC
As a rough budget, leave 20 to 30 percent of the container limit for non-heap memory. A 4 GB container with -Xmx4g is likely to be killed by the operating system.
Containers
Since JDK 10 (and backported to 8u191), the JVM reads cgroup limits and sizes itself from the container limit. Use percentage flags so the heap follows the limit:
java -XX:InitialRAMPercentage=50 -XX:MaxRAMPercentage=70 -jar app.jarThe default maximum is only 25 percent, which wastes memory in a container dedicated to one JVM. An explicit -Xmx overrides the percentage flags.
Sizing the generations
The young generation size controls how often minor collections run and how many objects die before promotion.
- A larger young generation means fewer minor collections and gives short-lived objects more time to die. It leaves less room for the old generation.
- A smaller young generation means frequent minor collections and more premature promotion of objects that were about to die.
Premature promotion fills the old generation with garbage and forces expensive old-generation collections. If the log shows the old generation growing steadily while the live set stays flat, suspect a young generation that is too small, or survivor spaces that are overflowing.
The default -XX:NewRatio=2 makes the old generation twice the young generation, so young gets one third of the heap. For Serial and Parallel, adjust with -Xmn or NewRatio.
Do not set -Xmn, -XX:NewSize, or -XX:MaxNewSize with G1 unless you have a specific reason. G1 resizes young regions dynamically to meet its pause goal, and fixing the size disables that adaptation and the pause target with it.
Tuning each collector
Parallel: throughput
Parallel is controlled mainly by goals:
-XX:MaxGCPauseMillis=nsets a pause goal.-XX:GCTimeRatio=nsets the throughput goal. GC time is 1/(1+n) of the total, son=19means 5 percent.-XX:ParallelGCThreads=nsets the number of GC worker threads.
The collector shrinks or grows generations to meet these goals, with the pause goal taking priority.
G1: balanced
G1 is the default from JDK 9. The most useful setting is the pause goal:
java -Xms4g -Xmx4g -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -jar app.jarThe default goal is 200 ms. G1 treats it as a target, not a promise. A very low goal such as 10 ms makes G1 collect fewer regions per cycle, which can reduce throughput and cause the old generation to fill faster than it is reclaimed. When that happens you see Pause Full (G1 Evacuation Failure) or a Full GC in the log, and pauses become far worse than before.
Other G1 flags to know:
-XX:G1HeapRegionSize=nsets the region size (1 MB to 32 MB, a power of two). Objects larger than half a region are humongous and are allocated directly in the old generation, which can fragment it. If the log shows many humongous allocations, raise the region size.-XX:InitiatingHeapOccupancyPercent=nsets the heap occupancy at which concurrent marking begins (default 45). Lower it if marking starts too late and you see full collections.
ZGC: low latency
ZGC targets pauses of a few milliseconds regardless of heap size. In JDK 11 it is experimental on Linux and needs -XX:+UnlockExperimentalVMOptions -XX:+UseZGC. From JDK 15 it is production-ready with -XX:+UseZGC. Its main tuning input is the heap size. ZGC needs headroom so that it can finish a concurrent cycle before the application exhausts free memory. If the heap is too tight, allocation stalls appear in the log and threads wait for memory.
A tuning workflow
Change one thing at a time, and compare runs under the same load. Keep the logs from every run, since a flag that looks helpful in one test often has no effect in the next.
Common mistakes
- Copying flags from the internet. Flags tuned for another workload, JDK version, or collector can be ignored, deprecated, or harmful. Check with
java -XX:+PrintFlagsFinal -version, which prints every flag with its final value. - Setting
-Xmxequal to the container limit. The process exceeds the limit through non-heap memory and the kernel kills it with no Java stack trace. - Calling
System.gc()or relying on it. It requests a full collection and can cause a long pause.-XX:+DisableExplicitGCignores such calls, but some libraries that use direct buffers depend on them. - Fixing a leak with a larger heap. If the live set grows without bound, more memory only delays the
OutOfMemoryError. - Mixing collector flags. Combining flags for two collectors, or enabling two collectors at once, causes the JVM to refuse to start.
- Tuning for the average. Pauses are tail events. Look at the maximum and high percentiles, not the mean.
A worked example
This program allocates short-lived objects and keeps a small set of long-lived ones. It lets you see the effect of heap size on GC frequency.
import java.util.ArrayList;
import java.util.List;
public class AllocDemo {
public static void main(String[] args) {
List<byte[]> retained = new ArrayList<>();
long sink = 0;
for (int i = 0; i < 2_000_000; i++) {
byte[] temp = new byte[10 * 1024]; // short-lived, 10 KB
sink += temp.length;
if (i % 1000 == 0) {
retained.add(new byte[10 * 1024]); // long-lived
}
}
System.out.println("Retained: " + retained.size() + ", sink: " + sink);
}
}Run it with two heap sizes and count the collections:
java -Xms64m -Xmx64m -Xlog:gc:file=small.log AllocDemo
java -Xms1g -Xmx1g -Xlog:gc:file=large.log AllocDemo
grep -c Pause small.log large.logThe 64 MB run logs many more pauses than the 1 GB run, because the young generation is smaller and fills sooner. Each pause is also shorter in the small heap, because less data is involved. This shows the trade-off in practice: a larger heap gives fewer collections, while the cost per collection depends on how much live data must be copied.
Summary of decision points
| Situation | First thing to try |
|---|---|
| Frequent Full GCs, flat live set | Increase `-Xmx` or the young generation |
| Frequent Full GCs, growing live set | Look for a leak with a heap dump |
| G1 pauses exceed target | Raise heap size, then relax `MaxGCPauseMillis` |
| Many humongous allocations | Raise `-XX:G1HeapRegionSize` |
| Allocation stalls in ZGC | Increase heap headroom |
| Container killed with no error | Lower the heap percentage |
Exercise
A service runs in a 2 GB container with -Xms2g -Xmx2g. After a few hours it is killed by the operating system, and the logs show no OutOfMemoryError and a steady live set. What is the likely cause, and what change would you make first?
Show answer
The heap alone fills the container limit, and the JVM also uses memory outside the heap (metaspace, thread stacks, code cache, direct buffers, GC structures). Total process memory exceeds 2 GB, so the kernel kills the process, which is why Java reports no error. Reduce the heap, for example with -XX:MaxRAMPercentage=70 or -Xmx1400m, so that about 25 to 30 percent of the limit remains for non-heap memory, and verify the process's resident size under load.
Exercise
G1 is configured with -XX:MaxGCPauseMillis=10, and the log now shows Full GCs that did not appear with the default setting. Explain why this happened and how you would fix it.
Show answer
With a 10 ms goal, G1 collects too few regions in each pause to keep up with allocation, so the old generation fills and G1 falls back to a Full GC, which pauses much longer. Relax the goal to a realistic value such as 100 to 200 ms, or give the heap more room. If pauses must stay in the low milliseconds, evaluate ZGC instead.