JVM tuning: heap sizing, ergonomics and key flags

Most JVM tuning starts with knowing what the JVM already does on its own. It sizes the heap and chooses a garbage collector from the memory and CPUs it sees, uses several memory areas besides the heap, and lets you inspect and change some flags while it runs. Every number on this page comes from asking a running JVM, including what compact object headers, stack sizes and start-up flags really change.

Share

Contents

What JVM tuning means

Tuning the JVM means trading three goals against each other: latency (how long the application is paused or slowed at any moment), throughput (how much work it completes per CPU second) and footprint (how much memory it uses). A bigger heap usually means fewer garbage collections and better throughput but more memory; a concurrent collector shortens pauses but spends extra CPU. No setting improves all three, so tuning starts with deciding which one matters for the application.

Before changing anything, it helps to know that the JVM already tunes itself. At start-up, ergonomics reads the memory and CPU count it sees, including container limits, and chooses the heap size, the collector, the number of GC and JIT threads, and many other defaults. Every setting is a flag with an origin: DEFAULT, ERGONOMIC (chosen by the JVM), VM_CREATION (given on the command line) or MANAGEMENT (changed while running). Flags come in kinds: standard options such as -Xmx, product -XX flags, and diagnostic or experimental ones that need an unlock flag first.

The effective values can be listed with java -XX:+PrintFlagsFinal -version, or for a running process with jcmd <pid> VM.flags. The programs on this page use both kinds of inspection, so every number comes from a real JVM.

Key settings and when they arrived
SettingSinceBest for
-Xmx, -Xms, -XssJava 1.2Fixed heap and stack sizes
Container awareness (UseContainerSupport)JDK 10, backported to 8u191Sizing from cgroup limits
-XX:MaxRAMPercentageJDK 10, backported to 8u191Heap as a share of the container
Unified logging -Xlog (JEP 158, 271)JDK 9GC and runtime logs
Default CDS archive (JEP 341)JDK 12Faster start-up, on automatically
Ahead-of-time cache (JEP 483)JDK 24Faster start-up of your own application
Compact object headers (JEP 519)JDK 25 (experimental in 24); the default since JDK 27 (JEP 534)Smaller heap for many small objects

Measurements were made on JDK 25 on a 2-core Linux machine.

What the JVM chooses by itself

Without flags, the JVM's ergonomics pick the maximum heap size and the collector based on the machine. Inside a container, the JVM reads the container's memory and CPU limits (container support has been on by default since JDK 10). The program starts child JVMs that pretend to run on machines of different sizes, using -XX:MaxRAM and -XX:ActiveProcessorCount, and reads the resulting settings from -XX:+PrintFlagsFinal.

Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

// Asks child JVMs which heap size and collector they choose for different machines.
// -XX:MaxRAM and -XX:ActiveProcessorCount make the JVM believe it has that much memory
// and that many CPUs, the same way a container limit does.
public class Ergonomics {

    static String flags(String... extra) throws Exception {
        List<String> cmd = new ArrayList<>(List.of(
                Path.of(System.getProperty("java.home"), "bin", "java").toString()));
        cmd.addAll(List.of(extra));
        cmd.addAll(List.of("-XX:+PrintFlagsFinal", "-version"));
        Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
        long maxHeap = 0;
        String gc = "?";
        try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;
            while ((line = r.readLine()) != null) {
                String[] f = line.trim().split("\\s+");
                if (f.length >= 4 && f[1].equals("MaxHeapSize")) {
                    maxHeap = Long.parseLong(f[3]);
                } else if (f.length >= 4 && f[3].equals("true") && f[1].startsWith("Use")
                        && f[1].endsWith("GC") && !f[1].equals("UseMaximumCompactionOnSystemGC")
                        && !f[1].equals("UseAdaptiveSizePolicyWithSystemGC")) {
                    gc = f[1].substring(3);
                }
            }
        }
        p.waitFor();
        return String.format("max heap %5d MB, collector %s", maxHeap / (1024 * 1024), gc);
    }

    public static void main(String[] args) throws Exception {
        System.out.println("8 GB, 4 CPUs:               " + flags("-XX:MaxRAM=8g",
                "-XX:ActiveProcessorCount=4"));
        System.out.println("2 GB, 2 CPUs:               " + flags("-XX:MaxRAM=2g",
                "-XX:ActiveProcessorCount=2"));
        System.out.println("1 GB, 1 CPU:                " + flags("-XX:MaxRAM=1g",
                "-XX:ActiveProcessorCount=1"));
        System.out.println("2 GB + MaxRAMPercentage=75: " + flags("-XX:MaxRAM=2g",
                "-XX:ActiveProcessorCount=2", "-XX:MaxRAMPercentage=75"));
        System.out.println("2 GB + -Xmx1500m:           " + flags("-XX:MaxRAM=2g",
                "-XX:ActiveProcessorCount=2", "-Xmx1500m"));
    }
}

