Skip to content
Tutorials Center
My learning

Topics

Lesson 169 of 201 ยท JVM and Advanced Topics

JVM Options and GC Tuning

Learn the JVM flags that matter: heap sizing with -Xms and -Xmx, container settings, choosing G1, ZGC, Parallel or Serial, GC logs, OOM handling and JFR.

The java command accepts hundreds of options, but a typical production service needs fewer than ten. Knowing which ones matter, and which are folklore copied between blog posts, saves you from both slow servers and mysterious outages. The most important rule is the same as in the Performance lesson: measure first. The JVM's defaults are chosen by engineers who tested a huge range of programs, so most applications run well with almost no tuning. You tune to solve a measured problem, such as pauses that are too long or an out-of-memory crash, not "just in case".

This lesson explains where the memory goes, the options for sizing it, the garbage collectors you can choose from, how to read GC logs, and how to make failures leave evidence behind. It builds on Memory and Garbage Collection, so read that first if heap, young generation and stop-the-world pauses are new terms.

Three kinds of options

JVM options come in three families:

  • Standard options, such as -version, -cp and -jar. They are stable across JVMs.
  • -X options, such as -Xmx and -Xss. They are non-standard but widely supported.
  • -XX options, such as -XX:+UseG1GC. These tune the HotSpot JVM itself. A + or - switches a boolean on or off (-XX:+UseZGC), and a value is set with = (-XX:MaxGCPauseMillis=100). They can change between Java versions, and old ones are removed, so always check the flags against the JDK you run.

A JVM prints options it no longer knows as warnings, and refuses to start on some of them, so a flag copied from a Java 8 blog post can break a Java 25 start. To see every flag and its actual value on your machine, run java -XX:+PrintFlagsFinal -version (a long list). Options can be given on the command line, in the JAVA_TOOL_OPTIONS or JDK_JAVA_OPTIONS environment variables, or in an @argfile for long lists.

Memory areas and their flags

The JVM uses several memory areas, and each has its own limit:

flowchart TB
    subgraph process["JVM process memory"]
        direction TB
        H["Java heap<br/>objects (-Xms, -Xmx)"]
        M["Metaspace<br/>class metadata (-XX:MaxMetaspaceSize)"]
        S["Thread stacks<br/>one per thread (-Xss)"]
        C["Code cache<br/>JIT-compiled code"]
        D["Direct buffers, native libraries,<br/>GC data structures"]
    end

The heap is only one part of what the operating system sees as the JVM's memory.

Flag Meaning
-Xms512m Initial heap size
-Xmx2g Maximum heap size
-Xss512k Stack size for new threads (each platform thread reserves this much address space)
-XX:MaxMetaspaceSize=256m Cap for class metadata (unlimited by default)
-XX:MaxDirectMemorySize=1g Cap for off-heap ByteBuffer.allocateDirect memory
-XX:MaxRAMPercentage=75 Heap maximum as a percentage of available RAM, used if -Xmx is not set

Units are k, m and g. The two flags everybody sets are -Xms and -Xmx. For servers, giving them the same value is common: the heap never has to grow or shrink, which avoids resizing pauses and makes memory use predictable. Leave room beyond the heap: with -Xmx4g the process will use more than 4 GB in total, because of metaspace, thread stacks, the code cache and native memory. A container with a 4 GB limit and -Xmx4g is killed by the operating system, not by a Java OutOfMemoryError, which is a very confusing way to fail.

Containers

Modern JVMs read the CPU and memory limits of a container (cgroup) instead of the host's. By default the maximum heap is 25% of the available memory, which is conservative. Instead of guessing a fixed -Xmx per environment, set a percentage so one image works everywhere:

TEXT
java -XX:MaxRAMPercentage=70 -jar app.jar

Also, the number of CPUs the JVM sees (it sizes GC threads and the common pool from it) comes from the container's CPU limit. Runtime.availableProcessors() tells you what it decided.

Looking at the JVM from inside

A program can read its own limits through Runtime and the management beans. This program prints facts that are true for any JVM, without printing machine-specific numbers:

