Video in progress
You want to use the Vertical Pod Autoscaler or in-place resize for Java pods in Kubernetes. How does the JVM adapt to memory and CPU changes?
The JVM fixes the maximum heap at startup and doesn't grow it while running. If the memory limit is raised, the heap doesn't change, and if it is lowered there is a risk of OOMKilled. Newer JDKs re-read the CPU count periodically, but pool sizes are often fixed at startup. So in practice VPA for memory works through a restart.
📖 Answer
Memory. MaxRAMPercentage is calculated from the limit at startup and MaxHeapSize is then fixed. If you raise the limit from 2 GB to 4 GB with in-place resize, the JVM doesn't use the extra 2 GB for the heap, and only the room for the native part grows. If you lower the limit (4 → 2 GB), the heap's -Xmx is still 3 GB, and at the next load peak the kernel kills the pod. So for Java pods, lowering memory should be tied to a restart policy (resizePolicy: RestartContainer).
There is some partial flexibility:
- in ZGC
-XX:SoftMaxHeapSizeis manageable: while it runs, you can change the heap "target" within Xmx withjcmd VM.set_flag; - G1 returns free memory to the OS (
G1PeriodicGCInterval), so you can start with a big Xmx and keep real usage small. But that doesn't remove the risk of lowering the limit.
CPU. The JVM takes availableProcessors() from the cgroup, and newer JDKs refresh it periodically. But GC threads, ForkJoinPool.commonPool, Netty event loops and Tomcat pools get their size at startup. If CPU is raised in place, throttling decreases, which helps right away, but the parallelism stays as before.
This is what I usually do:
- run VPA first in
Off/recommendation mode, to see the recommendations and to set the requests; - apply memory changes together with a deploy (new pods with the new limit);
- horizontal scaling (HPA) is usually more natural for Java: each pod has a stable size, and the count changes;
- don't forget that VPA's recommendation comes from RSS, not from the heap: because G1 fills the heap, VPA may think "it needs more".
In short, the JVM is designed for a predetermined budget, not an "elastic" memory model. Choose the autoscaling strategy accordingly.
Sign up to mark studied questions and save your progress.