Output:

Output
8 GB, 4 CPUs:               max heap  2048 MB, collector G1GC
2 GB, 2 CPUs:               max heap   512 MB, collector G1GC
1 GB, 1 CPU:                max heap   256 MB, collector SerialGC
2 GB + MaxRAMPercentage=75: max heap  1536 MB, collector G1GC
2 GB + -Xmx1500m:           max heap  1500 MB, collector G1GC
  • By default the maximum heap is a quarter of the available memory: 2,048 MB of 8 GB and 512 MB of 2 GB. In a 2 GB container, that leaves 1.5 GB unused unless you change it, one of the most common container mistakes.
  • With 1 CPU (or less than about 1.8 GB of memory), the JVM considers the machine not "server class" and picks Serial instead of G1, which can surprise people running small containers. This applies up to JDK 26: from JDK 27, G1 is the default in all environments (JEP 523).
  • -XX:MaxRAMPercentage=75 sizes the heap relative to the limit (1,536 MB of 2 GB) and keeps working if the container is resized. A fixed -Xmx overrides everything.

For containers, prefer MaxRAMPercentage between 60 and 80, and leave the rest for the memory areas below. Set -Xms equal to -Xmx when you want the heap reserved up front and no resizing at run time, as is common for servers.

Reading and changing flags at run time

A program can inspect its own flags through HotSpotDiagnosticMXBean, which is what monitoring tools use. The program was started with -Xmx256m -XX:+UseG1GC and prints the value and origin of five flags, then changes one.

Java
import com.sun.management.HotSpotDiagnosticMXBean;
import com.sun.management.VMOption;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

// Reads the effective values of JVM flags from inside the JVM, and changes a manageable one
public class RuntimeFlags {

    public static void main(String[] args) {
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        System.out.println("-X flags given at start-up: " + runtime.getInputArguments().stream()
                .filter(a -> a.startsWith("-X")).toList());

        HotSpotDiagnosticMXBean hs = ManagementFactory.getPlatformMXBean(
                HotSpotDiagnosticMXBean.class);
        for (String name : new String[] {"MaxHeapSize", "UseG1GC", "MaxGCPauseMillis",
            "UseCompressedOops", "HeapDumpOnOutOfMemoryError"}) {
            VMOption o = hs.getVMOption(name);
            System.out.printf("%-28s %-12s origin %-14s manageable %b%n", name, o.getValue(),
                    o.getOrigin(), o.isWriteable());
        }

        // Manageable flags can be changed while the JVM runs, like "jcmd <pid> VM.set_flag"
        hs.setVMOption("HeapDumpOnOutOfMemoryError", "true");
        VMOption changed = hs.getVMOption("HeapDumpOnOutOfMemoryError");
        System.out.println("after setVMOption: " + changed.getValue() + ", origin "
                + changed.getOrigin());
        try {
            hs.setVMOption("MaxHeapSize", "2147483648");
        } catch (IllegalArgumentException e) {
            System.out.println("MaxHeapSize at run time: " + e.getMessage());
        }
    }
}

Output:

