Volume 1 Companion: Foundations of ComputingPractice for Volume 1
0 / 0

Workbench / Volume 1 Companion: Foundations of Computing

V1·08

Operating Systems

Companion to Volume 1, chapter 08: how processes, concurrency and files connect; new angles (a bank teller's window as system calls, a restaurant's one bathroom key as a mutex, a gridlocked junction as deadlock, an office outbox tray as the page cache, a restaurant pager as epoll); what the chapter simplifies, from virtual threads that run 47× slower inside `synchronized` to a file lock that a script ignores and two processes that lose 40% of a shared log; the theory behind it (linearizability, the four deadlock conditions as a design tool, the end-to-end argument, the cost of copying); the JDK's native code for `force()` and `lock()`; four debugging drills; interview questions with how to approach each.

6 sections · ~18 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 08 has three strands. Processes and threads are how the kernel shares one machine among many programs. Concurrency and memory are what happens when several threads share an address space, and how virtual memory gives each process its own. Files and I/O are the kernel's abstractions over storage and devices, and the models for waiting on them.

processes and threads concurrency and memory files and I/O kernel, user space privilege boundary system calls the only door in processes fork · exec · wait scheduling time slices · switches signals async notifications threads share one address space race conditions interleavings mutex, semaphore one at a time · n at a time condition variables wait for a state deadlock circular wait virtual memory pages · faults · TLB mmap files as memory file descriptors everything is a file inodes, links names point to inodes page cache write() lands here fsync, journaling what survives power loss blocking, non-blocking who waits epoll, io_uring many sockets, few threads crossed by create share CPU interrupted by delivered to prevented by + waiting misused maps files refer to cached in flushed by scaled by goes deeper: ch7 the MMU and caches underneath · ch9 sockets are file descriptors · Volume 3 ch 35: Java threads exercises: P1–P12 count system calls, cost threads, build monitors, leak descriptors and test fsync
Concept map of chapter 08: processes and threads (kernel and user space, system calls, processes, fork and exec, scheduling and context switches, signals, threads), concurrency and memory (race conditions, mutexes and semaphores, condition variables, deadlock, virtual memory and page tables, page faults, mmap) and files and I/O (file descriptors and the VFS, inodes and links, the page cache and fsync, journaling, blocking and non-blocking I/O, epoll and io_uring), with links such as threads sharing an address space causing races, and the page cache sitting between write() and the disk.

