Video in progress

Where does the JVM get the memory limit in a container, and what is the benefit of MaxRAMPercentage over -Xmx?

Java 10+ (8u191+) reads the container limit from the cgroup files and sizes the heap relative to it. -XX:MaxRAMPercentage=75 adjusts the heap automatically even if the limit changes, while a hard-coded -Xmx has to be corrected by hand every time.

📖 Answer

-XX:+UseContainerSupport is on by default. The JVM reads the memory and CPU limits from /sys/fs/cgroup/... (cgroup v2 is fully supported in Java 15+ and 11.0.16+). It is easy to check:

java -XX:+PrintFlagsFinal -version | grep -E 'MaxHeapSize|UseContainerSupport'
java -Xlog:os+container=info -version

If you set nothing, the heap is only 25% of the limit. In a 2 GB container that is a 512 MB heap. That is why many teams are baffled: "Java doesn't eat that much memory, so why the OOM?"

This is what I usually write:

env:
  - name: JAVA_TOOL_OPTIONS
    value: "-XX:MaxRAMPercentage=70 -XX:InitialRAMPercentage=70"
resources:
  limits:
    memory: 2Gi

The benefit: if ops raise the limit from 2 GB to 4 GB, the heap grows by itself, and you don't have to rebuild the image.

Why not 100%: besides the heap, metaspace, thread stacks, the code cache and direct buffers also count toward the container limit. In small containers (512 MB) set the percentage lower (60-65); with big heaps 75-80 is also fine.

CPU matters too: the JVM picks the number of GC threads and the ForkJoinPool size from the CPU count in the limit. If it gets fewer than 2 CPUs, the JVM picks Serial GC.