Output
-X flags given at start-up: [-Xmx256m, -XX:+UseG1GC]
MaxHeapSize                  268435456    origin VM_CREATION    manageable false
UseG1GC                      true         origin VM_CREATION    manageable false
MaxGCPauseMillis             200          origin DEFAULT        manageable false
UseCompressedOops            true         origin ERGONOMIC      manageable false
HeapDumpOnOutOfMemoryError   false        origin DEFAULT        manageable true
after setVMOption: true, origin MANAGEMENT
MaxHeapSize at run time: VM Option "MaxHeapSize" is not writeable
  • MaxHeapSize is 268,435,456 bytes, which is 256 MB, with origin VM_CREATION because it came from -Xmx. UseG1GC came from the command line too.
  • MaxGCPauseMillis is G1's default pause target of 200 ms, origin DEFAULT.
  • UseCompressedOops is ERGONOMIC: the JVM turned it on because the heap is below about 32 GB, so object references fit in 32 bits. Above that size it is switched off and every reference doubles to 8 bytes, which is why a heap of 31 GB can hold more objects than one of 33 GB.
  • HeapDumpOnOutOfMemoryError is manageable, so it could be switched on while the JVM runs; its origin became MANAGEMENT. jcmd <pid> VM.set_flag HeapDumpOnOutOfMemoryError true does the same from outside. MaxHeapSize is not manageable and the attempt was rejected.

Memory besides the heap

A JVM process uses more memory than its heap. The program allocates fifty 1 MB arrays and a 32 MB direct buffer, then lists every memory pool the JVM reports through its management beans.

Java
import java.lang.management.BufferPoolMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

// Memory the JVM uses: the heap is only part of it
public class MemoryAreas {

    static final List<Object> KEEP = new ArrayList<>();

    public static void main(String[] args) {
        // Use some of each area: heap objects, loaded classes, direct buffers
        for (int i = 0; i < 50; i++) {
            KEEP.add(new byte[1024 * 1024]);
        }
        KEEP.add(ByteBuffer.allocateDirect(32 * 1024 * 1024));

        System.out.printf("%-44s %-8s %8s%n", "memory pool", "type", "used MB");
        for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
            System.out.printf("%-44s %-8s %8.1f%n", pool.getName(),
                    pool.getType() == MemoryType.HEAP ? "heap" : "non-heap",
                    pool.getUsage().getUsed() / 1048576.0);
        }
        for (BufferPoolMXBean b : ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class)) {
            System.out.printf("%-44s %-8s %8.1f%n", "buffer pool: " + b.getName(), "native",
                    b.getMemoryUsed() / 1048576.0);
        }
        System.out.println("loaded classes: "
                + ManagementFactory.getClassLoadingMXBean().getLoadedClassCount()
                + ", live threads: " + ManagementFactory.getThreadMXBean().getThreadCount());
    }
}

Output (G1):

Output
memory pool                                  type      used MB
CodeHeap 'non-nmethods'                      non-heap      1.3
Metaspace                                    non-heap      0.7
CodeHeap 'profiled nmethods'                 non-heap      0.1
Compressed Class Space                       non-heap      0.1
G1 Eden Space                                heap          0.0
G1 Old Gen                                   heap        101.1
G1 Survivor Space                            heap          0.4
CodeHeap 'non-profiled nmethods'             non-heap      0.1
buffer pool: mapped                          native        0.0
buffer pool: direct                          native       32.0
buffer pool: mapped - 'non-volatile memory'  native        0.0
loaded classes: 992, live threads: 6
JVM memory areas
AreaHoldsLimit flag
Heap (Eden, Survivor, Old)Java objects-Xmx, MaxRAMPercentage
Metaspace and compressed class spaceClass metadata-XX:MaxMetaspaceSize (unlimited by default)
Code heapsJIT-compiled code-XX:ReservedCodeCacheSize
Direct buffersByteBuffer.allocateDirect, used by NIO and Netty-XX:MaxDirectMemorySize (defaults to the max heap size)
Thread stacksOne per platform thread-Xss

Two details from the output:

  • The fifty 1 MB arrays occupy about 100 MB of old generation. Each array is slightly larger than G1's 1 MB region size because of its header, so G1 stores it as a humongous object rounded up to two whole regions. Sizing large buffers just below a power of two, or raising -XX:G1HeapRegionSize, avoids the waste.
  • The 32 MB direct buffer appears in a buffer pool, not in the heap, but still counts towards the container's memory limit.

To see all native memory, including GC and thread structures, start the JVM with -XX:NativeMemoryTracking=summary and run jcmd <pid> VM.native_memory summary.

Object headers: footprint you can switch off

Every Java object starts with a header that holds its hash code, lock state, GC age and a pointer to its class: 12 bytes on a 64-bit JVM with compressed class pointers. JDK 25 made compact object headers (JEP 519) a product feature, which shrinks the header to 8 bytes, and JDK 27 turns it on by default (JEP 534). The program allocates two million small records in a child JVM, with and without the flag, and measures the heap used per object.

Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