Java Asking the JVM about its limits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

maxMemory() reflects -Xmx, totalMemory() is what is currently committed, and freeMemory() is the unused part of that. For monitoring, the same numbers are available as JMX beans or through the JFR events.

Choosing a garbage collector

HotSpot ships several collectors. They differ in what they optimize: throughput (total work done per second), latency (the length of pauses) or footprint (memory used). You choose one with a flag:

Collector Flag Best for
G1 -XX:+UseG1GC The default on most servers; a balanced collector with a pause-time goal
ZGC -XX:+UseZGC Large heaps and strict latency; pauses stay very short (typically under a millisecond)
Parallel -XX:+UseParallelGC Batch jobs where only total throughput matters
Serial -XX:+UseSerialGC Tiny heaps, single-CPU containers, command-line tools
Shenandoah -XX:+UseShenandoahGC Low-pause alternative, available in many OpenJDK builds

If you don't choose, the JVM picks: G1 on a "server-class" machine (at least two CPUs and about 1.8 GB of memory), otherwise Serial. That is why a small container may silently run Serial GC. In current JDKs, ZGC is generational: it collects short-lived objects separately, which makes it far more efficient than the first version, and you don't need an extra flag for that.

flowchart TD
    A["Is the GC a measured problem?"] -->|"no"| B["Keep the defaults"]
    A -->|"yes"| C{"What hurts?"}
    C -->|"pauses too long<br/>or very large heap"| D["Try ZGC"]
    C -->|"batch job speed"| E["Try Parallel GC"]
    C -->|"tiny container / tool"| F["Try Serial GC"]
    C -->|"G1 pauses slightly high"| G["Raise heap or tune<br/>MaxGCPauseMillis"]

A decision path. Always benchmark with your own workload before and after.

For G1, the main tuning knob is the pause goal, -XX:MaxGCPauseMillis=200 (the default). It is a goal, not a promise: lower values make G1 do smaller, more frequent collections and cost throughput. For most services, a heap that is big enough and the default settings give the best result; low-level G1 options are rarely needed.

What a collection looks like

You can watch the collector work from inside a program. This one creates a lot of short-lived garbage while a small amount of data stays alive, then uses the collector beans to confirm that collections happened and that the live data survived them:

Java Garbage churn and survivors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Almost all of those 400 MB were unreachable immediately, so the collectors reclaim them cheaply: the work of a young collection is proportional to the live data, not to the garbage. That is why short-lived objects are nearly free in Java, and why long-lived caches that keep growing are the costly case.

Reading GC logs

The unified logging framework (-Xlog) prints what the JVM is doing. For GC, this is the one flag worth always enabling in production, because its overhead is tiny:

TEXT
java -Xlog:gc*:file=gc.log:time,uptime,level,tags:filecount=5,filesize=20m -jar app.jar

A short line looks like this (G1):

TEXT
[2.514s][info][gc] GC(12) Pause Young (Normal) (G1 Evacuation Pause) 412M->96M(1024M) 8.317ms

Read it from left to right: uptime, the collection number, the kind of pause, heap before -> after (committed size) and how long the application was stopped. Things to look for:

  • Pause times longer than your latency budget.
  • The "after" number growing over time after full or mixed collections: a sign of a memory leak.
  • Frequent full GCs: the heap is too small or the live set is too big.
  • High frequency of young collections with small gains: the allocation rate is huge; look for avoidable garbage (boxing, copies) with a profiler.

Tools such as GCViewer, GCeasy and the JFR viewer turn logs into graphs.

Making failures leave evidence

An OutOfMemoryError is an error, not an exception, but a program can catch it and survive if the allocation that failed was a one-off. This example asks for an array no heap can hold and proves that the JVM carries on:

Java Surviving an OutOfMemoryError

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In a real incident the failure is not so convenient, and you want data about what filled the heap. These options make the JVM write it down for you:

TEXT
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/var/dumps/
-XX:+ExitOnOutOfMemoryError
-Xlog:gc*:file=/var/log/app/gc.log

