Workbench / Volume 1 Companion: Foundations of Computing
V1·07
Computer Architecture
Companion to Volume 1, chapter 07: how the machine, the tricks for doing more per cycle, and the memory hierarchy connect; new angles (a kitchen brigade as a pipeline, a waiter who guesses your order, a library's reading room as the cache hierarchy, two cooks sharing one chopping board); what the chapter simplifies, from tiny numbers that make the same loop 37× slower to a division the compiler replaces with a multiplication and three shifts; the theory behind it (Amdahl's law, the roofline model, Little's law, why the clock stopped getting faster); the JDK's LongAdder cells and vectorised array comparison; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 07 has three strands. The machine is the basic model: gates build an ALU, a control unit runs the fetch–decode–execute cycle, and buses connect it to memory and devices. More per cycle is everything a modern core does to run faster than that model suggests. The memory hierarchy is how it hides the fact that main memory is about a hundred times slower than the core.
The links worth remembering:
- The simple model is still the contract. Pipelining, out-of-order execution and speculation all preserve the illusion that instructions run one at a time, in order. Your program can't tell, except through timing, which is how both performance work and Spectre-class attacks see through the illusion.
- Most performance is memory performance. The core can do several operations per nanosecond; one trip to DRAM costs around a hundred. Cache lines, locality and prefetching decide whether the core is working or waiting.
- Multicore turns the hierarchy into a conversation. Each core has private caches, so cores must agree on the contents of shared lines (coherence). Writing to a shared line is a message to other cores, which is why contended counters and false sharing are slow.
Explain it differently
1. A pipeline is a restaurant kitchen brigade. One cook taking an order from start to finish (chop, cook, plate, garnish) finishes a dish every 20 minutes. Four cooks, each doing one stage and passing it on, finish a dish every 5 minutes once the line is full, though each dish still takes 20 minutes end to end. That's pipelining: throughput improves, latency doesn't. A dish that needs the sauce from the previous dish before it can start (a data hazard) makes the line wait; a mistake that means throwing away the dishes in progress (a mispredicted branch) wastes every stage's work.
2. Branch prediction is a waiter who guesses your order. A regular walks in, and the waiter tells the kitchen "the usual" before you've sat down. Usually right, and your food arrives early. When you order something else, the started dish is thrown away and the kitchen starts again: a misprediction costs about 15–20 cycles on modern cores. Predictable code (sorted data, loops that run the same way) keeps the waiter right; random branches make every guess a coin flip (the chapter's lab sorts data to prove it).
3. The memory hierarchy is a library. The book in your hands is a register. The few books on your desk are L1 cache. The shelf beside your desk is L2, the reading-room shelves are L3, and the closed stacks, where a librarian fetches a book in ten minutes, are DRAM. Librarians don't fetch one page: they bring the whole book (a cache line, 64 bytes), betting you'll read the next page too (spatial locality), and they keep recently used books nearby (temporal locality). Code that reads memory in order is a reader going page by page; code that chases pointers is a reader who needs a different book for every sentence.
4. Coherence is two cooks sharing one chopping board. Each cook has their own counter space (a private cache), but some ingredients sit on a shared board (a cache line). When one cook changes what's on the board, the other must be told before using it. If both cooks keep working on different vegetables that happen to sit on the same board, they still keep interrupting each other: that's false sharing. Giving each cook their own board is padding, and it's what @Contended does in the JDK (Code walkthrough).
5. SIMD is a rubber stamp. Writing "PAID" on 8 invoices one at a time takes 8 strokes; a stamp that covers 8 invoices laid side by side takes one. A SIMD instruction applies one operation to 4, 8 or 16 values packed in a wide register. The catch is that the invoices must be laid out side by side: data in a contiguous primitive array can be stamped; data scattered in objects can't.
6. Out-of-order execution is a cook who reads the whole recipe first. "Boil water (10 min), chop onions (3 min), fry onions, add rice to the water." A literal cook waits at the stove for 10 minutes; a sensible one starts the water and chops onions meanwhile. The core does the same, using a window of a few hundred upcoming instructions, and runs whatever has its inputs ready. It still serves dishes in recipe order (instructions retire in order), so from outside nothing looks reordered.
7. A compiler knows tricks the CPU is slow at. Integer division is one of the slowest basic operations (tens of cycles); multiplication and shifts are a few. So when the divisor is a constant, compilers replace the division with a multiplication by a "magic" reciprocal and some shifts (Gaps 2). The cook asked to "divide this into sevenths" every time doesn't measure: they use a pre-marked template.
8. Speed is limited by the narrowest pipe. A tap feeding a bucket through a hose: a wider tap doesn't help if the hose is thin. A computation is limited either by how fast the core computes or by how fast memory delivers data, whichever is lower. Summing an array does one addition per 8 bytes loaded, so it's limited by memory bandwidth, not arithmetic (theoretical gap 2, the roofline model).
Gaps and misconceptions
What the chapter oversimplifies
1. "Each operation takes a few cycles": unless the numbers are very small. The chapter gives operations fixed costs. On x86 cores, floating-point arithmetic on subnormal numbers (the tiny values below about 2.2 × 10⁻³⁰⁸, the Companion to chapter 06's "special values") can be handled by a slow microcode path. Real measurement, the same loop with different starting values (JDK 21, this machine's Xeon):
50M multiply-adds: normal numbers 54 ms, subnormal numbers 2002 ms (37.1x) [9.93262e+06 9.93262e-304]
Same instructions, same count, 37× slower, decided only by the values. This hits code where values decay towards zero: exponential smoothing, audio fades, physics damping, probability products. GPUs and many compiled programs enable "flush to zero" to avoid it; the JVM doesn't, by specification (Java requires IEEE 754 subnormals). The fix is in the algorithm: snap values below a threshold to zero, or work in logarithms (drill D1).
2. "The ALU divides": the compiler often doesn't let it. The chapter lists division among ALU operations. Integer division is so slow that compilers avoid it whenever the divisor is known. GCC 13 at -O2, real assembly:
div7:
mov eax, edi
imul rax, rax, 613566757
shr rax, 32
sub edi, eax
shr edi
add eax, edi
shr eax, 2
ret
divn:
mov eax, edi
xor edx, edx
div esi
ret
mod1024:
mov eax, edi
and eax, 1023
ret
x / 7 became a multiplication by 613,566,757 (about 2³²/7, with a correction), a subtraction and three shifts: no div at all. x / n with an unknown n must use the real div. x % 1024 is a single and. Java's JIT does the same. That's why hash tables use power-of-two sizes and hash & (n - 1) (the Companion to chapter 03's walkthrough): measured in Java, 10 million bucket indexes took 86.9 ms with k % n (n not a compile-time constant) and 47.2 ms with k & (n - 1), for the same results.
3. "Shared variables live in memory": a volatile one really does. The chapter describes registers and memory. A Java field that isn't volatile can live in a register for the whole loop, and the JIT can even fold the loop away. A volatile field must be read and written through the memory system on every access, with ordering guarantees:
100M increments: plain field 2.7 ms, volatile field 962.1 ms
2.7 ms for 100 million increments is 0.03 ns each, faster than one clock cycle at 2.1 GHz, so the JIT clearly replaced the plain loop with a single addition. The volatile loop had to do every increment, each a store with a barrier: about 10 ns per increment, 350× slower. volatile is a correctness tool for visibility between threads (Volume 3, chapter 35), not a free annotation, and it's never a way to make count++ thread-safe (it isn't atomic).
4. "Multiple cores run work in parallel": only if there's enough work to pay for the coordination. The chapter introduces cores. Parallel work has fixed costs (splitting, waking threads, combining results), and those costs are measured in microseconds:
cores: 2
sum of 1,000 longs: sequential 0.0004 ms, parallel 0.0058 ms
sum of 10,000,000 longs: sequential 6.0020 ms, parallel 2.7044 ms
On 1,000 elements the parallel stream was 15× slower; on 10 million it was 2.2× faster on this 2-core machine. The break-even point depends on the work per element, the core count and what else is running (a server under load has no idle cores to borrow). parallel() in a request handler on a busy server usually makes everything slower (drill D2).
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "An instruction has a fixed cost." | It depends on data: subnormals, cache misses and mispredictions change it by 10–100×. | Gaps 1 |
| "Division and modulo are cheap." | Tens of cycles for a variable divisor; constants and powers of two are rewritten by the compiler. | Gaps 2; drill D4 |
"volatile makes it thread-safe." |
It makes reads and writes visible and ordered; count++ is still three steps and still races. |
Gaps 3; drill D3 |
| "Parallel is faster." | Only with enough work per task and idle cores. | Gaps 4; drill D2 |
| "Faster clock, faster program." | Clocks stalled around 2005; performance now comes from width, caches and cores (theoretical gap 4). | theoretical gap 4 |
| "A microbenchmark result is the cost." | The JIT may have deleted or folded the code (Gaps 3's 0.03 ns). | Chapter Exercises leaves-out (benchmarking) |
Theoretical gaps: the ideas behind the chapter
1. Amdahl's law, and Gustafson's answer. If a fraction p of a program can run in parallel on n cores, the best speedup is 1 / ((1 − p) + p / n). With p = 0.9 and unlimited cores, the limit is 10×: the serial 10% dominates. That's why parallelising a request handler rarely helps: the serial parts (parsing, a database call, a lock) remain. Gustafson's observation is the optimistic version: with more cores, people solve bigger problems in the same time, and the parallel part grows with the problem. Both are true; which applies depends on whether your work is fixed-size (one request) or scalable (a nightly batch over more data).
2. The roofline model: compute-bound or memory-bound. Every computation has an arithmetic intensity: operations per byte moved from memory. A machine has a peak compute rate (operations per second) and a peak memory bandwidth (bytes per second). Performance is capped by the lower of compute rate and intensity × bandwidth. Summing longs does 1 addition per 8 bytes: intensity 1/8, so a core that could add billions of numbers per second is held to bandwidth ÷ 8. Matrix multiplication reuses each loaded value many times: high intensity, compute-bound. The model tells you which optimisation can help: for low intensity, reduce bytes (smaller types, better layout, compression); for high intensity, use SIMD and more cores. The TiffinBox build's stage 7 is a low-intensity problem.
3. Little's law for memory. In any steady system, items in flight = arrival rate × time in system. For memory: bytes in flight = bandwidth × latency. To use 20 GB/s of bandwidth with 100 ns latency, about 2,000 bytes (around 30 cache lines) must be in flight at once. A single chain of dependent loads (pointer chasing) has one in flight, so it gets a tiny fraction of the bandwidth however fast the memory is. That's the deep reason arrays beat linked lists: independent addresses let the core and the prefetcher keep many misses in flight. The same law governs thread pools and queues (Volume 5).
4. Why the clock stopped getting faster. Moore's law (transistor counts doubling about every two years) continued for decades; Dennard scaling (smaller transistors using proportionally less power, so clocks could rise at the same power density) ended around 2005, when leakage current made faster clocks too hot. Since then, extra transistors go into width (superscalar, SIMD), caches and more cores, rather than frequency. The practical consequence for software: single-threaded code stopped getting faster for free, and performance now depends on parallelism and memory behaviour, which is this chapter's content.
5. Von Neumann, Harvard, and what modern CPUs actually are. The von Neumann model stores code and data in one memory, which makes programs data (compilers, JITs, loaders) and also makes code injection possible. The Harvard architecture separates them. Modern CPUs are modified Harvard inside (separate L1 instruction and data caches, so fetching code and loading data don't compete) and von Neumann outside (one main memory). Security features re-impose separation in software: pages marked non-executable (the NX bit) so injected data can't run as code. A JIT has to work around exactly that, writing code and then flipping its pages to executable.
6. Timing is an observable. The architectural contract (the ISA) says what results instructions produce, not how long they take. But time is observable from software, so everything that changes timing leaks information: cache state, branch history, speculative execution (Spectre), even subnormal slowdowns. Constant-time cryptographic code is written so that its timing doesn't depend on secret data, avoiding secret-dependent branches, memory addresses and variable-time instructions like division. It's the most extreme form of "the hardware is part of the semantics".
Applying it
Code walkthrough
Two JDK classes are written around the hardware the chapter describes. Excerpts from jdk-21-ga.
LongAdder and Striped64: spreading a counter across cache lines
Chapter Exercises P8 measures LongAdder beating AtomicLong under contention. Here's why. java/util/concurrent/atomic/LongAdder.java:
public void add(long x) {
Cell[] cs; long b, v; int m; Cell c;
if ((cs = cells) != null || !casBase(b = base, b + x)) {
int index = getProbe();
boolean uncontended = true;
if (cs == null || (m = cs.length - 1) < 0 ||
(c = cs[index & m]) == null ||
!(uncontended = c.cas(v = c.value, v + x)))
longAccumulate(x, null, uncontended, index);
}
}
and the cell type in Striped64.java:
@jdk.internal.vm.annotation.Contended static final class Cell {
volatile long value;
Cell(long x) { value = x; }
final boolean cas(long cmp, long val) {
return VALUE.weakCompareAndSetRelease(this, cmp, val);
}
Read it against the chapter:
- Uncontended, it's one CAS on
base. With a single thread,cellsstaysnullandaddis a compare-and-swap on one field: as cheap asAtomicLong. - When a CAS fails (another core changed
basefirst), the class creates an array ofCells, and each thread adds to the cell chosen by its probe (index & m: a power-of-two mask, Gaps 2). Different threads now write to different cells, so they stop fighting over one cache line.sum()addsbaseand every cell. @Contendedpads eachCellso that two cells never share a cache line. Without it, cells allocated next to each other would sit in the same 64-byte line, and the threads would be back to fighting over it: false sharing, inside the very class meant to avoid contention.- The array grows only up to the number of CPUs (
else if (n >= NCPU || cells != cs)): more cells than cores can't reduce contention further. When two threads collide on a cell, one moves to another cell withadvanceProbe, a three-line xorshift random number generator:
static final int advanceProbe(int probe) {
probe ^= probe << 13; // xorshift
probe ^= probe >>> 17;
probe ^= probe << 5;
THREAD_PROBE.set(Thread.currentThread(), probe);
return probe;
}
The trade-off is in the API: sum() isn't an atomic snapshot (cells can change while it adds them up), and memory use grows with cores. Good for statistics counters, wrong for sequence numbers.
ArraysSupport.vectorizedMismatch: comparing eight bytes at a time
jdk/internal/util/ArraysSupport.java is behind Arrays.equals, Arrays.mismatch, and the Latin-1 string comparison in the Companion to chapter 04:
@IntrinsicCandidate
public static int vectorizedMismatch(Object a, long aOffset,
Object b, long bOffset,
int length,
int log2ArrayIndexScale) {
int log2ValuesPerWidth = LOG2_ARRAY_LONG_INDEX_SCALE - log2ArrayIndexScale;
int wi = 0;
for (; wi < length >> log2ValuesPerWidth; wi++) {
long bi = ((long) wi) << LOG2_ARRAY_LONG_INDEX_SCALE;
long av = U.getLongUnaligned(a, aOffset + bi);
long bv = U.getLongUnaligned(b, bOffset + bi);
if (av != bv) {
long x = av ^ bv;
int o = BIG_ENDIAN
? Long.numberOfLeadingZeros(x) >> (LOG2_BYTE_BIT_SIZE + log2ArrayIndexScale)
: Long.numberOfTrailingZeros(x) >> (LOG2_BYTE_BIT_SIZE + log2ArrayIndexScale);
return (wi << log2ValuesPerWidth) + o;
}
}
Three layers of the chapter at once:
- Word-at-a-time in plain Java. Instead of comparing byte by byte, it reads 8 bytes as one
longfrom each array and compares those: one comparison per 8 bytes.getLongUnalignedallows the read to start at any address. - Finding the first differing byte with bit tricks.
av ^ bvhas 1-bits exactly where the two words differ. On a little-endian machine (x86, ARM), the first array element is the lowest byte of thelong, sonumberOfTrailingZeros(x) >> 3gives the index of the first differing byte. On big-endian machines, leading zeros. Byte order (the Companion to chapter 06) decides which end of the word is "first". @IntrinsicCandidate: the JIT may replace the whole method. HotSpot has hand-written assembly for this method that uses SIMD registers (16, 32 or 64 bytes per comparison, depending on the CPU). The Java code is the portable fallback and the specification; the intrinsic is what usually runs.Long.numberOfTrailingZerosis itself intrinsified to one instruction (tzcnton x86).
Read it yourself
- Why does
LongAdder.addtrycasBasefirst instead of always using cells? - In
vectorizedMismatch, why XOR rather than comparing the bytes inside thelongone by one?
Debugging drills
D1. A smoothing job that slows down overnight
A service keeps an exponentially smoothed "recent demand" score per dish, updated each minute: score = score * 0.9999999 + newOrders. For dishes that stop selling, the score decays towards zero. The nightly job that updates all scores gets slower as the night goes on, though the number of dishes doesn't change. A reproduction:
50M multiply-adds: normal numbers 54 ms, subnormal numbers 2002 ms (37.1x) [9.93262e+06 9.93262e-304]
Explain, and fix it.
D2. parallel() made the API slower
A developer added .parallel() to a stream that totals an order's lines in the checkout endpoint, to "use all the cores". Under load testing, p99 latency got worse and CPU usage went up. The microbenchmark they ran beforehand showed a speedup on a 10-million-element list. A measurement on this machine:
cores: 2
sum of 1,000 longs: sequential 0.0004 ms, parallel 0.0058 ms
sum of 10,000,000 longs: sequential 6.0020 ms, parallel 2.7044 ms
Explain why the benchmark misled them, and what happens under load.
D3. A metrics counter that's slow and wrong
class Metrics { static volatile long ordersSeen; }
// in each request:
Metrics.ordersSeen++;
A profiler shows noticeable time in this line, and the dashboard's count is lower than the database's. A single-threaded measurement:
100M increments: plain field 2.7 ms, volatile field 962.1 ms
Explain both problems and fix them.
D4. A custom hash index that's slower than HashMap
A team wrote their own open-addressing hash index for order ids, with a table sized to a prime number "for better distribution" and index = hash % tableSize. Profiling shows time in the index computation itself. A measurement of just that step:
10M bucket indexes: k % n 86.9 ms, k & (n-1) 47.2 ms (same: true)
Explain the gap, and what the prime size was trying to fix.
Career-oriented
Interview prep
Mid level
Q1. Why is iterating over an ArrayList<Integer> slower than over an int[] of the same values, even though both are O(n)?
How to get there. Walk through the memory layout of each (references to boxed objects against contiguous primitives), then the consequences: more bytes per element, pointer chasing, poor prefetching, no SIMD. Quantify roughly.
Q2. What does volatile do in Java, at the hardware level, and when is it the right tool?
How to get there. Separate the three things people confuse: visibility (other threads see the write), ordering (no reordering across it), and atomicity (which it doesn't give for compound operations). Then map to hardware (caches are coherent, but compilers and CPUs reorder and keep values in registers) and to use cases.
Senior level
Q3. A service's throughput doesn't improve when you move it from an 8-core to a 32-core machine. How do you find out why?
How to get there. Form hypotheses from the chapter and Amdahl's law (serial sections, contention, memory bandwidth, external bottlenecks) and say how you'd test each. Measure utilisation first: are the extra cores busy or idle?
Q4. You need to compute daily per-kitchen statistics over 50 million orders held in memory as Java objects, and it takes 9 seconds. What would you try, in what order?
How to get there. Use the roofline idea: this is low-intensity, memory-bound work. So the first moves reduce bytes touched and improve locality (layout), then reduce work, then parallelise. Measure after each step.
Staff level
Q5. Leadership asks whether moving the platform to ARM servers will save 30% on compute costs. How do you answer with evidence?
How to get there. Chapter Exercises S3 plans the migration; this question is about the decision. Separate price-performance (benchmark your real workloads), migration cost and risk (native dependencies, images, tooling), and organisational cost. Propose an experiment with a decision rule.
Q6. How would you build a performance culture in an organisation where performance problems are only noticed when customers complain?
How to get there. Change feedback loops: make performance visible (SLOs, dashboards), testable (benchmarks and load tests in CI with thresholds), and owned (budgets per team), and grow skills with real examples. Avoid "optimise everything".