Revision and MasteryVol. 20 · Parts XX–XXII
0 / 0

Trails / Revision and Mastery

RV·213A

Concepts to Revisit Forever I: Computer Science and Java

The roadmap's first two lists of concepts worth revisiting forever, each restated from first principles in a few paragraphs, with a prompt to explain it aloud, the confusion that most often trips people, and where to relearn it: pointers and references, memory, processes, threads, networking, TCP, DNS, concurrency and data structures and algorithms; then Java's collections, generics, streams, exceptions, JVM, garbage collection, concurrency and virtual threads; with a lab measuring the memory hierarchy and the cost of creating processes, threads and virtual threads.

26 topics · ~15 min read · 16-question quiz
Updated Suggest a correction

Start here: why revisit what you already know

You learned these concepts once. You'll forget parts of them, not because they're hard, but because memory fades without use: within weeks, you can recognise an idea but no longer explain it. The roadmap's Part XX lists the concepts worth revisiting forever, because nearly every bug, design decision and interview question eventually comes back to them.

Revision here means retrieval, not rereading. For each concept below:

  1. Read only the heading. Explain the concept aloud (or write it) from memory, as if to a colleague.
  2. Then read the summary. What did you miss?
  3. Answer the "explain it" prompt without looking.
  4. If you were shaky, follow the "relearn" pointer and do one exercise there.
  5. Tick the topic only when you could teach it.

Two facts worth feeling

The lab measured two things these concepts predict:

Measurement Result
reading memory in a random chain that fits in the L1 cache (16 KB) 1.3 ns per read
the same chain at 256 MB (main memory) 174 ns per read: ~135× slower
reading the same 256 MB sequentially 0.7 ns per element
creating and waiting for a process (fork) 102 µs
creating and joining an OS thread (C) 34 µs
creating and joining a Java virtual thread 7.6 µs
100,000 virtual threads each sleeping 1 s finished in 1.3 s

Memory access patterns can matter more than instruction counts, and the cost of a unit of concurrency decides how you structure a server. Each number follows from a concept below.

How deep to go

Volume 17 defines six mastery levels. For revision, aim to hold every concept here at L3 (explain why it behaves as it does) permanently, and at L4 (debug with it) for the ones your work uses daily. A concept you can only recognise (L1) has faded; that's the signal to relearn it.

Computer science

Pointers and references

A pointer is a value that holds a memory address; dereferencing it reads or writes what's at that address. A reference is a safer, restricted pointer: it can't be arithmetic'd, and in managed languages it can't dangle because the garbage collector keeps the target alive. Every "pass by reference vs pass by value" question resolves the same way: Java, Python and JavaScript pass references by value, so a method can change the object you pass but not which object your variable refers to. In C and C++ the bugs are dangling pointers, double frees and buffer overruns; Rust prevents them at compile time with ownership and borrowing.

Explain it: why can a Java method add to a list you pass in, but list = new ArrayList<>() inside the method has no effect outside? Confusion to avoid: "Java passes objects by reference". Relearn: Volume 1, chapter 02; Volume 3, chapter 33.

Memory

Programs see a flat virtual address space; the OS and hardware map it, page by page (usually 4 KB), to physical memory, and the TLB caches those mappings. Data reaches the CPU through a hierarchy: registers, L1 (~1 ns), L2 (~4 ns), L3 (~10–40 ns), main memory (~100 ns), SSD (~100 µs), network (~0.5 ms in a data centre). Data moves in 64-byte cache lines, so locality (using nearby data, in order) decides performance as much as algorithms do. The stack holds call frames and is freed automatically; the heap holds longer-lived data and is managed by malloc/free, ownership, or garbage collection.

Explain it: why can an array of objects be much slower to traverse than an array of numbers in Java? Confusion: "RAM access is constant time". Relearn: Volume 1, chapters 07–08.

Processes

A process is a running program with its own virtual address space, file descriptors and security identity, isolated from others by the OS. Creating one (fork + exec on Unix) costs tens to hundreds of microseconds (the lab: ~100 µs); switching between processes costs a context switch and cache disruption. Processes communicate through pipes, sockets, shared memory or files. Isolation is why browsers put sites in separate processes and why containers are, underneath, processes with namespaces and cgroups.

Explain it: what happens, step by step, when you type a command in a shell and press Enter? Confusion: "a container is a small virtual machine". Relearn: Volume 1, chapter 08; Volume 6, chapters 79–80.

Threads

Threads are independent flows of execution inside one process, sharing its memory. The OS schedules them onto cores; each has its own stack and registers. Sharing memory makes communication cheap and correctness hard: without synchronisation, compilers and CPUs may reorder operations, and two threads updating the same data can lose updates. OS threads cost memory (stacks of ~1 MB reserved) and creation time (the lab: ~30–100 µs), which is why servers use pools, event loops or user-space threads (virtual threads, goroutines).

