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

Workbench / Volume 1 Exercises: Foundations of Computing

V1·10

Compilers and Runtimes

Exercises for Volume 1, chapter 10: the compiler pipeline (lexing, parsing and grammars, ASTs, name resolution, type checking, intermediate representations and SSA, optimisation, code generation), linking and loading (static and dynamic, Java's class loading and linking), and runtime models (native code, bytecode VMs, interpreters, JIT and tiered compilation, AOT for managed languages, tracing JITs, garbage collection). 12 theory questions, 12 programming exercises, 3 cumulative projects with chapters 01–09, the concepts the chapter leaves out, and 6 senior-level exercises.

40 exercises · ~18 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. You'll build a small language front end (P1–P3), read the bytecode javac produces (P4–P6), watch HotSpot's JIT and garbage collectors at work (P7–P10), and look at native linking (P11–P12). Outputs come from this book's sandbox: Java 21 (HotSpot), clang/LLVM 18, gcc 13, Python 3.13 and Node 22 on a 2-vCPU x86-64 VM.

As in chapter 07, every timing in Java should come from later runs, after the JIT has compiled the code; P7 shows exactly how much the first runs differ.

Coverage map.

Chapter component Exercises
front end, middle end, back end T1
lexical analysis T2, P1
parsing, grammars, precedence and associativity T2, P2
abstract syntax trees T2, P2, P3
name resolution, semantic analysis, type checking T3, P3, P6
intermediate representations, SSA T4, P12
optimisation (constant folding, inlining, DCE, escape analysis…) T5, P5, P8, P9
code generation T4, P12
linking (static, dynamic), loading T6, P11
Java's linking and loading: class loading, constants, binary compatibility T7, P5
native code, bytecode VMs, interpreters T8, P4
JIT compilation, tiers, OSR, deoptimisation, inline caches T9, P7, P9
AOT for managed languages; tracing JITs; start-up T10, P10
garbage collection T11, P8
how the six languages compare end to end T12

Theory

T1. The pipeline

  1. Name the stages of a compiler and say what each produces, using javac + HotSpot and clang as two examples. Where do Java's "front end" and "back end" run, and when?
  2. Classify each error by the stage that catches it: int x = "hi";, int 9lives = 1;, foo(1, 2 (missing parenthesis), calling an undefined method, an infinite loop, a NullPointerException, a NoSuchMethodError at run time.
  3. Why do compilers have an intermediate representation instead of translating each language straight to each CPU?

T2. Lexing, grammars and parsing

  1. What does a lexer do with whitespace, comments, keywords, identifiers, number literals and string literals? Why is "maximal munch" needed (x+++y in Java, >> in generics)?
  2. Write a grammar (in EBNF) for arithmetic with + - * / ^, unary minus and parentheses, where ^ is right-associative and binds tighter than unary minus (so -2 ^ 2 is −4), and * binds tighter than +.
  3. Why do 10 - 4 - 3 and 2 ^ 3 ^ 2 group differently, and how does a recursive-descent parser express left versus right associativity? What goes wrong with a naive left-recursive rule like expr := expr '-' term in recursive descent?
  4. Why are ASTs, not parse trees, what later stages work on?

T3. Names, scopes and types

  1. What does name resolution do? Explain shadowing and why Java rejects int x = 1; { int x = 2; } inside one method but allows a local to shadow a field.
  2. Static vs dynamic typing, strong vs weak typing: place Java, Kotlin, TypeScript, Python, JavaScript, C and Go on both axes, with an example of each "weak" behaviour.
  3. Explain type erasure in Java generics. Using P6: why is List<String>.class == List<Integer>.class true, and how did an Integer get into a List<String> ("heap pollution") and fail far from where it was inserted?
  4. What does type inference do (var, lambdas, generic methods), and where does it stop in Java?

T4. Intermediate representations and SSA

  1. What is SSA (static single assignment) form, and what is a φ (phi) node? Convert this to SSA:
Text
s = 0; i = 0
while (i < n) { s = s + i; i = i + 1 }
return s
  1. Why do compilers love SSA? Name two optimisations it makes simpler.
  2. Why does clang's -O0 IR store every variable in memory (alloca, load, store), and what does the mem2reg pass do?
  3. What does the back end still have to do after optimisation (instruction selection, register allocation, scheduling), and why is register allocation hard?

T5. Optimisations you can rely on (and ones you can't)

For each, explain what it does and give an example where it changes how you should write or benchmark Java code: constant folding, inlining, dead-code elimination, common-subexpression elimination, loop-invariant code motion, bounds-check elimination, escape analysis and scalar replacement, devirtualisation, auto-vectorisation. Then explain why P8's walk loop still allocated 320 MB while P8's local loop allocated 0 bytes.

T6. Linking and loading native code

  1. What's in an object file (code, data, symbol table, relocations)? What does the linker do with them?
  2. Compare static and dynamic linking: size, start-up, updates, LD_PRELOAD, licensing, and containers. P11 built a hello world both ways: 16 KB dynamic and 785 KB static.
  3. What does the dynamic loader (ld-linux.so) do when a dynamically linked program starts? What are the PLT and GOT, and what is lazy binding?
  4. Explain "symbol not found" / "undefined reference" at link time versus error while loading shared libraries at run time versus UnsatisfiedLinkError in Java.

T7. Java's version of linking and loading

  1. Describe class loading: loading, linking (verification, preparation, resolution) and initialisation. When does a class's static initialiser run?
  2. Explain the class-loader hierarchy (bootstrap, platform, application) and parent delegation. Why do application servers and plugin systems use their own class loaders, and what's a ClassCastException: Foo cannot be cast to Foo?
  3. P5 compiled Cart against Limits.MAX_ITEMS = 10, then changed it to 20 and recompiled only Limits. Cart still printed 10 for MAX_ITEMS but 20 for MAX_BOXED. Explain, and say what this means for libraries.
  4. What do NoSuchMethodError and NoClassDefFoundError usually mean in a real project, and how do you track them down?

T8. Native code, bytecode VMs and interpreters

  1. Compare the execution models of C/Rust/Go (AOT native), Java/Kotlin (bytecode + JIT), C# (.NET), JavaScript (V8), and CPython on: start-up, peak speed, memory, portability and deployment artefact.
  2. P4: javap -c showed "Hi " + name + " x" + n compiled to a single invokedynamic (makeConcatWithConstants), and a switch on strings compiled to hashCode() + lookupswitch + equals. Why does javac emit invokedynamic here instead of a StringBuilder chain, and why does a string switch need equals after the hash?
  3. Stack-based versus register-based bytecode: what's the difference, which is the JVM, which is Lua or Dalvik, and why did Android choose registers?
  4. The chapter's lab ran a tiny language as a tree-walker (370 ms), a bytecode VM written in Python (518 ms) and compiled to Python source (53 ms). Explain why the bytecode VM lost, and why compiling to Python won.

T9. JIT compilation in HotSpot

  1. Describe HotSpot's tiered compilation (interpreter, C1 with profiling, C2), what triggers each tier, and what on-stack replacement (OSR) is. Read P7's PrintCompilation lines for Warm::price: % at level 3 then 4, normal compiles at 3 then 4, and "made not entrant".
  2. P7 timed one call of price over 1,000 items: 28.6 µs on the first call, 4.3 µs at call 1,000, 0.9 µs at call 100,000; with -Xint (interpreter only), 12.7 µs even after 100,000 calls. Explain the curve. Why was the first call slower than the pure interpreter's steady state?
  3. What are inline caches, and what do monomorphic, bimorphic and megamorphic call sites mean? P9 measured 0.84 ns per interface call with one receiver class, 5.42 with two, 13.3 with three, 15.2 with four. Explain.
  4. What is deoptimisation, and what kinds of events trigger it? Why can a Java service get slower for a while after a rare code path runs for the first time?

T10. Start-up, AOT and tracing JITs

  1. P10 measured a hello world: C 2 ms, Python 21 ms, Node 23–27 ms (146 ms on a cold first run), Java 39–46 ms with class-data sharing (CDS) and 123 ms with -Xshare:off. Java loaded 455 classes, 452 from the CDS archive. Explain what CDS does and why it matters.
  2. Compare ways to make Java start faster: AppCDS, tiered-compilation tuning, GraalVM Native Image (AOT), CRaC (checkpoint/restore) and Project Leyden. What does Native Image give up?
  3. What's a tracing JIT (LuaJIT, PyPy, early TraceMonkey), and how does it differ from HotSpot's method JIT?

T11. Garbage collection

  1. Explain reachability from GC roots, and compare reference counting, mark-sweep, mark-compact and copying collection. Why does Python use reference counting plus a cycle collector, and why does the JVM use tracing?
  2. What is the generational hypothesis, and how do young and old generations, minor and major collections, and write barriers / card tables implement it?
  3. P8 ran the same allocation-heavy program (3.1 GB allocated, ~155,000 live entries) with four collectors in a 512 MB heap:
Collector Run time Pauses Longest pause Total pause
Serial 1,483 ms 65 147.1 ms 912 ms
Parallel 824 ms 28 16.8 ms 288 ms
G1 1,026 ms 24 23.9 ms 308 ms
ZGC 1,380 ms 33 0.030 ms under 1 ms

Explain each row, and say which collector you'd choose for a batch job, a latency-sensitive API, and a small container with 1 CPU.

  1. What are the common causes of OutOfMemoryError in Java besides "the heap is too small" (metaspace, direct memory, threads, GC overhead limit), and how do you diagnose a memory leak?

T12. The six languages end to end

For one function, "sum the even numbers in a list of integers", describe what happens from source to execution in Java, Kotlin, C, Go, Python and JavaScript: who compiles what and when, what's in the artefact, how the integers are represented in memory (boxed or not), and roughly how fast the hot loop runs relative to C.

Programming exercises

P1. A lexer

In Java, write List<Tok> lex(String s) for arithmetic expressions: numbers (integers and decimals), operators + - * / ^, parentheses, whitespace; each token records its kind, text and position. Report the position of any unexpected character. Test with 12 $ 4, 3.5*(2+1), an empty string and a string of only spaces.

P2. A recursive-descent parser and evaluator

Using T2's grammar, write a parser that builds an AST of Num, Neg and Bin records (a sealed interface), and an evaluator using a switch over the sealed type. Print the value and the tree for 1 + 2 * 3, (1 + 2) * 3, 2 ^ 3 ^ 2, -2 ^ 2, 10 - 4 - 3, 8 / 2 / 2, and the errors for 2 * (3 + 4, 3 + * 4, 12 $ 4 and 1 2.

P3. Variables, scopes and a type checker

Extend P2's language with let x = expr; statements, variables in expressions, nested blocks { … } with lexical scope, and two types, num and bool (comparisons <, == produce bool; if c then a else b requires bool and branches of the same type). Write a separate checker pass that reports undefined variables, redeclaration in the same scope, and type errors with positions, before any evaluation. Test with programs that use a variable before declaration, shadow in an inner block, and add a number to a boolean.

P4. Read the bytecode javac produces

Compile a class with: a string concatenation "Hi " + name + " x" + n, a switch on a string with two cases, an autoboxing assignment Integer b = x;, and a for-each loop over an int[]. Run javap -c and find: the invokedynamic for concatenation, hashCode + lookupswitch + equals for the switch, Integer.valueOf for boxing, and the loop's bytecode. Then print Integer comparisons 127 == 127 and 128 == 128 with == and equals.

P5. Compile-time constants and binary compatibility

Create Limits with public static final int MAX_ITEMS = 10; and public static final Integer MAX_BOXED = 10;, and Cart that prints both. Compile both and run. Change both values to 20, recompile only Limits, and run Cart again. Inspect javap -c Cart to see why. Then think through what this means for a library you publish.

P6. Erasure and heap pollution

Show that new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass(). Then put an Integer into a List<String> through an unchecked cast, and find where the ClassCastException appears. Finally, write a type-safe heterogeneous container (Map<Class<?>, Object> with put(Class<T>, T) and get(Class<T>) using Class.cast) and explain why it doesn't suffer the same problem.

P7. Watch the JIT warm up

Write price(long[] items) that sums x * 118 / 100 over 1,000 items, call it 100,000 times, and print the time of calls 1, 10, 100, 1,000, 10,000 and 100,000. Run normally, with -Xint, and with -XX:+PrintCompilation (grep for price). Explain each tier transition.

P8. Escape analysis

Write two loops of 10 million iterations using a record Point(double x, double y) with plus: (a) local: each iteration creates two Points, adds them and accumulates their coordinates in a double; (b) walk: p = p.plus(step) carries a Point across iterations. Measure time and bytes allocated per run with com.sun.management.ThreadMXBean.getThreadAllocatedBytes, for six runs. Repeat with -XX:-DoEscapeAnalysis.

P9. Monomorphic, bimorphic, megamorphic

Create an interface Fee with four implementations, fill an array of 2²⁰ fees with 1, 2, 3 and then 4 different implementations at random, and time s += f.apply(k) over the array (50 passes) for each mix. Then sort each array by class and time again. Explain both sets of results.

P10. Start-up, class loading and CDS

Measure the wall-clock start-up of a hello world in Java (default, -Xshare:off, -Xint), Python, Node and C (dynamically and statically linked), repeating each a few times. Count the classes the JVM loads with -verbose:class and how many came from the CDS archive. Then create an AppCDS archive for a larger application (a Spring Boot demo or your C1 project from chapter 09) and compare its start-up time with and without it.

P11. Linking and symbols in C

Write a C library price.c with long gst(long paise) and a main.c that calls it. Build: (a) both into one executable; (b) price.c as a shared library libprice.so linked dynamically (run with and without LD_LIBRARY_PATH); (c) statically. Use nm to see defined (T) and undefined (U) symbols in main.o, ldd to see dependencies, and readelf -d for the NEEDED entries. Then write an LD_PRELOAD shim that overrides gst to print a message, and show it works for (b) but not (c).

P12. From C to LLVM IR to assembly

Write long sum_to(long n) { long s = 0; for (long i = 0; i < n; i++) s += i; return s; }. Produce LLVM IR at -O0 and -O2 (clang -S -emit-llvm -O0 -o - f.c), and assembly at -O2. In the -O0 IR, find the allocas and loads/stores; in the -O2 IR, find whether the loop survived. Then do the same in Java: write the same method and check with JMH or a timing loop whether HotSpot's C2 also removes the loop (compare n = 10⁶ and n = 10⁹).

Cumulative projects (chapters so far: 01–09)

C1. A filter language for the TiffinBox API

Product wants an admin search endpoint accepting filters like price < 200 and (veg or rating >= 4.5) and kitchen.city == "Hyderabad". Build the whole pipeline in Java: a lexer (numbers, strings with escapes, identifiers with dots, operators, and/or/not), a parser with correct precedence (not > comparison > and > or), a checker against a schema (field names and types: price: paise long, veg: bool, rating: decimal, kitchen.city: string), and two back ends: (a) an evaluator over in-memory Order records, and (b) a translator to a parameterised SQL WHERE clause (never string concatenation of values). Add limits (maximum length, depth, number of terms) and helpful error messages with positions, and expose it as GET /orders?filter=… (URL-encoded) returning 400 with the error on bad filters.

Combines: CLI testing (ch 01); clean code and error handling (ch 02); maps for the schema (ch 03); recursion and complexity limits (ch 04); boolean logic (ch 05); money as paise and decimal parsing (ch 06); performance of evaluation (ch 07); resource limits (ch 08); HTTP, URL encoding and status codes (ch 09); the whole front end of a compiler (ch 10).

C2. A bytecode VM for the filter language

Compile C1's checked AST into a compact bytecode (stack-based: LOAD_FIELD i, PUSH_CONST k, LT, EQ, AND, OR, NOT, JUMP_IF_FALSE, JUMP_IF_TRUE for short-circuit evaluation), and write a VM loop in Java. Benchmark three execution strategies over 1 million orders: the AST walker, the bytecode VM, and generating a Java Predicate<Order> by composing lambdas ("closure compilation"). Explain the results with this chapter's JIT concepts.

Combines: arrays and stacks (ch 03); short-circuit logic and complexity (ch 04, 05); integer encoding of instructions (ch 06); branch prediction and caches (ch 07); measurement discipline (ch 01–07); bytecode, interpreters and JIT (ch 10).

C3. A JVM memory and GC investigation

TiffinBox's order service (Java 21, G1, container limit 2 GiB, -XX:MaxRAMPercentage=70) shows p99 latency spikes of 150 ms every few minutes, and old-generation occupancy after each mixed collection rises slowly over days. Plan and carry out (on a reproduction you build) an investigation: GC logging setup, what to read in the logs, allocation profiling, heap dumps and leak analysis, and the fixes. Build the reproduction: a small HTTP service (chapter 09's C1 or any framework) with a deliberate leak (an unbounded cache keyed by request parameters) and a high allocation rate (building large JSON strings), then fix both and show the before/after GC metrics.

Combines: CLI tools and logs (ch 01); code quality (ch 02); hash maps and caches (ch 03); rates and growth (ch 04, 05); sizes in bytes (ch 06); memory hierarchy (ch 07); containers, memory limits and the OOM killer (ch 08); HTTP load generation (ch 09); garbage collection and escape analysis (ch 10).

What the chapter leaves out

JVM diagnostics: JFR, jcmd and async-profiler

The JVM ships with a production-grade flight recorder: JFR records GC, JIT, allocation, locks, I/O, exceptions, thread states and custom events with low overhead (typically about 1%), and can run continuously (-XX:StartFlightRecording). jcmd is the Swiss army knife: thread dumps, heap dumps, class histograms (GC.class_histogram), native memory (VM.native_memory), flags, and starting JFR on a running process. async-profiler gives accurate CPU, allocation, lock and wall-clock flame graphs without the safepoint bias of older profilers. Knowing these three makes most performance and memory problems tractable in production, not just in development.

Code generation in the Java ecosystem: annotation processors, proxies, bytecode libraries

A lot of Java "magic" is compiler technology: annotation processors run inside javac and generate source (Lombok goes further and edits javac's AST; MapStruct, Dagger, Micronaut and record builders generate code); frameworks create dynamic proxies (java.lang.reflect.Proxy) or subclasses at run time with bytecode libraries (ByteBuddy, ASM, cglib) to implement transactions, lazy loading (Hibernate), mocking (Mockito) and AOP (Spring). Knowing this explains why @Transactional doesn't work on a method called from the same class (the call bypasses the proxy), why final classes break some frameworks, why Native Image needs build-time metadata, and how to read stack traces full of $$SpringCGLIB$$ frames. JDK 24 added a standard Class-File API for reading and writing bytecode.

Dependency hell and how builds resolve it

T7's NoSuchMethodError is the visible symptom of dependency resolution. Maven picks the nearest version in the dependency tree; Gradle picks the highest by default; both can silently produce a combination nobody tested. Tools: dependency trees and insight reports, BOMs (bills of materials, such as Spring Boot's or Jackson's) to align versions, enforcer rules for convergence, shading (relocating a dependency's packages inside your JAR to avoid conflicts, at the cost of size and patching), and the Java module system (JPMS) for strong encapsulation (rarely used for applications, but it's why --add-opens flags appear when libraries use reflection on JDK internals). Supply-chain security (signed artefacts, SBOMs, scanning for vulnerable versions) builds on the same graph: Volume 8.

WebAssembly as a compilation target

WebAssembly is a portable, sandboxed, stack-based bytecode (like the JVM's, but with linear memory instead of objects and GC, though a GC proposal now exists) that browsers and standalone runtimes (Wasmtime, WasmEdge) execute at near-native speed after compiling it. C, C++, Rust, Go, Kotlin (Kotlin/Wasm) and others compile to it; it runs plugins safely inside servers (Envoy filters, database extensions), edge functions (Cloudflare Workers, Fastly), and heavy code in browsers (Figma, video editing, games). It's the same compiler architecture as this chapter (front ends to an IR to a portable target) with a security model designed in. Volume 2's chapter 29 covers it in the browser.

Compilers you use without noticing: regex, SQL, templates

Many everyday tools are compilers. Regular expressions are compiled to automata or backtracking programs (chapter 04's ReDoS was a consequence of the backtracking implementation). SQL is parsed, checked, and optimised by a query planner that chooses join orders and indexes using cost models and statistics, then executed by an interpreter or generated code; EXPLAIN shows you its "assembly" (Volume 4). Template engines, JSON path and GraphQL queries, build-system DSLs (Gradle's Kotlin scripts), and infrastructure-as-code tools (Terraform plans) are all front end + IR + back end. Recognising the shape helps: errors have positions, there's a checking phase you can run early, and performance depends on what the "compiler" can prove.

Security in the runtime: verification, deserialisation and sandboxing

The JVM verifies bytecode so that a malicious class file can't corrupt memory, but higher-level features have been the real attack surface: Java deserialisation (ObjectInputStream) of untrusted data could instantiate arbitrary classes and run "gadget chains" leading to remote code execution (a decade of critical vulnerabilities in libraries and application servers); expression languages and template engines that evaluate user input (Log4Shell in 2021 was a lookup feature in a logging library evaluating attacker-controlled strings, fetching and running remote code via JNDI). Rules: never deserialise untrusted data with Java serialisation (use JSON with explicit types, or serialisation filters), never evaluate user input as code or expressions, and keep runtimes and libraries patched. The Security Manager, the old in-JVM sandbox, is deprecated for removal: isolate untrusted code with processes, containers or WebAssembly instead.

Senior exercises

S1. The service is slow for two minutes after every deploy

After each deploy, a Java service's p99 latency is 3–5× normal for about two minutes, triggering alerts and occasionally autoscaling, which adds more cold instances. Explain the causes with this chapter's concepts, list the measurements that would confirm them, and design fixes at three levels: JVM, application and deployment.

S2. Review a PR that adds a scripting feature

A PR lets admins define pricing rules as JavaScript snippets stored in the database, executed with GraalJS (or the old Nashorn) inside the order service on every order. Review it from compiler/runtime, performance and security angles, and propose an alternative design if you'd reject it.

S3. Choose a runtime strategy for a new fleet of functions

TiffinBox wants 40 small event-driven functions (resize photos, send notifications, recompute kitchen ratings), each invoked 10–10,000 times per hour, on a serverless platform billed per millisecond and memory. Compare JVM with tuned start-up, GraalVM Native Image, Go, Node.js and Python on cold start, steady-state cost, developer productivity for a Java team, library availability and operational risk. Recommend an approach.

S4. Diagnose a NoSuchMethodError in production

A service upgrades the internal library tiffin-common from 3.4 to 3.5. The changelog says "MenuClient.fetch now returns Collection<Dish> instead of List<Dish>; source compatible for most callers", and the service compiles and passes its tests. In production, one endpoint fails with java.lang.NoSuchMethodError: 'java.util.List com.tiffinbox.common.MenuClient.fetch(java.lang.String)', although fetch(String) clearly exists. The stack trace shows the call coming from tiffin-orders-sdk, another internal library built a year ago. Explain how this can happen, how you'd find the root cause in 15 minutes, the immediate fix, and the long-term prevention.

S5. Decide whether to switch garbage collectors

The team proposes switching all services from G1 to ZGC "because pauses are microseconds". Write a decision document: what ZGC changes, the measured trade-offs from P8 and what you'd measure in your own services, which services should switch, and a rollout plan.

S6. Explain "why is Java slow to start but fast later?" to a product manager

A product manager asks why the new Java services take seconds to start and are slow right after a deploy, when "the Go service starts instantly". Write a clear explanation in under 250 words, with an analogy, that leads to the decision you need from them (accepting a warm-up step in deploys that makes them take two minutes longer, or funding a Native Image migration for two services).