Volume 3 Companion: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Companion: The Backend

V3·40

JVM Internals

Companion to Volume 3, chapter 40: how runtimes, bytecode, class loading, memory areas, the JIT and garbage collection connect; new angles (the JVM as a kitchen that learns its regulars' orders, the constant pool as a class's phone book, a non-daemon thread as the last cook who keeps the restaurant open); what the chapter simplifies, measured on JDK 21 and the build's stage 41: a server that hung forever when its port was taken because a log thread kept the JVM alive, a constructor that failed and kept a file lock, a source-level rule that missed method references the class files showed, and how far TiffinBox's first request is from its ten-thousandth; the theory behind lazy linking and JIT compilation; how the JVM shuts down; four debugging drills; interview questions with how to approach each.

6 sections · ~12 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 40 has seven parts: runtimes (from none to a full VM, the life of a Java program), bytecode (the stack machine), classes at run time (loading, loaders, verification), memory layout (data areas, objects on the heap), execution (tiered compilation, inlining, deoptimisation, safepoints), garbage collection (first principles, metrics, HotSpot's collectors, logs, sizing) and other runtimes.

starting code running fast memory runtimes none to a full VM life of a program threads, exit, hooks class loading lazy, on first use loaders, verification delegation bytecode a stack machine constant pool symbolic references linking resolve on first use objects on the heap headers, fields interpreter slow, starts at once tiered compilation C1, then C2 inlining profiles, bets deoptimisation, safepoints undo a bet GC first principles reachability, generations GC metrics pause, throughput, footprint HotSpot collectors Serial … ZGC logs and sizing containers, headroom for Java starts with by names via resolved by then objects then by undone by judged by trade-offs of tuned by goes deeper: ch38 concurrency · ch39 modern Java · ch41 memory and performance · ch42 modules and packaging exercises: P1–P10 class files, initialisation, loader leaks, escape analysis, deopt, containers, GC logs, safepoints, JFR, runtimes; C1–C3
Concept map of chapter 40, JVM internals: runtimes and the life of a Java program, bytecode and the stack machine, classes at run time (loading, class loaders, verification), memory layout (runtime data areas, objects on the heap), execution (interpreter, tiered compilation, inlining, deoptimisation, safepoints) and garbage collection (first principles, metrics, HotSpot's collectors, GC logs, heap sizing), with links such as laziness everywhere and the JIT betting on profiles.

The links worth remembering:

  • Everything is lazy. Classes load on first use, symbolic references resolve on first use, methods compile once they're hot. Startup cost and the first requests' latency come from that laziness.
  • The JIT bets on what it has seen. Inlining, devirtualisation and escape analysis rest on profiles; deoptimisation undoes a bet that stops paying.
  • A JVM's lifetime is about threads, not main. It ends when the last non-daemon thread ends or something calls exit/halt; shutdown hooks run in between.

Explain it differently

1. The JVM is a kitchen that learns its regulars. The first order of a dish is cooked slowly from the recipe (interpreted). After a few dozen, the cook keeps a quick version ready (C1). After thousands, a head chef rewrites the recipe for exactly how this restaurant orders it (C2). If a regular suddenly asks for something new, the specialised recipe is thrown away (deoptimisation).

2. The constant pool is a class's phone book. A class file doesn't contain other classes; it contains names: "call java/time/Instant.now()". The JVM looks each number up the first time it's dialled (lazy resolution). Reading the phone book tells you everyone a class might call, without running it (Gaps 3).

3. A non-daemon thread is the last cook who keeps the restaurant open. The restaurant closes when every non-daemon cook has gone home, not when the manager (main) leaves. A background cook who never leaves keeps the lights on forever (Gaps 1).

4. A constructor that throws is a delivery left half unpacked. Nobody signed for it, so nobody will put it away. Whatever the constructor opened (files, locks, sockets) stays open unless the constructor closes it on its way out (Gaps 2).

5. Garbage collection is clearing tables. A young collection clears the tables of guests who left within minutes (most objects die young); an old collection deals with the long-stayers, and costs more.

6. A safepoint is "everybody freeze" in a kitchen. Some jobs (collecting, deoptimising) need every cook to stop at a known point. A cook in the middle of a long, uninterruptible task delays everyone.

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from OpenJDK 21.0.12 and the build's stage 41 (exp/41), unless stated.

1. "The program ends when main returns" is true only without non-daemon threads. The chapter's "life of a Java program" ends with main returning or System.exit. The JVM actually waits for the last non-daemon thread (DestroyJavaVM). TiffinBox's order log starts a non-daemon writer thread, and the server is created after the log. With the port already taken:

Terminal
Exception in thread "main" java.net.BindException: Address already in use
	at java.base/sun.nio.ch.Net.bind0(Native Method)
	at java.base/sun.nio.ch.Net.bind(Net.java:577)
(still running after 20 s; stopped by timeout, exit code 124)

main died; the writer thread didn't, so the process stayed up, holding the log's lock, serving nothing. A supervisor (systemd, Kubernetes) sees a running process and never restarts it. After stage 41 the entry point closes what it opened and exits with a code a supervisor can act on:

Terminal
refusing to start: port 18994 is in use (Address already in use). Stop the other process or choose another port.
exit 75 after 0 s

Two more facts from the same corner: an uncaught exception that does end the JVM exits with status 1 (indistinguishable from any other failure), and a shutdown hook that calls System.exit hangs the JVM (Code walkthrough).

2. A constructor that throws leaves what it opened open. The chapter covers object layout and GC, not resource ownership. OrderLog's constructor took a file lock and opened two files, then read the log. A record whose checksum is valid but whose idempotency key isn't a key (written by an older bug, or by hand) made the reading throw:

Terminal
wrote 314 bytes: 3 good records and one with a 6-character key
open #1: java.lang.IllegalArgumentException: not a 128-bit hex key: 6f1c2a
open #2: java.nio.channels.OverlappingFileLockException: null
file descriptors still open on the log directory: 3

There's no object to close() (the constructor never returned), and no destructor: the channels close only if the garbage collector ever runs their cleaners. The second attempt in the same JVM failed with an error about locks, hiding the real one. After the fix (release in a finally when construction fails, and a LogDamagedException naming the record):

Terminal
open #1: in.tiffinbox.core.LogDamagedException: /tmp/w/c2/orders.log: record 4 at byte 255 can't be read: its checksum is valid, but idempotency-key(1) holds not a 128-bit hex key: 6f1c2a. The bytes are what was written: a bug wrote them or the file was edited
open #2: in.tiffinbox.core.LogDamagedException: /tmp/w/c2/orders.log: record 4 at byte 255 can't be read: …
file descriptors still open on the log directory: 0

3. Source-level checks see calls; class files also see references. The chapter shows bytecode with javap. Stage 38's compiler rule bans reading the wall clock, and checks method calls. A method reference slipped past:

Terminal
== javac -Werror with LangLint (stage 38 rules)
exit 0, no warnings
== java tools/ClassScan.java sneaky.jar
CLOCK     Sneaky calls java/time/Instant.now()Ljava/time/Instant;
CLOCK     Sneaky calls java/lang/System.currentTimeMillis()J
1 classes; class file versions {65=1}; 2 problems

Supplier<Instant> clock = Instant::now compiles to a constant-pool Methodref (behind a method handle for invokedynamic), so a 100-line class file reader (tools/ClassScan.java, no libraries) found both. LangLint now checks member references too. Reading the constant pool has a limit worth knowing: it lists what a class names, not what runs. Scanning the 152 JDK classes TiffinBox's code names:

Terminal
152 JDK classes named by our code; 4 of them read the wall clock themselves:
  java/time/Clock: java/time/Clock.system, java/lang/System.currentTimeMillis
  java/time/LocalTime: java/time/Clock.systemDefaultZone, java/time/Clock.system
  java/time/ZonedDateTime: java/time/Clock.systemDefaultZone, java/time/Clock.system
  java/util/concurrent/ThreadLocalRandom: java/lang/System.currentTimeMillis

LocalTime reads the clock only in its now() methods, which TiffinBox never calls; ThreadLocalRandom uses it once, to seed. Reachability needs a call graph, not a phone book.

4. A service is ready long before it's fast. The chapter's lab times a loop through the tiers. For TiffinBox's menu page, rendered in-process, request by request from a cold JVM:

Terminal
default                            #1       19596.5 µs #2        1065.9 µs #10        768.1 µs #100       273.0 µs #1000      101.8 µs #10000      39.1 µs #30000      14.4 µs
-XX:TieredStopAtLevel=1            #1       12488.0 µs #2         892.5 µs #10        604.6 µs #100       137.5 µs #1000       53.3 µs #10000      26.8 µs #30000      35.9 µs
-Xint                              #1       26222.8 µs #2        2001.4 µs #10       1793.2 µs #100      1688.5 µs #1000     1703.3 µs #10000    1764.6 µs #30000    1743.9 µs

The first request costs 1,400 times the 30,000th (most of it class loading and linking: the interpreter alone settles at 1.7 ms). It takes about 10,000 requests to get within 3× of steady state. C1 alone is faster to warm up and settles 2.5× slower than C2. A health check that says "ready" when the port opens sends real traffic to the slow version; after a deploy, the first users pay. Warm-up requests, CDS/AOT caches (chapter 39's lab) and gradual traffic shifting are the remedies.

Common misconceptions

Misconception What's actually true Where it's shown
"When main throws, the program exits." Not while a non-daemon thread runs. Gaps 1; stage 41
"The GC will close what a failed constructor opened." Maybe, someday; locks and descriptors stay until then. Gaps 2
"Checking source catches every call." Method references and code without source need the class files. Gaps 3
"A class's constant pool shows what it calls at run time." It shows what it names. Gaps 3
"Ready means fast." The first requests run interpreted and load classes. Gaps 4
"A shutdown hook can report failure with System.exit." That hangs the JVM; use halt. Code walkthrough
"Changing a library constant updates its users." Constants are inlined at compile time. Exercises T3

Theoretical gaps: the ideas behind the chapter

1. Lazy linking. The JVM specification (§5.4) lets an implementation resolve symbolic references lazily, at first use, or eagerly; HotSpot is lazy. It's why NoClassDefFoundError can appear deep into a run, and why startup work spreads into the first requests.

2. Adaptive optimisation. Self (Hölzle and Ungar, 1994) introduced profiling a running program and recompiling hot code with type feedback, and deoptimising when assumptions fail; HotSpot (1999) descends from it. The trade-off is the warm-up curve in Gaps 4.

3. Resource acquisition and release. C++'s RAII ties a resource's release to an object's destruction. Java has no destructors; try-with-resources and finally are the tools, and a constructor must release what it acquired before it throws, because there's no object yet to close.

4. Process lifecycle contracts. Exit codes are the interface between a program and its supervisor. sysexits.h (BSD) names a few (65 data error, 69 unavailable, 75 temporary failure); 128+N means killed by signal N (137 = SIGKILL). A service that hangs instead of exiting breaks the contract silently.

5. Static analysis on bytecode. Tools such as SpotBugs, ArchUnit and jdeps analyse class files rather than source: they see what the compiler produced, including generated code and dependencies, at the cost of losing comments and some structure.

Applying it

Code walkthrough

Gaps 1 and the shutdown-hook trap come from how the JVM shuts down. From openjdk/jdk21u, src/java.base/share/classes/java/lang/Shutdown.java.

Two ways in: exit and the last thread

Java
    static void exit(int status) {
        logRuntimeExit(status);         // Log without holding the lock;
        synchronized (Shutdown.class) {
            /* Synchronize on the class object, causing any other thread
             * that attempts to initiate shutdown to stall indefinitely
             */
            beforeHalt();
            runHooks();
            halt(status);
        }
    }
Java
    /* Invoked by the JNI DestroyJavaVM procedure when the last non-daemon
     * thread has finished.  Unlike the exit method, this method does not
     * actually halt the VM.
     */
    static void shutdown() {
        synchronized (Shutdown.class) {
            runHooks();
        }
    }

System.exit (through Runtime.exit) takes the lock on Shutdown.class, runs the hooks and halts. The other way in is shutdown(), which the launcher calls only when the last non-daemon thread has finished. That is why Gaps 1's server never shut down: main had ended, but the log writer was a non-daemon thread, so DestroyJavaVM kept waiting.

Running the hooks

Java
    private static void runHooks() {
        synchronized (lock) {
            /* Guard against the possibility of a daemon thread invoking exit
             * after DestroyJavaVM initiates the shutdown sequence
             */
            if (VM.isShutdown()) return;
        }
        for (int i=0; i < MAX_SYSTEM_HOOKS; i++) {
            try {
                Runnable hook;
                synchronized (lock) {
                    // acquire the lock to make sure the hook registered during
                    // shutdown is visible here.
                    currentRunningHook = i;
                    hook = hooks[i];
                }
                if (hook != null) hook.run();
            } catch (Throwable t) {
                // ignore
            }
        }
        // set shutdown state
        VM.shutdown();
    }

System hooks occupy fixed slots; slot 1 starts every application hook (Runtime.addShutdownHook) on its own thread and waits for them all. Any exception from a hook is ignored.

Halting

Java
    static void halt(int status) {
        synchronized (haltLock) {
            halt0(status);
        }
    }

halt stops the process without running hooks. Runtime.halt calls it directly, which is the escape hatch when a hook itself needs to end the process.

Debugging drills

D1. A service that's "running" but never answers

After a host reboot, a service's process is up (systemd says active (running)), but nothing answers on its port. Its log has one stack trace from main at startup, a BindException.

D2. "OverlappingFileLockException" on retry

An integration test opens an embedded store on a directory with a corrupt file and expects a failure. It then repairs the file and opens the same directory again, in the same test, and gets OverlappingFileLockException.

D3. A banned API that still shows up in production

A team bans System.currentTimeMillis() with an Error Prone check, but a production profile shows calls to it from their code.

D4. Every deploy causes a latency spike

Each deploy produces a two-minute p99 spike to 800 ms, from 40 ms, though the new instances pass health checks within 10 s.

Career-oriented

Interview prep

Mid-level 1: what java -jar does

Question. "What happens between typing java -jar app.jar and the first line of main running?"

How to get there. Launcher, VM, class loading, linking, initialisation.

Mid-level 2: daemon threads

Question. "What's a daemon thread, and when would you make a thread one?"

How to get there. JVM exit rules, then what each choice risks.

Senior 1: startup failure behaviour

Question. "Design how a service should behave when it can't start: port taken, config invalid, database unreachable, data on disk damaged."

How to get there. Fail fast or wait, what to say, how to exit.

Senior 2: checking compiled code

Question. "Our architecture rules (no clock reads in the domain, no java.net in the core) are checked in code review. How would you automate them?"

How to get there. Source rules, bytecode rules, where each runs.

Staff 1: cold starts across a fleet

Question. "Our autoscaling adds instances under load, and new instances make latency worse for two minutes. What would you change?"

How to get there. Measure, reduce startup and warm-up, change how traffic arrives.

Staff 2: what "the JVM did it" incidents teach

Question. "Several incidents were blamed on 'the JVM': a hang on shutdown, a process that wouldn't exit, a long pause. How do you turn these into engineering standards?"

How to get there. Find the mechanism behind each, then the rule and the test.