Explain it: why does adding threads to a CPU-bound Python program not help, while it does in Java? Confusion: "more threads, more speed". Relearn: Volume 1, chapter 08; Volume 3, chapter 38.

Networking

Data crosses networks in layers: links move frames between neighbours (Ethernet, Wi-Fi), IP routes packets between networks by address (best effort: packets can be lost, duplicated, reordered), transport adds ports and either reliability (TCP) or nothing (UDP; QUIC builds reliability on top), and applications speak protocols like HTTP. Latency comes from distance (light in fibre: ~5 µs per km, so Hyderabad to Mumbai, roughly 700 km of fibre, is ~3.5 ms one way and ~7 ms round trip at best, more in practice), from queueing in routers, and from round trips the protocol requires. Bandwidth is how much; latency is how soon. Most web performance is about latency.

Explain it: why does a page with 40 small requests load slowly over a high-bandwidth, high-latency link? Confusion: bandwidth and latency. Relearn: Volume 1, chapter 09; Volume 2, chapter 19.

TCP

TCP turns unreliable packets into a reliable, ordered byte stream: a three-way handshake (SYN, SYN-ACK, ACK) establishes sequence numbers; the receiver acknowledges data; lost segments are retransmitted after timeouts or duplicate ACKs; flow control (the receive window) stops a fast sender overwhelming a slow receiver; congestion control (slow start, then cautious growth, backing off on loss) shares the network. Costs to remember: one round trip before data can flow (plus one or more for TLS), slow start limiting early throughput, head-of-line blocking (one lost segment delays everything behind it), and TIME_WAIT holding closed connections for a while. Nagle's algorithm with delayed ACKs can add ~40 ms to small writes (Volume 19's Java lab).

Explain it: why do connection pools and keep-alive make such a difference? Confusion: "TCP preserves messages". Relearn: Volume 1, chapter 09.

DNS

DNS maps names to records (A/AAAA addresses, CNAME aliases, MX, TXT) through a hierarchy: a recursive resolver asks root servers, then the TLD's servers, then the domain's authoritative servers, caching each answer for its TTL. Most lookups are cache hits (microseconds locally, a few ms from a nearby resolver); misses take tens to hundreds of ms. DNS is also a control plane: failover and traffic steering change answers, limited by TTLs and by clients that cache longer than told. Many outages are DNS: an expired domain, a bad record, a resolver failure, or a negative answer cached.

Explain it: you changed a record's IP, but some users reach the old server for an hour; why? Confusion: "DNS changes are instant". Relearn: Volume 1, chapter 09; Volume 7, chapter 87.

Concurrency

Concurrency is structuring a program as independent tasks; parallelism is running them at the same time. Correctness needs three things: atomicity (an operation can't be seen half-done), visibility (one thread's writes become visible to another, guaranteed only by happens-before relationships such as locks, volatile or atomics), and ordering. The classic failures: race conditions (lost updates), deadlocks (circular waiting, prevented by lock ordering or timeouts), livelocks and starvation. Safer designs avoid shared mutable state: immutability, message passing, confinement to one thread, or a single writer.

Explain it: why can count++ from two threads lose increments, and name three fixes. Confusion: "it worked in testing, so it's thread-safe". Relearn: Volume 1, chapter 08; Volume 3, chapter 38.

Data structures and algorithms

Choose structures by operation costs: arrays give O(1) indexing and cache-friendly scans; linked lists O(1) insertion at known points but poor locality; hash tables O(1) average lookup (with resizing, collisions and a good hash); balanced trees O(log n) ordered operations and range queries; heaps O(log n) priority access; graphs for relationships, searched by BFS (shortest paths in unweighted graphs) or Dijkstra (weighted). Algorithms: sorting (O(n log n) comparison lower bound), binary search on sorted data, two pointers and sliding windows, dynamic programming (overlapping subproblems), greedy when a local choice is provably safe. Big-O describes growth; constants and memory layout decide real speed at your sizes.

Explain it: when would a sorted array beat a hash map for lookups? Confusion: Big-O as a speed measurement. Relearn: Volume 1, chapters 03–04.

Java

Collections

List (usually ArrayList: a resizable array, fast iteration and index access), Set and Map (usually HashMap/HashSet: hash buckets that become trees when crowded; or TreeMap for sorted keys; LinkedHashMap for insertion or access order, which makes a simple LRU cache), Deque (ArrayDeque for stacks and queues). Rules: keys must have consistent equals and hashCode and must not change while in a map; prefer immutable collections (List.of) for shared data; concurrent access needs ConcurrentHashMap and friends, not Collections.synchronizedMap around compound actions.

