Video in progress

How many cores does the JVM see in a container with a CPU limit, and how does this affect the GC and thread pools?

The JVM reads the cgroup CPU quota and computes availableProcessors() from it: with limits.cpu: 2 it sees 2 cores. GC threads, the ForkJoin common pool and the pool sizes of many libraries are derived from that, so a very small limit slows down the whole application.

📖 Answer

kubectl exec shop-api-xyz -- jcmd 1 VM.info | grep -i "active processor"
kubectl exec shop-api-xyz -- java -XX:+PrintFlagsFinal -version | grep -E "ParallelGCThreads|ConcGCThreads"

There are two kinds of traps.

The first is a limit below 1 core (500m). The JVM sees 1 core and picks SerialGC (for G1 a machine must be "server-class": at least 2 CPUs and about 1792 MB of memory). The result is unexpectedly long pauses. Choosing the GC explicitly is a good idea: -XX:+UseG1GC.

The second is CFS throttling. The quota is handed out in 100 ms periods. If many threads suddenly run during Spring startup or during GC, the quota runs out early in the period and the process waits for the rest of it. Average CPU looks like 40%, but p99 latency spikes. You can see this in the metric container_cpu_cfs_throttled_periods_total.

What I do:

  • set the CPU limit noticeably above real usage, or remove it entirely if the cluster policy allows (requests stay);
  • if needed, give the JVM an explicit number with -XX:ActiveProcessorCount=N;
  • size pools such as Tomcat threads and HikariCP by a load test, not by core count.

From JDK 19 (also backported to 17.0.5 and 11.0.17), when computing the core count the JVM does not look at CPU shares, that is requests. It looks only at the quota (limits) and the host's cores. In older versions even requests.cpu: 500m affected the JVM.