The links worth remembering:

  • System calls are the only way in. Every file, socket, thread, page of memory and signal handler your program uses was obtained through a system call. Counting and timing them (strace, Chapter Exercises P1) is the most direct view of what a program asks of the OS.
  • Threads share everything, so they race; processes share nothing, so they must communicate. The concurrency strand exists because threads share an address space. Two processes sharing a file meet the same problems through the filesystem (Gaps 2 and 3).
  • write() returning is not durability. Data goes to the page cache first and reaches the disk later; fsync closes the gap. Everything about crash safety (the TiffinBox build's stage 8) follows from that one fact.

Explain it differently

1. System calls are a bank teller's window. You can't walk into the vault (kernel memory, the disk, the network card). You fill in a slip (put arguments in registers), push it through the window (a syscall instruction), and the teller checks your identity and the slip, does the work behind the glass, and pushes back a result or an error code. Each visit costs a queue and a check, which is why buffering (one slip for many lines, the chapter's lab) matters so much.

2. A mutex is the one bathroom key at a small restaurant. Whoever holds the key goes in; everyone else waits at the counter. Forgetting to return the key (an exception before unlock) locks everyone out forever, which is why Java has try/finally and synchronized blocks. A semaphore is a parking lot with 10 spots and a counter at the gate: up to 10 cars, then the gate waits for one to leave (Chapter Exercises P7 limits concurrency this way).

3. Deadlock is a gridlocked junction. Four cars at a four-way junction, each having entered a little and each waiting for the car on its right to move. Nobody's broken; everyone's waiting for someone who's waiting. The four conditions (exclusive use of road space, holding while waiting, no one can be forced to reverse, and a circle of waiting) are all present. Break any one and gridlock can't happen: a traffic light breaks "hold and wait", and a rule that cars always enter in one order breaks the circle (theoretical gap 2).

4. The page cache is an office outbox tray. You drop a letter in the outbox (write() returns) and go back to work. Hours later the post room collects it (the kernel writes dirty pages to disk). If the building burns down in between, the letter is gone, even though you "sent" it. fsync is walking the letter to the post office yourself and waiting for the receipt: slow, but certain. Group commit (stage 8) is collecting everyone's letters and walking them over together.

5. Virtual memory is every flat's door number starting at 1. In every building, flat numbering starts at 101, so flat 101 exists in thousands of buildings, each a different flat. A program's address 0x7ffd… is likewise private to that process; the MMU and the page table are the building's register, mapping "flat 101 in building 4,321" to a physical location. Two processes can't reach each other's memory because they can't even name it.

6. A context switch is putting a bookmark in one book to read another. The bookmark (saved registers) is cheap, but your head has to reload the other plot (caches and TLB entries for the other process go cold). Switching every few seconds is fine; switching every few sentences means you spend more time remembering than reading. That's why thousands of busy threads on a few cores is slow, and why the cost of a switch is mostly the cache misses afterwards.

7. epoll is a restaurant pager. In a blocking model, every customer stands at the counter waiting for their own order (one thread per connection, mostly idle). With a pager, customers sit down, and one person at the counter watches all the orders, buzzing whichever pager is ready. One thread can watch thousands of sockets and only act on the ready ones. Virtual threads give you blocking-style code with pager-style efficiency: the JVM does the watching for you (Gaps 1 shows where that breaks).

8. A file descriptor is a cloakroom token. open() gives you a small number (3, 4, 5…), and you hand that token back on every read and write. The token isn't the coat: two tokens can refer to the same coat (two open calls on one file), and one token can be shared by two people (a child process inheriting it). Lose tokens without returning them (forget close) and the cloakroom runs out (Chapter Exercises P10).

Gaps and misconceptions

What the chapter oversimplifies

1. "Virtual threads unmount when they block": not inside synchronized, in JDK 21. Chapter Exercises T5 explains pinning. Here it is measured: 100 virtual threads, each blocking for 50 ms while holding its own lock (no contention at all), on this 2-core machine:

Terminal
carrier parallelism: 2
100 virtual threads, each blocking 50 ms inside synchronized: 2519 ms
100 virtual threads, each blocking 50 ms inside ReentrantLock: 54 ms

With ReentrantLock, all 100 sleep at once and the batch takes about one sleep. With synchronized, a blocked virtual thread pins its carrier thread, so only 2 can sleep at a time: 100 × 50 ms ÷ 2 = 2.5 s, 47× slower. The JDK can tell you (-Djdk.tracePinnedThreads=short, real output):

Terminal
VirtualThread[#18]/runnable@ForkJoinPool-1-worker-1 reason:MONITOR
    Pin.lambda$main$0(Pin.java:14) <== monitors:1

JDK 24 (JEP 491) removed pinning for synchronized. On JDK 21, any library that does blocking I/O inside synchronized (older JDBC drivers, some HTTP clients, your own code) quietly turns virtual threads back into a tiny platform-thread pool (drill D1).

2. "Locks provide mutual exclusion": file locks only exclude those who ask. The chapter's mutexes are for threads. For files, Java's FileChannel.lock() is the tool, and on Linux it's an advisory POSIX lock: it only stops other processes that also ask for a lock. Real output (process A holds an exclusive lock for 3 seconds; B is a Python script that simply appends; C is another Java process that asks):

Terminal
A: holding an exclusive lock on orders.log
B (Python, plain append): write succeeded
C (Java, tryLock): lock not available
A: releasing
--- file:
written by a script that never asked for the lock

The lock stopped the polite process and did nothing about the one that didn't ask. (Linux once supported mandatory locks; they were unreliable and have been removed from recent kernels.) A file lock is a protocol between cooperating programs, so every writer must use it, including scripts and tools (drill D3). It's the right tool for "only one instance of this service may run on this data directory", which is how the TiffinBox build's stage 8 uses it.

3. "Shared file offsets after fork cause interleaving": separate opens lose data outright. The chapter notes interleaved writes when processes share a descriptor. When two processes open the same file separately and each "seeks to the end, then writes", they overwrite each other. Real output, two Python processes each writing 20,000 lines:

Terminal
seek  : 40,000 lines written by two processes, 24,229 lines in the file, 24,223 intact
append: 40,000 lines written by two processes, 40,000 lines in the file, 40,000 intact

"Seek to end, then write" is two system calls: between them, the other process can write at the same offset, and one line overwrites the other. 40% of the lines were lost, and six were corrupted. O_APPEND makes "move to the end and write" a single atomic step in the kernel, so nothing is lost (for local filesystems; NFS doesn't guarantee it). Java's FileOutputStream(file, true) and StandardOpenOption.APPEND use O_APPEND; RandomAccessFile with seek(length()) doesn't (drill D2).

4. "mmap errors arrive as SIGBUS": in Java, as an Error you probably don't catch. The chapter mentions SIGBUS when a mapped file is truncated. The JVM turns it into something else. Real output, a file mapped with FileChannel.map, then truncated by another process (as log rotation might):

Terminal
read 8 MB through the mapping, sum 0
another process truncated the file to 0 bytes; reading the mapping again...
caught: java.lang.InternalError: a fault occurred in an unsafe memory access operation

A plain get(i) on a MappedByteBuffer threw InternalError, a subclass of Error, not an IOException. Code that catches IOException around file access won't see it, and many frameworks treat Errors as fatal. Mapped files are fast because the OS handles I/O behind ordinary memory reads, and that's also why failures can't be reported as ordinary I/O errors (drill D4).

Common misconceptions

Misconception What's actually true Where it's shown
"Virtual threads make blocking free." Pinned in synchronized on JDK 21: back to a pool the size of the core count. Gaps 1; drill D1
"A file lock protects the file." It protects it from processes that also lock (advisory). Gaps 2; drill D3
"Two processes appending to a file is safe." Only with O_APPEND, on a local filesystem. Gaps 3; drill D2
"File errors are IOExceptions." Through mmap, they're InternalErrors (or crashes). Gaps 4; drill D4
"close() flushes to disk." It flushes Java's buffers to the kernel; the page cache still isn't on disk. Explain it differently 4
"A POSIX lock belongs to the file descriptor." It belongs to the process: closing any descriptor for the file releases them all. Code walkthrough

Theoretical gaps: the ideas behind the chapter

1. Atomicity has a precise definition: linearizability. The chapter says an operation is atomic if it can't be observed half-done. The formal version (Herlihy and Wing, 1990): every operation appears to take effect at a single instant between its start and its end, and the resulting order is consistent with real time. O_APPEND writes are linearizable on local files (Gaps 3); "seek then write" isn't, because its effect is spread over two instants. The same definition is used for AtomicLong, ConcurrentHashMap.compute, and distributed databases (Volume 5), so it's worth knowing by name.

2. The four deadlock conditions are a design checklist, not trivia. Coffman's conditions (mutual exclusion, hold and wait, no preemption, circular wait) all have to hold for deadlock. Design removes one: lock ordering (always acquire in a global order) removes circular wait; try-lock with timeout and back-off removes hold-and-wait; lock-free or single-writer designs remove mutual exclusion. Databases choose a different route: allow deadlocks, detect cycles in the wait-for graph (the Companion to chapter 04's DFS), and abort a victim. Choosing between prevention and detection is an architectural decision, and stage 8 avoids the question by having one writer thread.

3. The end-to-end argument: who is responsible for durability? Saltzer, Reed and Clark (1984) argued that some guarantees can only be provided completely at the endpoints of a system; lower layers can only help with performance. fsync returning success means the kernel and the disk claim the data is stored; it doesn't mean the client knows. If a server crashes after fsync but before replying, the client retries, so the request must be idempotent (the TiffinBox build's stage 5). Durability is end-to-end: the disk, the log, the reply and the client's retry policy together.

4. Every copy has a cost, so the OS offers ways to avoid them. A read() copies bytes from the page cache into your buffer; a write() to a socket copies them back into the kernel. For a file server, that's two copies and two system calls per chunk for bytes the program never looks at. mmap removes the first copy; sendfile (Java's FileChannel.transferTo) moves data from the page cache to a socket inside the kernel with no user-space copy at all, which is how Kafka and web servers serve files. The general lesson: when performance is dominated by moving bytes, count the copies.

5. Scheduling is a policy with trade-offs that can't all be won. The chapter describes time slices. Underneath, every scheduler balances throughput (do the most work), latency (respond fast), and fairness (everyone gets a share), and they conflict: longer slices raise throughput and hurt latency. Linux's Completely Fair Scheduler (and EEVDF since kernel 6.6) targets fairness weighted by priority; real-time schedulers target deadlines. Container CPU limits (cgroups quotas) add a fourth policy on top, which is why a containerised service can be throttled while the machine looks idle (Chapter Exercises S1).

6. Files are an abstraction over a log-structured, lying device. An SSD doesn't overwrite blocks in place: it writes new pages and remaps (a flash translation layer, effectively a log). It may also acknowledge writes from a volatile cache. Filesystems hide both behind "a file is an array of bytes", and fsync asks the whole stack, down to the device, to make data durable. Real durability requires every layer to honour it, which is why databases test with power-cut rigs, and why PostgreSQL changed its handling of fsync errors in 2018 after learning that Linux could drop failed dirty pages and report success on a later retry ("fsyncgate").

Applying it

Code walkthrough

Java's file APIs are thin layers over the system calls in this chapter. Two native functions from jdk-21-ga, in UnixFileDispatcherImpl.c, the code behind FileChannel on Linux and macOS.

force(): fsync or fdatasync

C
Java_sun_nio_ch_UnixFileDispatcherImpl_force0(JNIEnv *env, jobject this,
                                          jobject fdo, jboolean md)
{
    jint fd = fdval(env, fdo);
    int result = 0;

    if (md == JNI_FALSE) {
        result = fdatasync(fd);
    } else {
        result = fsync(fd);
    }

    return handle(env, result, "Force failed");
}

FileChannel.force(boolean metaData) is one line of C:

  • force(true) calls fsync: flush the file's data and its metadata (size, modification time) to the device.
  • force(false) calls fdatasync: flush the data, and only the metadata needed to read it back (such as a changed file size), skipping things like timestamps. It can save a disk write per call.

For an append-only log, the file size changes on every append, so fdatasync still has to write the size, and the saving is small; for a file overwritten in place (a database page), fdatasync avoids a metadata write every time. Neither makes a newly created file's directory entry durable: that needs an fsync of the directory, which Java can do by opening the directory with FileChannel.open(dir, READ) and calling force(true) (on Linux; it isn't portable to Windows). The TiffinBox build's stage 8 does this when it creates the log.

