Tech Interview RoomStudy guides

Docker

How does the JVM behave in containers, and why might a pod be OOMKilled even though the heap looks fine?

Advanced · 2 min read · Lesson 5 of 6 in Docker

Container awareness

Since JDK 10 (and backported to 8u191), the JVM reads cgroup limits (v1 and v2) for CPU and memory instead of the host's. java -XshowSettings:system -version shows what it detected.

  • Default max heap is 25% of the container memory limit, often too small for a dedicated container. Set -XX:MaxRAMPercentage=70..75 (and InitialRAMPercentage) instead of hard-coding -Xmx, so the heap follows the limit.
  • CPU limits determine availableProcessors(), which sizes GC threads, the common ForkJoinPool and many frameworks' thread pools. With under 2 CPUs and under about 1.8 GB the JVM may pick the Serial collector; set the collector explicitly.

OOMKilled vs OutOfMemoryError

  • java.lang.OutOfMemoryError is thrown by the JVM when the heap (or Metaspace, direct memory) limit is reached; you see a stack trace and can capture a heap dump.
  • OOMKilled (exit code 137) is the kernel killing the process because the whole container exceeded its cgroup memory limit. No Java error, no heap dump.

Why OOMKilled with a healthy heap

The process uses far more than the heap: Metaspace, code cache, thread stacks (about 1 MB × number of threads), GC structures, direct buffers (Netty, NIO), JNI and native libraries, and glibc malloc arenas. With -Xmx at 90% of the limit, the rest does not fit.

Fixes

  • Leave headroom: heap around 70–75% of the limit, and more headroom for thread-heavy or Netty-heavy applications.
  • Cap other areas (-XX:MaxMetaspaceSize, -XX:MaxDirectMemorySize, -Xss), and reduce thread counts.
  • Diagnose native usage with Native Memory Tracking (-XX:NativeMemoryTracking=summary, then jcmd <pid> VM.native_memory summary).
  • On glibc, set MALLOC_ARENA_MAX=2 to limit malloc arena growth, or use jemalloc.
  • In Kubernetes set memory request = limit for predictable behaviour.

Follow-up questions interviewers ask

Try answering each one before you open it.

Should you set CPU limits for Java services in Kubernetes?

CPU limits are enforced by CFS quota: when a container uses its quota within a 100 ms period it is throttled until the next period, which causes latency spikes, especially during GC and JIT bursts. Many teams set CPU requests (for scheduling and fair share) but no CPU limits for latency-sensitive services, and use -XX:ActiveProcessorCount to size thread pools explicitly. Others keep limits for strict multi-tenant fairness. Either way, monitor container_cpu_cfs_throttled_periods_total.