CS › JVM

JVM process isolation, thread switching, and Linux memory

How HotSpot JVM processes and OS threads share memory on Linux, why context switching hurts CPU caches, and how virtual memory triggers the OOM Killer.

JVM process isolation, thread switching, and Linux memory

When a Spring Boot server pins CPU with flat throughput or exits with code 137 without a Java OutOfMemoryError, JVM flags alone rarely tell the full story. This post explains how Linux manages JVM processes, OS threads, context switching, virtual memory, and the OOM Killer.

Based on Linux Kernel 6.x and Java 21 (HotSpot JVM).

Running Java services on Linux means your JVM sits directly on top of kernel scheduling and virtual memory management. When CPU usage climbs while requests per second stall, or when a container vanishes with Exit Code 137 and no heap dump, the root cause usually lives at the OS layer rather than inside your application code.

How JVM processes and OS threads share memory

When you start a JVM on Linux, the kernel creates a process represented by a task_struct and assigns it an isolated virtual address space containing Code, Data, Heap, and Stack segments. By contrast, a standard HotSpot platform thread (java.lang.Thread) maps 1:1 to a Linux kernel thread (LWP) through pthread (NPTL). The kernel tracks each thread with its own task_struct as well, created via the clone() system call with flags like CLONE_VM and CLONE_FILES so threads share the parent’s address space and open file descriptors.

Because of that sharing, all threads inside one JVM access the same Code, Data, and Heap (JVM Heap and Metaspace), while keeping only their Stack (-Xss) and CPU registers (including the program counter) private.

AspectOS process (JVM)OS thread (Java platform thread)
RoleUnit of memory and FD allocationUnit of CPU execution and scheduling
Address spaceFully isolated virtual address spaceShares parent process address space
Shared resourcesNone (requires IPC)Code, Data, Heap, open FDs
Private resourcesEntire memory space and registersStack (-Xss), registers, PC
Switching costHigh (page table swap)Lower (same address space)

Sharing the heap lets threads reuse connection pools and cached objects without copying data across IPC boundaries. The trade-off shows up as soon as you spawn too many threads: lock contention grows and the kernel spends more time shuffling threads than running your business logic.

Direct and indirect costs of context switching

Whenever the number of runnable threads exceeds available CPU cores, the Linux scheduler (EEVDF in Kernel 6.6+, CFS in earlier releases) preempts threads at the end of a time slice or when they block on I/O and hands the core to another thread.

flowchart TD
    A["Thread A runs (user mode)"] -->|"Time slice expired / I/O wait"| B["Enter kernel mode & save registers"]
    B --> C["Scheduler picks next task_struct"]
    C --> D["Restore Thread B state & return"]
    D -->|"Cache cold misses"| E["Thread B runs (L1/L2 warm-up)"]

Context switching carries two distinct costs:

  • Direct cost: Transitioning between user mode and kernel mode, saving the outgoing thread’s registers and stack pointer into its PCB/TCB (task_struct), and loading the incoming thread’s state.
  • Indirect cost (the real bottleneck):
    • L1/L2 CPU cache cold misses: The new thread brings in different working data, evicting hot cache lines left behind by the previous thread and forcing slower reads from main RAM.
    • TLB flush: Switching between separate processes swaps the page table base register (CR3), invalidating the Translation Lookaside Buffer (TLB) that caches virtual-to-physical translations. Switching between threads in the same JVM avoids a TLB flush because they share an address space, yet it still pays the penalty of L1/L2 cache pollution and CPU pipeline flushes.

Virtual memory, page faults, and the OOM Killer

Linux gives every process its own virtual address space, and the hardware MMU walks page tables to translate 4KB virtual pages into physical RAM frames. Passing -Xmx4g to the JVM does not immediately consume 4GB of physical RAM. Linux uses demand paging: it backs virtual pages with physical frames only when the JVM actually touches them.

  • Minor page fault: The page is mapped to a free RAM frame or already sits in the page cache. No disk I/O occurs, so the fault resolves quickly.
  • Major page fault: The needed page lives on disk swap space, forcing a disk read that adds milliseconds of latency.

That difference is why you should monitor RSS (Resident Set Size)—actual physical memory in use—instead of VSZ (Virtual Size). Because Linux allows memory overcommit, the kernel steps in with the OOM Killer when total RSS (JVM heap plus Metaspace, Direct Buffers, thread stacks, and native overhead) breaches the host or container cgroup memory limit. The kernel scores each process using its memory footprint and oom_score_adj, then sends SIGKILL (9) to the highest-scoring process. When the JVM receives SIGKILL, it terminates instantly with no heap dump, no shutdown hook, and Exit Code 137 (128 + 9).

Inspecting JVM threads and memory on Linux

When throughput drops despite high CPU or a container dies unexpectedly, I check four kernel metrics before changing any JVM flags:

1
2
3
4
5
6
7
8
9
10
11
# 1. List OS threads (LWPs) inside the JVM and their CPU placement
ps -eLf | grep java

# 2. Sample context switches every second for 5 seconds (sysstat package)
pidstat -w -p <JVM_PID> 1 5

# 3. Inspect VSZ, RSS, thread count, and cumulative context switches
grep -E "VmSize|VmRSS|Threads|ctxt_switches" /proc/<JVM_PID>/status

# 4. Check kernel logs for OOM Killer terminations
dmesg -T | grep -i -E "killed process|out of memory"

Pay close attention to the two context-switch counters. voluntary_ctxt_switches (cswch/s) counts how often a thread yielded the CPU voluntarily while waiting on I/O or a lock. nonvoluntary_ctxt_switches (nvcswch/s) counts forced preemptions when a thread’s time slice expired. A spike in nvcswch/s signals too many runnable threads fighting over too few cores. Similarly, if VmRSS climbs well above -Xmx, look for native memory leaks or excessive thread stacks rather than heap growth.

Production pitfalls and checklist

Sizing thread pools into the thousands or leaving swap enabled on a JVM host leads directly to CPU thrashing and multi-second GC stop-the-world pauses.

First, oversized thread pools and -Xss stack bloat. On 64-bit Linux, HotSpot defaults to a 1MB stack per thread (-Xss1m). Spinning up 2,000 active threads can commit up to 2GB of native memory just for stacks while driving nvcswch/s and cache misses high enough to cause thrashing, where adding threads lowers throughput. Keep CPU-bound pools close to core_count + 1, and find the saturation point for I/O-bound pools with load tests instead of guessing.

Second, swap-induced GC pauses. If idle JVM heap pages get pushed out to disk swap, the next GC marking cycle touches the entire heap and triggers a storm of major page faults. A stop-the-world pause that normally takes tens of milliseconds can stretch into multiple seconds. On production JVM nodes, disable swap (swapoff -a) and cap -Xmx around 70–75% of the container memory limit so native memory and OS overhead have room to breathe.

  • Are you tracking VmRSS (or container memory working set) rather than only JVM heap usage?
  • Have you checked pidstat -w under load to verify nvcswch/s isn’t spiking?
  • Are thread pools bounded with explicit upper limits instead of unbounded executors?
  • Is disk swap disabled on your JVM hosts?
  • Does -Xmx leave at least 25–30% of container memory for Metaspace, stacks, and native buffers?
This post is licensed under CC BY 4.0 by the author.