// Measures heap per small object with and without compact object headers (JDK 25, JEP 519)
public class ObjectHeaders {

    // Run in a child JVM: allocate 2 million small objects and report heap growth per object
    public static class Child {
        record Point(int x, int y) {
        }

        public static void main(String[] args) {
            Runtime rt = Runtime.getRuntime();
            System.gc();
            long before = rt.totalMemory() - rt.freeMemory();
            Object[] keep = new Object[2000000];
            for (int i = 0; i < keep.length; i++) {
                keep[i] = new Point(i, i);
            }
            System.gc();
            long after = rt.totalMemory() - rt.freeMemory();
            long perObject = (after - before - 16L - 4L * keep.length) / keep.length;
            System.out.println(perObject + " " + (keep.length > 0));
        }
    }

    static String run(String... flags) throws Exception {
        List<String> cmd = new ArrayList<>(List.of(
                Path.of(System.getProperty("java.home"), "bin", "java").toString(),
                "-XX:+UseSerialGC", "-Xmx512m"));
        cmd.addAll(List.of(flags));
        cmd.addAll(List.of("-cp", System.getProperty("java.class.path"),
                "ObjectHeaders$Child"));
        Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
        String result = "?";
        try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;
            while ((line = r.readLine()) != null) {
                if (line.matches("\\d+ true")) {          // skip any JVM notices
                    result = line.split(" ")[0];
                }
            }
        }
        p.waitFor();
        return result;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("record Point(int x, int y), bytes per object on the heap:");
        System.out.println("  default headers (12 bytes):        " + run());
        System.out.println("  -XX:+UseCompactObjectHeaders (8):  "
                + run("-XX:+UseCompactObjectHeaders"));
    }
}

Output:

Output
record Point(int x, int y), bytes per object on the heap:
  default headers (12 bytes):        24
  -XX:+UseCompactObjectHeaders (8):  16

With default headers, a Point holding two ints takes 12 + 8 = 20 bytes, rounded up to 24 because objects are aligned to 8 bytes. With compact headers it is 8 + 8 = 16 bytes, a third less. Applications with many small objects, such as caches of records or boxed values, can see a clearly smaller live heap and fewer collections. The flag is off by default in JDK 25, so measure before enabling it in production.

Thread stack size

Each platform thread gets its own stack, 1 MB by default on 64-bit Linux, set with -Xss. The stack limits recursion depth, and its total across threads counts towards the process's memory. The program measures how deep a simple recursive method gets before StackOverflowError, in child JVMs with three stack sizes. It uses -Xint so the JIT does not change the frame sizes between runs.

Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Path;

// How deep can recursion go with different thread stack sizes (-Xss)?
public class StackDepth {

    public static class Child {
        static int depth = 0;

        static void recurse(long a, long b) {
            depth++;
            recurse(a + 1, b + 1);
        }

        public static void main(String[] args) {
            try {
                recurse(0, 0);
            } catch (StackOverflowError e) {
                System.out.println("depth " + depth);
            }
        }
    }

    static long depth(String xss) throws Exception {
        Process p = new ProcessBuilder(Path.of(System.getProperty("java.home"), "bin", "java")
                .toString(), "-Xss" + xss, "-Xint", "-cp", System.getProperty("java.class.path"),
                "StackDepth$Child").redirectErrorStream(true).start();
        long d = -1;
        try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;
            while ((line = r.readLine()) != null) {
                if (line.startsWith("depth ")) {
                    d = Long.parseLong(line.substring(6));
                }
            }
        }
        p.waitFor();
        return d;
    }

    public static void main(String[] args) throws Exception {
        long small = depth("256k");
        long normal = depth("1m");
        long large = depth("4m");
        System.out.printf("-Xss256k: about %,d frames%n", Math.round(small / 1000.0) * 1000);
        System.out.printf("-Xss1m:   about %,d frames%n", Math.round(normal / 1000.0) * 1000);
        System.out.printf("-Xss4m:   about %,d frames%n", Math.round(large / 1000.0) * 1000);
        System.out.printf("4m allows about %.0f times the depth of 1m%n", (double) large / normal);
    }
}

Output (rounded to the nearest thousand frames):

