Skip to content

JVM tuning for production: heap, GC, and container limits

Set heap sizes correctly under cgroup limits, pick a GC, and surface the metrics that tell you whether the JVM is healthy.

A Java service that runs out of heap mid-request fails a request; a service whose GC pauses are 8 seconds long fails a fleet. Modern JVMs are aware of cgroup memory limits and ship with a competent default GC, but the defaults are conservative — production tuning is about giving the JVM more of the host than the default 25% and picking a GC whose latency profile matches the workload. This article covers the heap math, GC choice, and the JVM flags that actually matter.

How to verify

Inspect the running JVM and the host’s view of it:

java -version
jps -v
jcmd <pid> VM.flags
jcmd <pid> GC.heap_info
cat /sys/fs/cgroup/memory.max 2>/dev/null || cat /sys/fs/cgroup/memory/memory.limit_in_bytes
free -h

If VM.flags shows -Xmx256m on a 4 GiB container, the JVM picked a tiny heap because no -Xmx was set and the container-aware defaults kicked in conservatively. That is the most common production “the GC is bad” misdiagnosis.

What’s happening

The JVM heap is the region where objects live. The young generation (eden + survivor spaces) holds short-lived objects; the old generation holds objects that have survived a few collections. The GC reclaims memory by tracing reachability — pause-the-world phases are necessary for safety. Different GCs trade pause time for throughput differently.

Container-aware JVMs (Java 10+) read cgroup memory limits and set MaxRAMPercentage defaults that occupy 25% of the limit. On a 4 GiB container that is a 1 GiB heap, leaving 3 GiB unused by the JVM (and arguably by anything). For a JVM workload that wants the box, set -XX:MaxRAMPercentage=75.0 to claim 75% of the cgroup limit as heap, leaving 25% for metaspace, threads, and the C heap.

GC choice in 2026: G1 is the default and a good choice for heaps up to ~32 GiB with mixed workloads. ZGC (-XX:+UseZGC) and Shenandoah (-XX:+UseShenandoahGC) are concurrent collectors with sub-millisecond pauses, useful for very large heaps or latency-sensitive services. Parallel GC is still the throughput champion for batch workloads where pauses do not matter.

The fix

  1. Compute the heap budget. On a 4 GiB container running just the JVM:

    heap     = ~75% of cgroup memory = 3072 MiB
    metaspace + threads + C heap = ~768 MiB
    OS slack = ~256 MiB (already excluded by cgroup)

    Stick to MaxRAMPercentage rather than absolute -Xmx so the same image scales across container sizes.

  2. Set the heap explicitly and pick a GC. For a typical web service:

    -XX:InitialRAMPercentage=75.0
    -XX:MaxRAMPercentage=75.0
    -XX:+UseG1GC
    -XX:MaxGCPauseMillis=200
    -XX:G1HeapRegionSize=8m

    MaxGCPauseMillis is a target, not a guarantee. G1 will tune its young-generation sizing to hit it on average; explicit -Xmn overrides this and is usually a mistake.

  3. For latency-critical workloads, swap G1 for ZGC:

    -XX:+UseZGC
    -XX:+ZGenerational
    -XX:MaxRAMPercentage=75.0

    ZGC’s Generational mode (Java 21+) is the modern default — it improves throughput dramatically over the original single-generation ZGC.

  4. Surface GC metrics. Add JFR (Java Flight Recorder) flight recording or expose /actuator/metrics (Spring) or /q/metrics (Quarkus):

    -XX:+FlightRecorder
    -XX:StartFlightRecording=settings=profile,duration=60s,filename=/var/log/app/jfr.jfr

    Capture a 60 s JFR every hour via a sidecar or cron, archive the files, and feed Mission Control or an APM tool to spot pause spikes before they become incidents.

  5. systemd unit with the flags. /etc/systemd/system/myapp.service:

    [Service]
    User=myapp
    WorkingDirectory=/opt/myapp
    Environment=JAVA_OPTS="-XX:MaxRAMPercentage=75.0 -XX:+UseG1GC -XX:MaxGCPauseMillis=200 \
      -Xlog:gc*:file=/var/log/myapp/gc.log:time,uptime,level,tags:filecount=10,filesize=20m"
    ExecStart=/usr/lib/jvm/java-21-openjdk-amd64/bin/java $JAVA_OPTS -jar /opt/myapp/app.jar
    Restart=on-failure
    MemoryMax=4G

    MemoryMax=4G is the cgroup ceiling — the JVM will read that and size accordingly.

Operational notes

  • -Xmx and -XX:MaxRAMPercentage together do not coexist gracefully — -Xmx wins if both are set. Use one or the other consistently across environments.
  • The Metaspace (where class metadata lives) is unbounded by default and can grow until the cgroup OOMs. Set -XX:MaxMetaspaceSize=512m on services that load many classes (Groovy DSLs, Spring with many beans).
  • Heap dumps on OOM are gold for debugging but huge. -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/log/myapp/heapdump.hprof writes one; ship it off the host before disk fills.
  • The JVM’s direct memory (used by NIO byte buffers) is outside the heap and not bounded by -Xmx. Netty-heavy services can OOM the cgroup with no heap pressure — set -XX:MaxDirectMemorySize=512m explicitly.
  • jstack <pid> is the underused debugging tool. On a hung service, a single jstack tells you whether threads are blocked in GC, on a lock, or on an external call.

For monitoring the JVM through Prometheus, the matching exporter (jmx_exporter or micrometer-registry-prometheus) is the standard path. Stack Harbor’s managed operations practice keeps JVM flags in configuration management, with GC log retention as a default — when the next pause incident lands, the logs are already there to investigate.