Video in progress

Strong Middle ⚙️ JVM and memory

With a CPU limit of 2 in a container, how many cores does the JVM see, and how does that affect the GC and thread pools?

Java 10+ (8u191+) reads the cgroup limits and returns availableProcessors() based on the CPU quota. That number sets the size of the GC threads, the JIT compiler threads, ForkJoinPool.commonPool and many framework pools, so if the limit is wrong, everything is sized wrong.

📖 Answer

In Kubernetes you set limits.cpu: 2. The JVM reads the quota from /sys/fs/cgroup/cpu.max (cgroup v2) and Runtime.getRuntime().availableProcessors() returns 2. To check:

java -Xlog:os+container=trace -version
jcmd <pid> VM.info | grep -i -A3 container

What this number affects:

  • ParallelGCThreads, ConcGCThreads: GC parallelism;
  • the JIT's CICompilerCount;
  • ForkJoinPool.commonPool(): parallel streams and CompletableFuture.supplyAsync (when no executor is given);
  • the number of Netty event loops, some Tomcat/Undertow defaults, Micrometer, Reactor schedulers.

The problem cases:

  1. No CPU limit. The JVM sees the cores of the whole node, say 64. 64 GC threads and 63 commonPool threads choke each other in a small pod, and CFS throttling begins. In this case set -XX:ActiveProcessorCount=2 explicitly.
  2. A limit of 0.5 or 1. The JVM sees 1 core. Serial GC may get picked, and the JIT is very slow. Watch throttling with the container_cpu_cfs_throttled_seconds_total metric.
  3. An old JDK. Old updates of JDK 8 and anything before JDK 9 don't know cgroups. Since JDK 19, cpu.shares is no longer taken into account, only the quota.

In a container I usually write the GC (-XX:+UseG1GC) and, if needed, ActiveProcessorCount explicitly, so the behavior stays the same even when the node type changes.