Output
-Xss256k: about 1,000 frames
-Xss1m:   about 8,000 frames
-Xss4m:   about 34,000 frames
4m allows about 4 times the depth of 1m
  • Depth grows roughly in proportion to the stack size: four times the stack allowed about four times the frames. The 256 KB stack allowed fewer frames than a quarter of the 1 MB figure, most likely because a fixed part of every stack is reserved for guard pages that detect the overflow.
  • Real frames are larger than this two-argument method's, so deeply recursive code such as parsers of nested data may need a larger -Xss, or better, an iterative algorithm.
  • A server with 500 platform threads reserves up to 500 MB of address space for stacks at 1 MB each, outside the heap. Lowering -Xss reduces that, and virtual threads, whose stacks live on the heap, avoid it.

Start-up flags

Start-up time matters for command-line tools, serverless functions and scaling up containers. The program compiles a one-line program and measures how long a JVM takes to run it under different flags, using the median of 7 runs.

Java
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// Measures JVM start-up for a tiny program under different flags (median of 7 runs)
public class StartupFlags {

    static long medianMillis(Path dir, String... flags) throws Exception {
        String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
        long[] times = new long[7];
        for (int i = 0; i < times.length; i++) {
            List<String> cmd = new ArrayList<>(List.of(java));
            cmd.addAll(List.of(flags));
            cmd.addAll(List.of("-cp", dir.toString(), "Hello"));
            long start = System.nanoTime();
            Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
            p.getInputStream().readAllBytes();
            p.waitFor();
            times[i] = (System.nanoTime() - start) / 1000000;
        }
        Arrays.sort(times);
        return times[times.length / 2];
    }

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("startup");
        Files.writeString(dir.resolve("Hello.java"),
                "public class Hello { public static void main(String[] a) {"
                + " System.out.println(String.join(\",\", java.util.List.of(\"hi\"))); } }");
        Process javac = new ProcessBuilder(Path.of(System.getProperty("java.home"), "bin",
                "javac").toString(), "-d", dir.toString(), dir.resolve("Hello.java").toString())
                .inheritIO().start();
        javac.waitFor();

        long def = medianMillis(dir);
        long noCds = medianMillis(dir, "-Xshare:off");
        long c1 = medianMillis(dir, "-XX:TieredStopAtLevel=1");
        long serial = medianMillis(dir, "-XX:+UseSerialGC");
        System.out.println("default (class data sharing on): " + def + " ms");
        System.out.println("-Xshare:off (no CDS):             " + noCds + " ms");
        System.out.println("-XX:TieredStopAtLevel=1:          " + c1 + " ms");
        System.out.println("-XX:+UseSerialGC:                 " + serial + " ms");
        System.out.println("CDS saves start-up time: " + (noCds > def));
    }
}

Output (times vary by machine; the comparison held on every run):

Output
default (class data sharing on): 26 ms
-Xshare:off (no CDS):             53 ms
-XX:TieredStopAtLevel=1:          24 ms
-XX:+UseSerialGC:                 25 ms
CDS saves start-up time: true
  • Class data sharing (CDS) maps pre-parsed JDK classes from an archive, and is on by default. Turning it off with -Xshare:off made start-up roughly twice as slow. You can create an archive for your own application's classes with -XX:ArchiveClassesAtExit, or since JDK 24 an ahead-of-time cache (JEP 483).
  • TieredStopAtLevel=1 (only the quick C1 compiler) and UseSerialGC make little difference for a program this short. They can help short-lived tools that do real work, at the cost of peak performance for long-running services.

A sensible starting point

Flags worth setting for a typical containerized service
FlagWhy
-XX:MaxRAMPercentage=75Use most of the container's memory for the heap
-Xlog:gc*:file=gc.log:time,uptime:filecount=5,filesize=20mRotating GC logs, cheap enough for production
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumpsEvidence when memory runs out; see memory leaks
-XX:+ExitOnOutOfMemoryErrorLet the orchestrator restart a broken process instead of leaving it half-working
-XX:+UseCompactObjectHeaders (JDK 25 and 26; on by default from JDK 27)Smaller objects, often a noticeably smaller heap; test it with your workload
A collector flag only if measurements justify itSee the comparison in the GC deep dive

Change one flag at a time and measure with the real workload. Many flags copied from old articles (-XX:+UseConcMarkSweepGC, -XX:PermSize, -XX:+AggressiveOpts) were removed long ago and now stop the JVM from starting.