Workbench / Volume 1 Exercises: Foundations of Computing
V1·08
Operating Systems
Exercises for Volume 1, chapter 08: kernel and user space, system calls, kernel designs, processes (PIDs, fork/exec/wait, states, scheduling, context switches, signals), threads (kernel, user and virtual threads), concurrency (races, critical sections, mutexes, semaphores, monitors and condition variables, deadlock, livelock, starvation), memory management (virtual memory, pages, TLB, page faults, heap and stack, mmap), filesystems (descriptors, VFS, inodes, paths, permissions, links, page cache, fsync, journaling, block storage) and I/O models (blocking, non-blocking, epoll, io_uring). 13 theory questions, 12 programming exercises, 3 cumulative projects with chapters 01–07, the concepts the chapter leaves out, and 6 senior-level exercises.
Start here: how this chapter's exercises work
Same four sets and the same locking. Most programming exercises make the kernel visible from Java with strace, /proc, signals and timers. Measurements come from this book's sandbox: a Linux 6.18 virtual machine with 2 vCPUs, Java 21, running as root (which matters in P9). VMs make some operations slower than bare metal, so compare ratios, not absolute numbers.
You'll need a Linux shell (WSL on Windows works) for strace, /proc and signals. On macOS, use dtruss or a Linux container.
Coverage map.
| Chapter component | Exercises |
|---|---|
| kernel and user space; system calls; kernel designs | T1, P1 |
| processes, PIDs, process tree; fork, exec, wait | T2, P3 |
| process states; scheduling; context switches | T3, P6 |
| signals | T4, P2 |
| threads vs processes; kernel, user, M:N and virtual threads; thread lifecycle | T5, P4, P5 |
| race conditions, critical sections, atomicity | T6, P6 |
| mutex, semaphore, monitors and condition variables | T7, P6, P7 |
| deadlock, livelock, starvation | T8, P8 |
| virtual memory, pages, page tables, TLB, page faults | T9 |
| heap and stack; mmap and memory-mapped files | T9, T10 |
| file descriptors, VFS, inodes, directories and paths, links | T11, P9, P10 |
| permissions | T11, P9 |
| buffering, page cache, fsync; journaling and crash consistency; block storage | T12, P1, P11 |
| blocking, non-blocking, epoll, io_uring; I/O models per language | T13, P5, P12 |
Theory
T1. Kernel, user space and the cost of asking
- What can kernel-mode code do that user-mode code can't, and how does the CPU enforce it (chapter 07)?
- Walk through what happens when Java's
FileOutputStream.write(int b)writes one byte: from the Java method to thewritesystem call and back. - P1 measured 100,000 one-byte writes: unbuffered 33.5 ms and 100,010
writecalls; buffered 2.6 ms and 23 calls. Explain both numbers, and whyclock_gettimecosts ~20 ns while a real syscall costs ~100 ns or more. - Compare monolithic kernels (Linux), microkernels (seL4, QNX) and hybrids (Windows NT, macOS XNU) on performance and fault isolation.
T2. Processes: fork, exec and wait
- What does a process consist of (at least six things the kernel tracks)?
- Explain fork, exec and wait, and how a shell runs
ls -l | wc -l. - What is a zombie process and an orphan? What happens to orphans, and why does this matter inside a Docker container?
- Why did spawning
truefrom Java take 2.19 ms per process (P3), while creating a thread took about 186 µs and a virtual thread 33 µs (P4)?
T3. Scheduling and context switches
- Name the main process states and the events that move a process between them.
- What does a scheduler optimise, and what are the trade-offs between throughput, latency and fairness? How does Linux's scheduler (CFS, and EEVDF since kernel 6.6) decide what runs next?
- What does a context switch cost, directly and indirectly (chapter 07)? Why does a 2-vCPU container running 200 busy threads perform badly?
- A Java service in a container with a CPU limit of 2 shows p99 latency spikes of exactly ~100 ms. What OS mechanism is the likely cause?
T4. Signals
- What is a signal, and how does it differ from a normal function call? List SIGINT, SIGTERM, SIGKILL, SIGSEGV, SIGCHLD, SIGHUP, SIGPIPE and SIGQUIT with what each usually means.
- P2 ran a Java program with a shutdown hook and sent it SIGTERM, SIGINT and SIGKILL. The exit codes were 143, 130 and 137, and the hook ran for the first two only. Explain every part.
- What does
kill -3(SIGQUIT) do to a JVM, and when is it useful in production? - Why are signal handlers in C so restricted (only async-signal-safe functions)?
T5. Threads: kernel, user and virtual
- What do threads in one process share, and what does each have of its own?
- Compare 1:1 (kernel threads: Java platform threads, C pthreads), N:1 (green threads) and M:N (Go goroutines, Java virtual threads, Erlang processes) threading, including what happens when a thread blocks in a system call.
- P5 ran 10,000 tasks that each block for 50 ms: a fixed pool of 100 platform threads took 5,084 ms; a virtual thread per task took 152 ms. Explain both numbers. What wouldn't virtual threads speed up?
- What is "pinning" of a virtual thread, and when did it happen in JDK 21?
T6. Races, critical sections and atomicity
- Define a race condition and a data race, and show why
count++is three operations. - Give three races from everyday code that aren't about counters (check-then-act on a file, a lazy cache, a bank balance check).
- What makes an operation atomic at the hardware level (chapter 07), and why isn't
volatileenough to makecount++safe in Java?
T7. Mutexes, semaphores and condition variables
- Compare a mutex, a counting semaphore and a monitor (a lock plus condition variables). Give one everyday use of each.
- In a bounded buffer (producers and consumers), why must a consumer wait in a
while (count == 0)loop rather thanif? What are spurious wakeups, and what is a lost wakeup? - Java has
synchronized/wait/notifyAll,ReentrantLock/Condition,SemaphoreandBlockingQueue. When would you use each?
T8. Deadlock, livelock and starvation
- State the four Coffman conditions and show how a money transfer between two accounts (locking
fromthento) can deadlock. - Give three ways to prevent deadlock, saying which condition each breaks.
- Explain livelock and starvation with everyday examples, and how they differ from deadlock.
- Deadlocks also happen without locks in your code. Give an example with a thread pool, and one with database transactions.
T9. Virtual memory in practice
- Explain how virtual memory gives each process its own address space, and how the kernel uses pages, page tables and page faults to implement lazy allocation, copy-on-write fork, swapping and memory-mapped files.
- The chapter's lab touched 512 MB of fresh memory: 131,086 minor page faults at about 2 µs each, then 16 ns per page on the second pass. A forked child writing 256 MB caused 65,538 copy-on-write faults. Explain the numbers.
- A
pslisting shows a JVM with VSZ 4.2 GB and RSS 82 MB (P3's/proc/self/status). Which number matters for memory limits, and why are they so different? - What is a major page fault, and why does a server that starts swapping become unusable?
T10. Heap, stack and mmap
- Draw a typical Linux process address space (text, data, heap, mmap region, stacks, kernel) and say where a Java object, a Java local
int, a JIT-compiled method and a thread's stack live. - When would you use
mmap(Java'sFileChannel.map/MemorySegment) instead ofread? What are the risks? - How do
malloc, the JVM's heap and the kernel's page allocation relate?
T11. Files, inodes, links and permissions
- What is a file descriptor, and what does the VFS do? Why did P10 fail after opening 19,994 files?
- What's stored in an inode, and what's stored in a directory? Using P9, explain why
hard.txtstill read "hello" afterorig.txtwas deleted, butsoft.txtfailed. - Explain
rw-r--r--, the execute bit on directories, the setuid bit, and umask. Why could P9'scatread a file with mode000?
T12. Durability: page cache, fsync and journaling
- After
write()returns, where is the data, and what happens if the machine loses power then? What about if only the process crashes? - P11 measured 200 small writes: 1.7 ms without fsync and 40.4 ms with
force()after each (about 200 µs per fsync). Explain, and say how databases make many small commits durable without paying this per commit. - Write the correct sequence for atomically replacing a config file so a crash leaves either the old or the new version, never a mix.
- What does a journaling filesystem protect, and what doesn't it protect?
T13. I/O models
- Compare blocking I/O with a thread per connection, non-blocking I/O, I/O multiplexing (select, poll, epoll, kqueue), and completion-based asynchronous I/O (io_uring, Windows IOCP).
- Why does
selectscale badly to 10,000 connections whileepolldoesn't? - For each, name what uses it: Java's classic
SocketAPI, Java NIOSelector, Netty, Node.js, Go's net package, Java virtual threads, nginx. - P12 compares a thread-per-connection echo server with platform threads, with virtual threads, and with NIO. Which would you choose for a new Java service in 2026, and why?
Programming exercises
P1. Count the system calls
Write a Java program that writes 100,000 single bytes to a file, once through FileOutputStream and once through BufferedOutputStream. Time both, then run each under strace -f -e trace=write -o trace.txt java W raw and count the write calls. Look at the size of the buffered writes. Finally, run strace -c -f java -version and find the total number of syscalls the JVM makes just to start.
P2. Signals, exit codes and graceful shutdown
Write a Java program that registers a shutdown hook (printing a message), prints its PID and sleeps for a minute. From a shell, run it in the background and send SIGTERM, SIGINT and SIGKILL in turn, printing the exit status (wait $pid; echo $?) and the output each time. Then make the hook simulate finishing in-flight work (sleep 5 s) and see what happens when you send SIGTERM followed by SIGKILL after 2 s, as an orchestrator with a short grace period would.
P3. Processes from Java
Using ProcessBuilder, run ls -l / and capture its output and exit code; run a command that fails (ls /nope) and capture stderr separately; time spawning true 50 times. Print your own PID, parent PID and the relevant lines of /proc/self/status (Pid, PPid, Threads, VmSize, VmRSS). Then build the pipeline ls -l / | wc -l with ProcessBuilder.startPipeline.
P4. The cost of a thread
Time creating, starting and joining 2,000 platform threads and 2,000 virtual threads (repeat twice, report the second run). Then start 10,000 platform threads that each sleep 10 seconds and watch Threads in /proc/<pid>/status and the RSS in another terminal; repeat with virtual threads. What limit do you hit first with platform threads, and why?
P5. Thread pool versus virtual threads for blocking work
Submit 10,000 tasks that each Thread.sleep(50) to (a) Executors.newFixedThreadPool(100) and (b) Executors.newVirtualThreadPerTaskExecutor(). Time both. Then replace the sleep with a CPU-bound loop of about 5 ms per task and compare again. Explain both results.
P6. Build a bounded buffer with a monitor
Implement BoundedBuffer<T> with put and take using a ReentrantLock and two Conditions (notFull, notEmpty), backed by a circular array. Test it with 4 producers each putting 250,000 distinct integers and 4 consumers each taking 250,000; check the sum. Then compare its throughput with ArrayBlockingQueue of capacity 16 and 1,024, using one producer and one consumer that takes in batches with drainTo.
P7. Limit concurrency with a semaphore
A payment provider allows at most 3 concurrent calls per API key. Write a client wrapper that uses a Semaphore(3) so that 100 virtual threads calling it never exceed 3 in flight. Verify by tracking the maximum number inside the critical section. Then add tryAcquire(200, MILLISECONDS) so callers fail fast with a clear error instead of queueing forever.
P8. Create, detect and fix a deadlock
Write two threads that transfer between two accounts in opposite orders, using a CountDownLatch so each holds its first lock before trying the second. Detect the deadlock from inside the program with ThreadMXBean.findDeadlockedThreads() and print who waits for whom. Then take a thread dump with jcmd <pid> Thread.print or kill -3. Finally, fix it with lock ordering by account ID and show the transfer completes.
P9. Inodes, links and permissions
In a shell: create orig.txt, a hard link hard.txt and a symlink soft.txt; print each one's inode number and link count with stat -c '%n inode=%i links=%h'; delete orig.txt and cat both links. Then create a file, chmod 000 it and try to read it, first as your normal user and then with sudo (or as root). Finally, from Java, read the POSIX permissions and owner with Files.getPosixFilePermissions and Files.getOwner.
P10. Descriptor limits and leaks
From Java, open FileInputStreams on one file in a loop without closing them until an exception occurs; print how many you opened and the message. Check ulimit -n and ls /proc/<pid>/fd | wc -l while it runs. Then fix the loop with try-with-resources and confirm the count stays flat. Explain what happens to a server that leaks one socket per failed request.
P11. Page cache, fsync and deleted-but-open files
- Write a 200 MB file, drop the page cache (
echo 3 > /proc/sys/vm/drop_cachesas root, or reboot/use a fresh file), and time reading it twice withcat file > /dev/null. - From Java, time 200 small (100-byte) writes with and without
FileChannel.force(false)after each. - Start a process that keeps a file open, delete the file, and use
lsof +L1(orls -l /proc/<pid>/fd) to find it. Check thatdfdoesn't show the space freed until the process exits. - Implement the atomic config replacement from T12 in Java.
P12. Three echo servers
Write an echo server on port 9000 three ways: (a) ServerSocket with a platform thread per connection, (b) the same code with a virtual thread per connection, and (c) a single-threaded NIO Selector loop. Write a load generator that opens 5,000 concurrent connections, each sending 10 messages with 100 ms pauses. Measure: does each server cope, how many threads does the JVM have (/proc/<pid>/status), and the p99 round-trip time. Confirm with strace -f -e trace=epoll_wait,epoll_ctl that (b) and (c) use epoll.
Cumulative projects (chapters so far: 01–07)
C1. A crash-safe append-only log for orders
Write a Java OrderLog that appends order events (chapter 06's C1 binary format, or JSON lines) to a file with group commit: callers from many threads call append(event) and get a CompletableFuture that completes only once the event is durable; a single writer thread batches all pending events, writes them with one write, calls force() once, then completes all their futures. On start-up, recover by reading the log and stopping cleanly at the first truncated or corrupt record (CRC). Measure appends per second with fsync per event versus group commit, from 1, 16 and 256 concurrent virtual-thread clients. Test crash safety by kill -9 during heavy writing and verifying recovery.
Combines: files, exit codes and signals (ch 01, 08); concurrency and error handling (ch 02); queues and buffers (ch 03); batching and complexity (ch 04); probability of undetected corruption (ch 05); binary formats, varints and CRCs (ch 06); the cost of syscalls and storage latency (ch 07, 08).
C2. A process supervisor in Java
Write a small supervisor (like a mini systemd or tini) in Java: it reads a config listing commands to run, starts each with ProcessBuilder, captures stdout/stderr to per-process log files with timestamps, restarts crashed processes with exponential back-off (1 s, 2 s, 4 s… max 60 s, reset after 5 minutes of uptime), and on SIGTERM sends SIGTERM to all children, waits up to 10 seconds, then SIGKILLs the stragglers and exits 0. Expose status (PID, uptime, restart count, last exit code) on stdout every 10 seconds.
Combines: CLI, stdout/stderr, exit codes (ch 01); error handling and clean design (ch 02); maps and queues (ch 03); back-off arithmetic (ch 04, 05); exit status encoding (ch 06); processes, signals and pipes (ch 08).
C3. Find the bottleneck: an OS-level investigation script
Write a shell script diag.sh <pid> that collects, for a running Java process: thread count and states (from /proc/<pid>/task/*/stat), open descriptor count and types, RSS and VSZ, voluntary and involuntary context switches, minor and major page faults, cgroup CPU throttling (cpu.stat) and memory limit/usage if in a container, three thread dumps 5 seconds apart (jcmd), and a 10-second strace -c -f summary. Output a short report highlighting anything unusual (descriptor count near the limit, involuntary switches rising fast, throttling, major faults). Test it against P5's and P12's programs and against a deliberately leaky program.
Combines: shell scripting, pipes and text processing (ch 01); reading program behaviour (ch 02); counting and thresholds (ch 04, 05); number formats from /proc (ch 06); context switches and caches (ch 07); everything in ch 08.
What the chapter leaves out
Containers are processes with namespaces and cgroups
A container isn't a VM: it's ordinary processes with namespaces (their own view of PIDs, mount points, network interfaces, hostnames, users, IPC) and cgroups (limits and accounting for CPU, memory, I/O, PIDs). Consequences you'll meet: your app is PID 1 (T2: no default signal handling, must reap zombies; use tini or --init, and use the exec form of CMD so the JVM, not a shell, receives SIGTERM); CPU limits throttle per period (T3); memory limits count RSS and page cache, and exceeding them triggers the OOM killer (next section); modern JVMs read cgroup limits to size the heap (-XX:MaxRAMPercentage) and thread pools (availableProcessors() reflects the CPU limit), but older ones (before 8u191/10) didn't; /proc/meminfo inside a container still shows the host's memory, so tools that read it are wrong. Volume 9 covers containers in depth; the mechanisms are this chapter's.
The OOM killer and memory accounting
When Linux (or a cgroup) runs out of memory and can't reclaim enough page cache, the OOM killer chooses a process (by oom_score, mostly size) and sends SIGKILL: exit code 137, no shutdown hooks, nothing in your application logs; the evidence is in dmesg/kernel logs and memory.events. For JVMs, the classic surprise is that RSS is much more than -Xmx: metaspace, code cache, thread stacks, GC data structures, direct ByteBuffers, and native libraries (Netty, compression) all live outside the heap. Budget heap at about 50–75% of the container limit, use Native Memory Tracking (-XX:NativeMemoryTracking=summary, jcmd VM.native_memory) to see the rest, and alert on restarts with exit code 137.
Observability tools for the OS
Beyond strace (slow: it stops the process on every syscall, so use it briefly) and /proc: perf samples CPU stacks and hardware counters system-wide (chapter 07's gaps); eBPF tools (bcc's execsnoop, opensnoop, biolatency, tcpconnect, offcputime, and bpftrace one-liners) attach safe, verified programs to kernel events with low overhead, answering questions like "which process opens which files?", "what's the disk latency distribution?", "why are threads off-CPU?". vmstat, iostat, pidstat, ss, sar cover the basics. Brendan Gregg's USE method (utilisation, saturation, errors for every resource) gives a checklist. Production platforms increasingly ship eBPF-based agents (Cilium, Pixie, Parca).
Time and clocks
The OS offers several clocks: wall-clock time (CLOCK_REALTIME, Java's System.currentTimeMillis, Instant.now), which can jump backwards or forwards when NTP corrects it or an admin changes it, and monotonic time (CLOCK_MONOTONIC, System.nanoTime), which only moves forward but has no meaning across machines or reboots. Use monotonic time for measuring durations and timeouts (a wall-clock timeout can fire early or never after a clock step), wall-clock time for timestamps people read, and never compare raw timestamps across machines to order events: clock skew between servers is milliseconds or worse (distributed systems use logical clocks, Volume 5). Leap seconds and time-zone rules add further traps (Volume 23's chapter 03).
Security boundaries the OS provides
Processes, users and permissions are security boundaries; containers add namespaces, capabilities (root's powers split into pieces: drop all you don't need), seccomp filters (restrict which syscalls a process may make; Docker's default profile blocks dozens), and mandatory access control (SELinux, AppArmor). ASLR, non-executable stacks and stack canaries make memory-corruption exploits harder. Practical defaults: run as non-root, read-only root filesystem, drop capabilities, keep the default seccomp profile, and treat a shared kernel as a weaker boundary than a VM (sandboxes like gVisor and Firecracker microVMs exist for running untrusted code, as this book's sandbox does).
io_uring and the future of I/O
The chapter introduces io_uring briefly. It's worth knowing why it matters: syscall costs rose after Spectre mitigations (T1), and NVMe drives can do millions of operations per second, so one syscall per operation became the bottleneck. io_uring's shared submission and completion rings let a program queue many reads, writes, accepts and even fsyncs with one syscall (or none, with kernel-side polling), and it does truly asynchronous file I/O. Databases (TigerBeetle, ScyllaDB, newer PostgreSQL work) and runtimes (Netty's io_uring transport, Tokio's) adopt it. It has also had a run of security bugs, so some environments (Google's production, some container platforms) disable it: check before depending on it.
Senior exercises
S1. Intermittent latency spikes in a containerised Java service
A Spring Boot service in Kubernetes (CPU limit 2, memory limit 2 GiB, -Xmx1536m) shows p99 latency spikes to 100–300 ms every few minutes and occasional restarts with exit code 137 and no error in the application log. Lay out your investigation: hypotheses, evidence to collect (with commands), and fixes, ordered by likelihood.
S2. Design graceful shutdown for a fleet
Your company's services lose in-flight requests and occasionally corrupt background jobs during deploys. Write a graceful-shutdown standard for Java services on Kubernetes covering: signal handling, readiness, load balancer draining, in-flight HTTP requests, message consumers, scheduled jobs, connection pools, and timeouts, with the sequence and numbers.
S3. Review a file-handling change
A colleague's PR adds a feature that writes a user's export to exports/<userId>.csv by new FileWriter(path), writing rows as they're generated, then a background thread uploads finished files and deletes them. Another process sometimes reads the directory to show "your export is ready". Find the OS-level problems and write the review.
S4. Choose a concurrency model for a new service
A new "order notification" service must hold 50,000 concurrent long-poll/SSE connections from apps, consume events from Kafka, and call a push-notification provider limited to 100 concurrent requests. Compare implementing it with (a) a classic thread-per-request Spring MVC on platform threads, (b) Spring WebFlux/Netty (reactive event loops), and (c) Spring MVC on virtual threads. Recommend one and list the risks you'd address.
S5. A post-incident review: the disk that filled up
A production incident: a payments API returned 500s for 40 minutes. The root cause was a full disk on its hosts: an application debug log level was left on after an investigation, logs grew 40 GB in a day, logrotate rotated and deleted the files, but disk space wasn't freed, and then the database client's temp files failed to write. Write the "what happened and why" (technical, with this chapter's concepts) and five action items.
S6. Teach the "everything is a file descriptor" model
Prepare a 20-minute session for your team that explains file descriptors as the unifying idea behind files, pipes, sockets and epoll, with three live demos from this chapter, and connects it to three production problems they've seen. Write the outline, the demos and the takeaways.