lock(): a POSIX record lock

C
Java_sun_nio_ch_UnixFileDispatcherImpl_lock0(JNIEnv *env, jobject this, jobject fdo,
                                      jboolean block, jlong pos, jlong size,
                                      jboolean shared)
{
    jint fd = fdval(env, fdo);
    jint lockResult = 0;
    int cmd = 0;
    struct flock64 fl;

    fl.l_whence = SEEK_SET;
    if (size == (jlong)java_lang_Long_MAX_VALUE) {
        fl.l_len = (off64_t)0;
    } else {
        fl.l_len = (off64_t)size;
    }
    fl.l_start = (off64_t)pos;
    if (shared == JNI_TRUE) {
        fl.l_type = F_RDLCK;
    } else {
        fl.l_type = F_WRLCK;
    }
    if (block == JNI_TRUE) {
        cmd = F_SETLKW64;
    } else {
        cmd = F_SETLK64;
    }
    lockResult = fcntl(fd, cmd, &fl);
    if (lockResult < 0) {
        if ((cmd == F_SETLK64) && (errno == EAGAIN || errno == EACCES))
            return sun_nio_ch_UnixFileDispatcherImpl_NO_LOCK;

Read it against Gaps 2:

  • fcntl with F_SETLK/F_SETLKW is the POSIX record lock: a lock on a byte range (l_start, l_len), shared (F_RDLCK) or exclusive (F_WRLCK). lock() blocks (F_SETLKW, "W" for wait); tryLock() doesn't, returning NO_LOCK when another process holds it. A length of Long.MAX_VALUE becomes 0, which POSIX defines as "to the end of the file, however large it grows".
  • These locks are advisory (nothing in write() checks them) and per process, not per descriptor. Closing any descriptor for the file releases all the process's locks on it, a notorious POSIX trap. That's why the JDK keeps its own table of locks per file inside the JVM and throws OverlappingFileLockException when the same JVM asks twice: the kernel can't distinguish two threads, or two channels, of one process.
  • Linux also has flock() (whole-file, per open file description) and, since 3.15, "open file description locks" (F_OFD_SETLK) that fix the close-releases-everything problem. The JDK uses the classic POSIX variant for portability.

Read it yourself

  1. Why does the C code treat size == Long.MAX_VALUE specially instead of passing it straight to l_len?
  2. A service opens its data file twice: once to lock it at startup, and once (in another component) to read it. The second component closes its channel after reading. What happens to the lock?

Debugging drills

D1. Virtual threads made the service slower

A team moved their order service to JDK 21 virtual threads (Executors.newVirtualThreadPerTaskExecutor()). Throughput under load dropped, and thread dumps show only a couple of carrier threads, both inside a synchronized method of an in-house HTTP client wrapper that calls a slow partner API. A reproduction:

Terminal
100 virtual threads, each blocking 50 ms inside synchronized: 2519 ms
100 virtual threads, each blocking 50 ms inside ReentrantLock: 54 ms

Explain, show how to confirm it in the real service, and fix it.

D2. The audit log loses lines when two services run

Two services on one host append audit lines to the same file, each with:

Java
RandomAccessFile f = new RandomAccessFile(path, "rw");
f.seek(f.length());
f.write(line);

Auditors notice gaps. A reproduction with two processes:

Terminal
seek  : 40,000 lines written by two processes, 24,229 lines in the file, 24,223 intact
append: 40,000 lines written by two processes, 40,000 lines in the file, 40,000 intact

Explain, and fix it.

D3. "We lock the file, so how did it get corrupted?"

The nightly price import locks prices.csv with FileChannel.lock() while rewriting it. A support engineer's shell script (sed -i … prices.csv) occasionally runs at the same time, and the import then reads a half-old, half-new file. The team's position is "it can't happen, we lock it". A reproduction:

Terminal
A: holding an exclusive lock on orders.log
B (Python, plain append): write succeeded
C (Java, tryLock): lock not available

Who's right?

D4. The analytics job dies during log rotation

A job memory-maps yesterday's order file to compute reports quickly. Occasionally it dies with an InternalError, at the same time each night. Operations' log rotation truncates files in place. A reproduction:

Terminal
read 8 MB through the mapping, sum 0
another process truncated the file to 0 bytes; reading the mapping again...
caught: java.lang.InternalError: a fault occurred in an unsafe memory access operation

Explain, and fix both the job and the rotation.

Career-oriented

Interview prep

Mid level

Q1. What's the difference between a process and a thread, and when would you choose several processes over several threads?

How to get there. Name what's shared and what isn't (address space, file descriptors, credentials), the costs (creation, switching, communication), and the failure model (a crash takes down one process or all threads). Then give concrete situations for each.

Q2. Your Java service writes a record, and the client gets "201 Created". The server loses power one second later. Is the record there after restart? What would you need to guarantee it?

How to get there. Trace the write through every layer (Java buffers, the kernel page cache, the device cache, the disk), say which survive a power cut, then state the guarantee you need and its cost.

Senior level

Q3. Should the new order service use virtual threads, a platform thread pool, or a reactive framework? Justify the choice for a team of eight.

How to get there. Chapter Exercises S4 compares the models; here, the decision includes your team and dependencies. Check the JDK version, blocking libraries and pinning, observability, the team's familiarity, and how you'll limit concurrency to downstream systems.

Q4. Two instances of a service must never process the same data directory at the same time. How do you enforce it, on one host and across hosts?

How to get there. On one host, the OS gives you a tool (a file lock) with specific semantics you must respect. Across hosts, the OS can't help: you need a lease from a shared system. Name the failure modes of each, especially "the holder is alive but paused".

Staff level

Q5. Your platform runs 300 JVM services in containers. Incidents keep tracing back to OS-level misconfiguration: descriptor limits, CPU throttling, memory limits, missing fsyncs. How do you make the platform safe by default?

How to get there. Treat it as defaults plus guardrails plus visibility: a base image and runtime configuration that are right for most services, checks that catch the dangerous deviations, and dashboards that show OS-level signals per service.

Q6. A product wants every order event durable before acknowledging, at 20,000 events per second on one node. The storage team says an fsync takes 2 ms on your disks. Is it feasible, and how would you design it?

How to get there. Do the arithmetic first (fsyncs per second needed against available), then the design that changes the arithmetic (group commit), then the trade-offs (latency, failure handling), then how to verify.