Explain it: what happens to a HashMap entry if you mutate a field used in the key's hashCode? Relearn: Volume 3, chapter 35.

Generics

Generics let types take type parameters (List<Order>), checked at compile time and erased at runtime (so List<String> and List<Integer> are the same class at runtime). Variance: List<Dog> is not a List<Animal>; use wildcards: ? extends T to read (producer), ? super T to write (consumer), "PECS". Bounded type parameters (<T extends Comparable<T>>) express requirements. Erasure explains the odd parts: no new T(), no instanceof List<String>, and heap-pollution warnings with generic varargs.

Explain it: why can't you add a Cat to a List<? extends Animal>? Relearn: Volume 3, chapter 36.

Streams

Streams describe a pipeline over data: a source, lazy intermediate operations (filter, map, flatMap), and a terminal operation (collect, reduce, forEach) that pulls elements through. Laziness means nothing runs until the terminal operation and short-circuiting operations (findFirst, anyMatch) stop early. Collectors (groupingBy, toMap) express aggregations. Pitfalls: side effects inside lambdas, parallel() for small or blocking workloads (it uses the shared ForkJoin pool), and reusing a stream (one use only).

Explain it: in list.stream().filter(...).map(...).findFirst(), how many elements are mapped? Relearn: Volume 3, chapter 37.

Exceptions

Exceptions separate the error path from the normal path. Checked exceptions (must be declared or caught) model recoverable conditions; unchecked (RuntimeException) model programming errors or conditions callers can't handle; Errors are for the JVM. Good practice: catch only what you can handle, at the level that knows what to do; preserve the cause when wrapping; use try-with-resources for anything closeable; never swallow exceptions silently; don't use them for normal control flow (stack traces are expensive). At service boundaries, translate them into problem-details responses.

Explain it: what does try-with-resources guarantee, and in what order are resources closed? Relearn: Volume 3, chapter 33.

The JVM

Java compiles to bytecode, which the JVM loads (class loaders), verifies, interprets, and compiles hot code to native code with the JIT (C1 quickly, C2 with aggressive optimisation guided by runtime profiles: inlining, escape analysis, deoptimisation when assumptions break). That's why Java warms up: the first seconds run slower than steady state. Memory: heap (objects), metaspace (class metadata), thread stacks, and off-heap buffers, all of which count toward a container's memory limit.

Explain it: why do benchmarks need warm-up iterations, and why does JMH exist? Relearn: Volume 3, chapters 40–41.

Garbage collection

The GC finds objects no longer reachable from roots (stacks, statics) and frees them. Generational collectors exploit the fact that most objects die young: frequent cheap young collections, rarer old collections. Modern collectors: G1 (the default; regions, pause-time goals), ZGC and Shenandoah (concurrent, sub-millisecond pauses at the cost of some throughput and memory). Tuning starts with sizing the heap and choosing the collector for the goal (latency vs throughput); then GC logs. Memory leaks in Java are references kept alive unintentionally: caches without bounds, listeners never removed, static collections.

Explain it: why can a Java service with a leak run fine for days, then pause for seconds and die? Relearn: Volume 3, chapter 41.

Java concurrency

The Java Memory Model defines when writes are visible across threads (happens-before via synchronized, volatile, java.util.concurrent classes, thread start/join). Tools by level: synchronized and ReentrantLock for mutual exclusion; atomics (AtomicLong, LongAdder) for counters; concurrent collections; executors for running tasks; CompletableFuture for composing asynchronous results; structured concurrency for treating related tasks as a unit. Prefer higher-level tools and immutability over raw locks.

Explain it: why does a volatile boolean stop flag work, but volatile int count; count++ doesn't? Relearn: Volume 3, chapter 38.

Virtual threads