The first two save a heap dump (a snapshot of every live object) when the heap runs out, to analyze later with a tool such as VisualVM or Eclipse MAT (see Profiling with JFR and VisualVM). ExitOnOutOfMemoryError ends the process so an orchestrator such as Kubernetes or systemd restarts it; a service that has thrown an OOM in an arbitrary thread is often half-broken, and a clean restart is safer than limping on. Make sure the dump directory has enough disk space for a file as large as the heap.

Other flags worth knowing

  • -XX:+AlwaysPreTouch: touch every heap page at startup so the first requests don't pay for page faults. Slower start, steadier latency.
  • -XX:NativeMemoryTracking=summary: track JVM-internal native memory; read it with jcmd <pid> VM.native_memory. Useful when the process is bigger than the heap explains.
  • -XX:+UseStringDeduplication: lets G1 and others share identical string contents. Helps for apps holding many duplicate strings; test the effect.
  • -XX:+UseCompactObjectHeaders: smaller object headers (8 bytes instead of 12), saving memory for object-heavy applications. Available as a product feature in recent JDKs; measure before adopting.
  • -XX:StartFlightRecording: starts the low-overhead profiler (next lesson).
  • -Xshare and class-data/AOT caches: speed up startup by reusing preprocessed class data.
  • -XX:+DisableExplicitGC: ignores System.gc() calls. Rarely needed; calling System.gc() yourself is almost always a mistake anyway.

Copied flag lists are the biggest source of bad JVM configuration. Flags from old blog posts (-XX:+UseConcMarkSweepGC, -XX:MaxPermSize, -XX:+UseParNewGC) no longer exist, and many tuning flags that helped an older collector make a modern one slower. Start with the defaults plus the heap size, GC logging and OOM options above. Add anything else only because a measurement told you to.

A sensible starting point

For a typical containerized service on a current JDK:

TEXT
java -XX:MaxRAMPercentage=70 \
     -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps \
     -XX:+ExitOnOutOfMemoryError \
     -Xlog:gc*:file=/logs/gc.log:time,uptime:filecount=5,filesize=20m \
     -jar app.jar

Run it under realistic load, read the GC log, and change one thing at a time. If you then see a specific problem, you have a reason to reach for a flag from this lesson. For the broader picture of structuring and shipping a Java service, see Build Tools and Logging.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A container has a 2 GB memory limit and the app runs with -Xmx2g. What is the likely result under load?

    The JVM also uses memory for metaspace, thread stacks, the code cache and native buffers. The container limit counts all of it, so leave headroom or use a percentage like MaxRAMPercentage.
  2. 2. What does -XX:+UseZGC choose?

    ZGC does most of its work concurrently with the application, so pauses stay very short. It trades some CPU and memory for latency.
  3. 3. Which option writes a snapshot of the heap when the JVM runs out of memory?

    The heap dump captures every live object at the time of the error, so you can see what was filling the heap. Combine it with HeapDumpPath.
  4. 4. The GC log shows the heap after each full collection getting larger every hour. What does this suggest?

    The size after collection approximates the live set. If it keeps growing, objects are being retained when they should be released.
  5. 5. What is the best way to approach JVM tuning?

    Defaults are well tested, and flags change between versions. Measure, change one thing, and measure again.

Summary

  • JVM options are standard, -X or -XX; check them against your JDK version, and see actual values with -XX:+PrintFlagsFinal.
  • The heap is only part of process memory; size -Xmx (or -XX:MaxRAMPercentage in containers) with headroom for metaspace, stacks, code cache and native memory.
  • Defaults pick G1 on server-class machines and Serial on small ones. ZGC targets low latency, Parallel targets batch throughput.
  • Enable GC logging with -Xlog:gc*, and read pauses, before/after heap sizes and the trend of the live set.
  • Use -XX:+HeapDumpOnOutOfMemoryError and -XX:+ExitOnOutOfMemoryError so failures leave evidence and the process restarts cleanly.
  • Tune only for a measured problem, one change at a time.

Next: Profiling with JFR and VisualVM, where you find out what the JVM is actually spending time on.