Skip to content

Java earns its place in a book about building systems because the JVM underneath it is one of the most heavily engineered runtimes in existence. Modern Java is not the language of a decade ago: records give you immutable data in one line, sealed interfaces and pattern-matching switch give you algebraic data types, and virtual threads make blocking I/O cheap enough that you can write one thread per request again. The exercises in this chapter push you into the JVM’s internals (generics by erasure, garbage collection, the class-file format) and into its modern features at the same time.

Concepts from other sections (6)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

  • Algebraic data type (ADT): a type built from sums (“one of these variants”) and products (“all of these fields”), such as a Rust enum with payloads; with exhaustive matching, every case must be handled explicitly. Read more: Chapter 21: Rust
  • Type erasure: hiding a concrete type behind a uniform interface so unrelated types can be stored as one type. Read more: 19.7 Function: type erasure with a small buffer
  • Thread pool: a fixed set of long-lived worker threads that execute tasks taken from a shared queue. Read more: 18.7 Thread pool
  • Escape analysis: a compiler pass that keeps a value on the stack unless a reference to it can outlive the function, in which case the value is moved to the heap; Go and the JVM use it to reduce garbage-collector work. Read more: Chapter 20: Go
  • Event sourcing: storing only the history of changes and deriving all state from it. Read more: 7.2 The workflow service in Systems Engineering
  • backpressure: a slow consumer slowing its producer, so memory between them stays bounded. Read more: 1.9 Async Rust and tokio: futures, tasks, channels, cancellation, hyper

Note: Java is an optional language here. None of the core books target it, so these exercises have no worked solutions yet and nothing in this chapter is built in CI. The briefs are kept because they are worth reading as design problems. If you want a toolchain, install it with mise and pin it in a .mise.toml; on a chezmoi-managed machine it comes from the install_alt_langs flag, which is off by default. On macOS, /usr/bin/java is a stub that exists and only prints “Unable to locate a Java Runtime”, so check for a real JDK with javac -version, not command -v javac.

Learning objectives

  • Describe the JVM’s memory model, Java’s type system and its use of type erasure, and the language’s error-handling and concurrency models.
  • Apply modern Java idioms (records, sealed interfaces with pattern matching, virtual threads, try-with-resources) when designing a small system.
  • Explain what type erasure prevents you from doing at run time, and how a generic container works around it.
  • Reason through the design of each exercise brief before writing code.

You should be able to write, compile, and run a small Java program and read generic signatures such as <T extends Comparable<? super T>>. The concurrency briefs assume you know what a lock and a thread pool are; the JVM-internals briefs assume you have met a stack machine and a mark-sweep collector, at least by name.

Memory is managed by the JVM’s garbage collector (G1 by default, ZGC for low pause times). Objects live on the heap and locals on the stack, and escape analysis lets the JIT keep short-lived objects off the heap entirely. Value types are in preview under Project Valhalla.

The type system is strong and static. Generics are implemented by erasure: List<String> and List<Integer> are the same class at run time, which is why you cannot write new T[]. Sealed classes restrict which types may extend a hierarchy, and records declare immutable data carriers with generated accessors, equals, and hashCode.

Errors are exceptions, split into checked exceptions (which a method must declare) and unchecked ones. Optional expresses “maybe absent” without null, and try-with-resources closes any AutoCloseable deterministically.

Concurrency spans the full range: virtual threads (Java 21 and later) for I/O-bound work, CompletableFuture for asynchronous composition, the java.util.concurrent toolkit of locks, queues, and executors, and structured concurrency for scoping a group of tasks to one block. Builds use Gradle or Maven, and jshell gives you a REPL. The exercises target Java 21 LTS or later.

  • Records for immutable data-transfer objects.
  • Sealed interfaces with pattern matching in switch expressions, so the compiler checks that every case is handled.
  • Virtual threads instead of thread pools for I/O-bound work.
  • The Stream API for functional processing of collections.
  • Try-with-resources for cleaning up anything AutoCloseable.
  • Optional instead of returning null.
  • var for local variable type inference where the type is obvious from the right-hand side.

The briefs are listed below, ordered by concept rather than by difficulty, so choose by the difficulty rating (1 is easiest, 5 hardest) rather than by number.

#ExerciseConceptsDifficulty (1-5)
01ArrayList<T> from scratchGenerics, type erasure, Iterable2
03Virtual thread HTTP serverVirtual threads, ServerSocket, structured concurrency3
04Dependency injection (mini-Spring)Reflection, annotations, Proxy4
05Stream collector libraryCollector interface, Spliterator, parallel streams3
06Event sourcing frameworkRecords, sealed interfaces, pattern matching4
07Garbage collector simulatorMemory model, reference types, mark-sweep4
08Bytecode interpreter (subset)ClassFile format, operand stack, JVM internals5
09Reactive streams publisherFlow API, backpressure, SubmissionPublisher4
10Annotation processorjavax.annotation.processing, code generation4

There is no exercise 02. It was a concurrent hash map, and that problem is now covered in full by A Swiss table and A Robin Hood hash map in the Systems data structures chapter of Algorithms.

  • Virtual thread: a lightweight Java thread (Java 21 and later) that the JVM schedules onto a few platform threads, cheap enough that blocking I/O code can use one thread per request.
  • Java record: a class declared as record Point(int x, int y), an immutable data carrier for which the compiler generates the constructor, accessors, equals, and hashCode.
  • Sealed class / sealed interface: a Java class or interface that lists the only types allowed to extend it, so a pattern-matching switch over it can be checked for exhaustiveness; with records, Java’s way to write algebraic data types.
  • Checked exception: a Java exception that a method must declare in its throws clause and that callers must catch or declare in turn, unlike unchecked exceptions, which need neither.
  • Try-with-resources: a Java try form that closes every AutoCloseable resource it declares when the block exits, normally or by exception, in reverse order of opening.
  • Structured concurrency: scoping a group of concurrent tasks to one block, so the block does not exit until all of them have finished and a failure in one cancels the rest.