Virtual threads (final in JDK 21) are JVM-scheduled threads: cheap to create (the lab: 7.6 µs vs 105 µs for platform threads), cheap to block (they unmount from their carrier thread during blocking I/O and sleeps), so a thread-per-request style scales to hundreds of thousands of concurrent requests. They don't make CPU-bound work faster, don't remove the need to limit concurrency toward slow dependencies (Volume 19's lab), and shouldn't be pooled. On JDK 21, blocking inside synchronized pinned the carrier thread (Volume 17's lab: 100 s instead of 0.11 s); JDK 24 removed most pinning.

Explain it: when would you still use a bounded executor with virtual threads available? Relearn: Volume 3, chapters 38–39; Volume 17, chapter 194B.

Lab: the memory hierarchy, and the cost of a unit of concurrency

Setup. The lab machine: an Intel Xeon at 2.3 GHz with 2 vCPUs (a cloud VM; its reported cache sizes are those of the host), gcc -O2, OpenJDK 21.

Experiment 1: memory latency by working-set size

A C program builds an array of size_t and links every element into one random cycle (each element holds the index of the next), then follows the chain for 20 million steps. Each read depends on the previous one, so the CPU can't overlap them: the time per step is the latency of wherever the data lives. For comparison, it also sums the same array sequentially.

Working set Random dependent read Sequential read
16 KB 1.28 ns 0.26 ns/element
32 KB 1.31 ns 0.26
256 KB 4.11 ns 0.29
1 MB 5.47 ns 0.27
4 MB 44.6 ns 0.50
16 MB 68.9 ns 0.52
64 MB 138.2 ns 0.73
256 MB 173.7 ns 0.68

Experiment 2: creating units of concurrency

Unit Create + wait for completion
process: fork(), child _exit(0), parent waitpid (C) 101.8 µs
OS thread: pthread_create + pthread_join (C) 33.6 µs
Java platform thread: Thread.ofPlatform().start() + join() 105.4 µs
Java virtual thread: Thread.ofVirtual().start() + join() 7.6 µs
100,000 virtual threads, each sleeping 1 s, all started then joined 1.32 s in total

(Java figures are from the second of two rounds, after JIT warm-up.)

What it shows

  • The hierarchy is real and steep. Latency stepped from ~1.3 ns (L1) to ~4–5 ns (L2) to tens of ns, then ~140–170 ns once the data no longer fit in caches and the page-table cache (TLB) started missing too. That's a ~135× range for the "same" operation.
  • Sequential access hides latency. Even at 256 MB, a sequential scan cost 0.7 ns per element, ~250× faster than random access, thanks to prefetching and 64-byte cache lines.
  • Design consequence: data layout (arrays of values rather than pointers to scattered objects, columnar formats for analytics, B-trees with wide nodes) often matters more than a better Big-O.
  • Processes and OS threads cost tens to a hundred microseconds to create on this VM; Java's platform threads cost about the same as a process here (JVM bookkeeping on top of the OS thread). A thread per request needs pooling, unless threads are virtual.
  • Virtual threads are ~14× cheaper to create than platform threads, and 100,000 blocked ones cost little: the 1.32 s total is the 1 s sleep plus the time to start and join 100,000 threads.

Try it yourself

  1. Add a stride-64-bytes access pattern (touch one value per cache line) and compare with sequential.
  2. Allocate the 256 MB array with huge pages (madvise(MADV_HUGEPAGE)) and see whether TLB misses shrink.
  3. Run the Java program with -Xss256k and with 10,000 platform threads sleeping 1 s; compare memory with the virtual-thread version.
  4. Measure context-switch cost with two threads ping-ponging through a pipe.

Revision sheet: CS and Java concepts

One line each

  • Pointers/references: addresses vs restricted handles; Java passes references by value.
  • Memory: virtual pages, TLB, cache lines, ~1 ns → ~100 ns; locality decides speed.
  • Processes: isolated address spaces; ~100 µs to create.
  • Threads: shared memory, own stacks; correctness needs synchronisation.
  • Networking: layers; latency from distance and round trips.
  • TCP: reliable ordered bytes; handshake, retransmission, flow and congestion control.
  • DNS: hierarchical, cached by TTL; a common outage cause.
  • Concurrency: atomicity, visibility, ordering; avoid shared mutable state.
  • DSA: choose by operation costs and memory layout.
  • Collections: equals/hashCode contracts; immutable by default; concurrent versions for sharing.
  • Generics: compile-time types, erasure, PECS.
  • Streams: lazy pipelines pulled by terminal operations.
  • Exceptions: handle where you can act; keep causes; try-with-resources.
  • JVM: bytecode, JIT with profiles, warm-up; all memory areas count in containers.
  • GC: generational; G1 default; ZGC/Shenandoah for low pauses; leaks are unintended references.
  • Java concurrency: happens-before; prefer high-level tools.
  • Virtual threads: cheap to create and block; still limit concurrency; not for CPU-bound speed-ups.

Numbers to remember

  • L1 ~1.3 ns, L2 ~4–5 ns, RAM ~140–170 ns random; sequential ~0.3–0.7 ns/element.
  • fork ~100 µs; pthread ~34 µs; Java platform thread ~105 µs; virtual thread ~7.6 µs.
  • Light in fibre ~5 µs/km.

Glossary

  • TLB: cache of virtual-to-physical page mappings.
  • Happens-before: the Java Memory Model's visibility guarantee.
  • Carrier thread: an OS thread that runs virtual threads.
  • Head-of-line blocking: one lost packet delaying later data on the same stream.
  • PECS: producer extends, consumer super.