SteelReed

Search

Search posts, questions…

3. Advanced Java

Virtual memory, page cache, swap and the JVM in containers

Virtual memory, page tables, the TLB and page faults; overcommit, swap and the OOM killer; why a JVM's RSS is bigger than its heap and how to size a container memory limit; the page cache and mmap; CPU caches, cache lines, false sharing and why the Java Memory Model exists.

18 Nov 20268 min readSenior

–

1. The problem

A Spring Boot pod with a 1 GiB limit and -Xmx1g gets OOMKilled every evening, though the heap dashboard shows 600 MB. No heap dump, no OutOfMemoryError. Meanwhile free -m on the node reports 212 MB "free" and someone asks for more RAM.

2. Key idea

Every process sees its own virtual address space; the kernel's page table maps each 4 KB page to real RAM, assigned only when the page is first touched (page fault). When RAM runs low the kernel reclaims in order: drop clean page cache, push heap pages to swap, finally SIGKILL a process. In a container, the limit is the cgroup's memory.max.

OutOfMemoryError: Java heap space Container OOMKilled (exit 137)
Who detects it the JVM: heap full after GC the kernel: cgroup RSS over the limit
Heap dump yes (-XX:+HeapDumpOnOutOfMemoryError) no: SIGKILL
Cause heap leak, small -Xmx heap + off-heap over the limit
Fix analyze the heap dump shrink heap relative to the limit, measure with NMT

2.1 What share of the limit should the heap get?

RSS is heap plus metaspace (100–200 MB for Spring Boot), code cache, thread stacks, direct buffers (Netty, Kafka client) and GC structures.

Approach Use when Don't use when
Default 25% not measured yet, want safety big pods: 2 GB gets a 512 MB heap
-XX:MaxRAMPercentage=75 typical web services lots of direct memory or threads
Fixed -Xmx measured under real load the limit changes often (two places to edit)
Swap on JVM nodes always avoid: GC touching swapped pages turns 50 ms pauses into seconds

3. In Java

$ java -XX:+PrintFlagsFinal -version | grep MaxHeapSize     # inside a -m 512m container
   size_t MaxHeapSize = 134217728        # 128 MB = 25% of the limit
 
$ java -XX:NativeMemoryTracking=summary -XX:MaxRAMPercentage=75 -jar app.jar
$ jcmd <pid> VM.native_memory summary    # read committed, not reserved
Java Heap   committed=512MB
Class       committed=160MB              # metaspace
Thread      committed=125MB              # 250 threads
Other       committed=100MB              # direct buffers
 
$ free -m
Mem:  total 15890  used 6120  free 212  buff/cache 9558  available 9310
                                          # ~9 GB left: page cache can be dropped

Flags worth having: -XX:+ExitOnOutOfMemoryError, and -XX:MaxDirectMemorySize if you use many direct buffers. Other languages: Go sets GOMEMLIMIT to the limit; Node.js sets --max-old-space-size.

Page cache, mmap and false sharing
  • Page cache: write() only changes the page in RAM and marks it dirty; it reaches disk seconds later unless you fsync(). Later reads skip the disk. PostgreSQL and Kafka rely on it, so don't give a Kafka broker's JVM a huge heap.
  • Page cache counts toward container memory: alert on container_memory_working_set_bytes, the number kubelet uses to evict pods, not on usage.
  • mmap (FileChannel.map()) maps a file into memory: reading the array reads page cache, no syscall, no copy.
  • False sharing: L1 and L2 are per core and synchronized per 64-byte cache line. Two threads writing adjacent variables keep invalidating each other's line. Fix with padding or @Contended; LongAdder does exactly this.

4. Working with AI

Hand to AI: reading NMT output and kubectl describe pod, building a memory budget table from measurements, writing a Prometheus alert on the working set.

Check yourself in AI-written config:

  • -Xmx (or MaxRAMPercentage) leaves at least 25–30% of the limit for off-heap memory.
  • The limit is based on measurements under real load (RSS, NMT committed), not on -Xmx.
  • Nodes running JVMs have swap off, or a very low vm.swappiness.
  • Container memory alerts use the working set, not free or usage.

5. Exercises

Exercise 1: Compute a memory limit

A Spring Boot service under real load: ~400 MB live data on the heap after a full GC, 160 MB metaspace, ~250 threads, ~100 MB direct memory. The AI proposes -Xmx1g and a 1Gi limit. Review it and give your numbers.

Solution 1

A 1Gi limit equal to the heap is a guaranteed OOMKilled. Add up the parts:

Part Estimate
Heap (~2.5× live data) 1,024 MB
Metaspace 160 MB
Code cache 80 MB
Thread stacks (250 × ~0.5 MB) 125 MB
Direct buffers (capped by MaxDirectMemorySize=128m) 100 MB
GC + malloc + other 160 MB
Total ~1.65 GB

Add 20% headroom: limit 2Gi, -Xmx1g. Recheck with NMT and the working set after a week in production.

Exercise 2: Read an incident

The pod from section 1: kubectl describe pod shows Last State: Terminated, Reason: OOMKilled, Exit Code: 137. Heap dashboard 600 MB, -Xmx1g, limit 1Gi. Diagnose it, say what to do in 15 minutes, fix the root cause.

Solution 2
  • Diagnosis: the kernel killed the process because RSS exceeded the limit; 600 MB of heap plus metaspace, stacks and direct buffers passed 1 GiB. No heap dump because SIGKILL gives the JVM no chance.
  • 15 minutes: raise the limit to 1.5Gi (or lower -Xmx to 700m) to stop the restarts.
  • Root fix: enable NMT, measure each region under real load, reset -Xmx and the limit as in Exercise 1; add MaxDirectMemorySize and a working-set alert at 85% of the limit.

Summary

  • Virtual memory is assigned lazily: watch RSS, not VSZ.
  • Reclaim order: page cache, swap, OOM killer.
  • OutOfMemoryError leaves a heap dump; OOMKilled (exit 137) doesn't.
  • Memory limit = heap + off-heap, measured with NMT, plus 20–30%.
  • JVMs and swap don't mix; low "free" RAM is normal.

Further reading: I/O models and epoll.

Practice interview questions on this topic

All Concurrency questions →All JVM questions →

Loading comments…