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

Workbench / Volume 3 Exercises: The Backend

V3·40

JVM Internals

Exercises for Volume 3, chapter 40: the spectrum of runtimes and the life of a Java program; bytecode and the stack machine; class loading, class loaders and verification; runtime data areas and object layout; the interpreter, tiered JIT compilation, inlining, deoptimisation and safepoints; garbage collection from first principles, the metrics that matter, HotSpot's collectors, GC logs and heap sizing; and other runtimes (Go, Python, .NET, V8). 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~15 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

The exercises follow the same four sets and the same locking as before. Code is Java 21, with Go and Python for comparison. Every quoted output was measured, and five of them catch experienced developers:

  • P2. Config.class, new Config[3] and the constant Config.CONST did not run Config's static initialiser. Reading the non-constant Config.live did.
  • P2. A failing static initialiser gave ExceptionInInitializerError the first time, then NoClassDefFoundError: Could not initialize class C$Broken on every later access.
  • P3. The same class file loaded by two class loaders produced two different classes. Casting gave "Cannot cast B to B".
  • P4. 10 million short-lived records allocated 0 bytes after warm-up, because escape analysis removed the allocations. With -XX:-DoEscapeAnalysis, the same loop allocated 240,000,000 bytes.
  • P5. PrintCompilation showed D::total compiled at tier 4 and then "made not entrant" the moment a second shape type appeared, followed by recompilation.

The chapter's lab results are the starting point. The exercises build on them rather than repeat them:

  • tiered compilation warm-up: 8.1 ms down to 0.9 ms, against -Xint at 32 ms;
  • monomorphic, bimorphic and megamorphic call sites: 1.69, 6.99 and 15.42 ms;
  • four collectors on one workload: Serial max pause 43.92 ms, ZGC 0.06 ms.

Coverage map.

Chapter component Exercises
spectrum of runtimes; life of a program T1
bytecode; stack machine; invokedynamic T2, P1
class loading; initialisation; loaders; verification T3, P2, P3
runtime data areas; object layout T4, P6
interpreter; tiered compilation T5, P5
inlining; escape analysis T5, P4
deoptimisation; safepoints T6, P5
GC first principles; metrics T7, P7
HotSpot collectors; reading GC logs; heap sizing T8, P7, P8
GC and runtimes in other languages T9, P9

Theory

T1. The spectrum of runtimes and the life of a Java program

  1. Place C, Rust, Go, Java, C#, JavaScript (V8), Python (CPython) and Erlang (BEAM) on a spectrum from "no runtime" to "full VM". For each, say what its runtime provides: memory management, scheduling, JIT, reflection and dynamic loading. Then say what each costs in startup time, memory, peak performance and predictability.
  2. Trace the life of a TiffinBox JVM process from java -jar app.jar to its first request: - launcher and VM creation; - CDS archive mapping (P2 saw 452 of 455 classes for hello world come from the shared archive); - loading the main class and its dependencies lazily; - Spring's classpath scanning; - interpreted execution; - tiered JIT compilation as the code gets hot; - GC cycles; - the shutdown hooks.

Where does startup time go, and where does warm-up time go? 3. Why does "Java is slow" persist as a belief, and what is true about it? Cover startup, warm-up, memory footprint and peak throughput, comparing the lab's results with Go and Rust.

T2. Bytecode and the stack machine

  1. P1 disassembled four small methods: - i++; return i became iinc 0, 1; iload_0; ireturn; - dish + " x" + qty became invokedynamic makeConcatWithConstants; - () -> s.toUpperCase() became an invokedynamic producing a Supplier, plus a private synthetic method lambda$sup$0; - the constructor became aload_0; invokespecial Object."<init>".

Explain each, and the operand stack and local variable slots. 2. Explain the five invoke instructions (invokestatic, invokespecial, invokevirtual, invokeinterface, invokedynamic) and why invokedynamic (JDK 7) made lambdas, string concatenation and records' toString/equals both flexible and fast. 3. Why does bytecode matter to a backend engineer? Consider reading javap to settle "what does this compile to", understanding stack traces (lambda$…, $$SpringCGLIB$$), bytecode-generating libraries (ByteBuddy, Spring proxies, Hibernate enhancement), and agents (APM, JFR).

T3. Class loading, initialisation, loaders and verification

  1. Describe the class lifecycle: loading, then linking (verification, preparation, resolution), then initialisation. P2 showed that Config.class, new Config[3] and the compile-time constant Config.CONST did not trigger initialisation, while reading Config.live did. List the JLS initialisation triggers, and explain why constants don't trigger it (they're inlined into the caller's class at compile time).
  2. P2: a static initialiser that threw gave ExceptionInInitializerError with the real cause once, then NoClassDefFoundError: Could not initialize class C$Broken forever after. Why is this a production debugging trap, and how do you design static initialisation to avoid it?
  3. Class loaders. Cover the bootstrap, platform and application loaders, parent delegation, child-first loaders in application servers and plugin systems, and how class identity is (loader, name). P3: two URLClassLoaders loaded the same B.class into different classes, and cast failed with "Cannot cast B to B". Explain class-loader leaks (metaspace OOM on redeploy; P6) and verification (what the verifier checks and why -Xverify:none was removed).

T4. Runtime data areas and object layout

  1. Describe the runtime data areas: - per JVM: the heap (young and old generations), metaspace (class metadata), the code cache (JIT output), and native memory (thread stacks, GC structures, direct buffers); - per thread: the JVM stack (frames), the program counter, and the native method stack.

Which OutOfMemoryError message corresponds to each? P6 produced Java heap space and Metaspace. Name the others: unable to create native thread, Direct buffer memory, GC overhead limit exceeded, Requested array size exceeds VM limit. 2. Object layout: - the header (mark word plus class pointer, 12 bytes with compressed class pointers, 8 with compact headers: ch39's lab); - fields reordered by size; - 8-byte alignment; - arrays with a length field; - compressed oops (32-bit references for heaps under ~32 GB).

Why does a heap of 31 GB sometimes beat one of 33 GB? 3. How does a container's memory limit relate to all of these? Cover heap plus metaspace plus code cache plus thread stacks plus direct memory plus GC overhead, why a container with -Xmx equal to its limit gets OOM-killed, and the Native Memory Tracking tool (-XX:NativeMemoryTracking=summary, jcmd VM.native_memory).

T5. Interpreter, tiered compilation, inlining and escape analysis

  1. Explain tiered compilation: - tier 0, the interpreter, which collects profiles; - tier 3, C1 with full profiling; - tier 4, C2 using those profiles; - plus tiers 1 and 2 for special cases.

P5's log showed D::total at tier 3 and then 4, OSR compilation (%, on-stack replacement of a running loop), and earlier tier-3 versions "made not entrant". Relate it to the lab (8.1 ms down to 0.9 ms; -Xint at 32 ms; C1 only flat at 1.6 ms). 2. Inlining copies a callee's body into its caller. Why is it "the mother of all optimisations"? What does it unlock (constant folding, escape analysis, loop optimisations), and what are its limits (MaxInlineSize of 35 bytecode bytes, the hotness thresholds, megamorphic sites: the lab's 15.42 ms)? 3. Escape analysis. P4: 10 million new P(i, i + 1) allocated 0 bytes after warm-up, because C2 proved that no P escaped the loop and replaced it with scalars. With -XX:-DoEscapeAnalysis it allocated 240,000,000 bytes, exactly 10M × 24. When does escape analysis fail (objects stored in fields, passed to non-inlined methods, merged control flow), and what does this mean for "avoid allocation" folklore?

T6. Deoptimisation and safepoints

  1. Deoptimisation. C2 compiles speculatively: "this call site only ever sees Sq", "this branch is never taken". When a speculation fails, the compiled code is invalidated ("made not entrant": P5 after circles arrived), the running frame is converted back to interpreter state, and the method is recompiled with new profiles. List the triggers (a new receiver type, an uncommon trap on a branch, class loading that invalidates class-hierarchy assumptions, null checks) and explain why a benchmark can suddenly slow down mid-run.
  2. Safepoints. Explain why the JVM sometimes needs all threads stopped (some GC phases, deoptimisation, biased-lock revocation historically, thread dumps, class redefinition). What is time-to-safepoint, and why can long counted loops without safepoint polls delay a pause (JDK 10's loop strip mining)? How do you see it (-Xlog:safepoint, JFR)?
  3. What do these mechanisms mean for backend practice? Consider warm-up before benchmarks and before production traffic, stable type profiles in hot paths, avoiding "benchmark first with one type, then production with many", and reading jstack dumps knowing that they bring threads to a safepoint.

T7. Garbage collection from first principles

  1. Explain reachability from GC roots (thread stacks, static fields, JNI references) against reference counting. P9: in Python, a two-object cycle stayed alive after del under reference counting alone, until gc.collect() found it (9 objects, including dictionaries) and freed it. Explain why tracing collectors don't have this problem.
  2. Explain the basic algorithms: - mark-sweep (fragmentation); - mark-compact (moves objects); - copying (fast for mostly dead young objects; needs to-space); - generational hypothesis (most objects die young); - write barriers and remembered sets; - concurrent marking (tri-colour invariant, SATB); - concurrent relocation (load barriers in ZGC).
  3. The metrics that matter: throughput (the percentage of time not spent in GC), latency (pause time distribution: max, p99), footprint (heap size needed) and allocation rate. The lab's four collectors traded these off. Explain why you can usually optimise two of the three, and which ones matter for a TiffinBox API and for a nightly batch job.

T8. HotSpot's collectors, GC logs and heap sizing

  1. Compare Serial, Parallel, G1, ZGC (generational since 21, the only mode since 24: ch39's P6) and Shenandoah: - the algorithm; - pause behaviour (the lab's max pauses: 43.92, 20.18, 7.08 and 0.06 ms); - CPU overhead; - heap-size sweet spot; - the default selection (G1 unless the machine is small: P8 reported G1 with a default maximum heap of 1,496 MB on this machine, about a quarter of RAM).
  2. Read a GC log. P6's 64 MB heap showed lines like GC(2) Pause Young (Prepare Mixed) (G1 Humongous Allocation) 55M->55M(64M) 0.470ms and GC(3) Pause Full (G1 Compaction Pause) 55M->55M(64M) 3.118ms. Decode each field: - the event number; - the pause type and its cause; - before → after (committed); - the duration.

What do "Humongous Allocation" and back-to-back Full GCs with no reclaimed memory tell you? 3. Heap sizing: -Xms/-Xmx against MaxRAMPercentage in containers, setting the initial heap equal to the maximum for servers, the live-set rule of thumb (a heap of about 3–4× the live data after a full GC for G1), MaxGCPauseMillis, and when to tune at all. Write a sizing procedure for a TiffinBox service.

T9. GC and execution in other runtimes

  1. Compare GC designs: - Go: a concurrent, non-moving, non-generational mark-sweep tuned for low latency, with GOGC (default 100: a collection when the heap grows 100% over the live set) and GOMEMLIMIT. P9 ran 8 GC cycles with 0.57 ms of total pause for 2 million small allocations. - .NET: generational, server versus workstation, background GC. - V8: generational, with Orinoco's parallel and concurrent phases. - CPython: reference counting plus a cycle collector (P9). - Rust: no GC; ownership, with Rc/Arc for shared ownership. - Erlang: per-process heaps, so GC never stops other processes.
  2. Execution strategies: the Go and Rust compilers (AOT), .NET's RyuJIT with tiered compilation and ReadyToRun, V8's tiers, PyPy's tracing JIT against CPython's interpreter (and 3.13's experimental JIT), and GraalVM (Truffle, native-image). What does AOT lose compared with a profile-guided JIT, and what does it gain?
  3. For a polyglot TiffinBox (Java services, a Go notification worker, Python ML scoring, Node BFF), write the "runtime cheat sheet" an on-call engineer needs: the memory limit setting, GC tuning knobs, how to get a profile, and the common OOM signatures for each.

Programming exercises

P1. Reading bytecode

Disassemble with javap -c -p: - i++; - string concatenation; - a capturing lambda; - a constructor; - an enhanced for over a List (iterator calls); - autoboxing in List<Integer>.add(1) (Integer.valueOf); - a switch on a string (hashCode and lookupswitch); - a record's toString (ObjectMethods bootstrap).

For each, explain one surprise.

P2. Class initialisation triggers and failures

Show: - which accesses initialise a class and which don't (.class, an array, a constant, a non-constant static, Class.forName(name, false, loader)); - a failing static initialiser producing ExceptionInInitializerError, then NoClassDefFoundError; - the constant-inlining trap: change a library constant, recompile only the library, and see the old value in the caller.

Then rewrite a "config loaded in a static block" class as a lazily initialised, dependency-injected bean.

P3. Class-loader identity and leaks

Load the same class with two isolated URLClassLoaders. Show: - == is false; - isInstance is false; - casting fails with "Cannot cast B to B".

Then simulate a class-loader leak: 1. Create loaders in a loop. 2. Keep one object from each in a static list. 3. Cap metaspace, and observe OutOfMemoryError: Metaspace. 4. Remove the references, close the loaders, and show metaspace usage dropping after GC.

P4. Escape analysis and allocation

Measure the bytes allocated for 10 million short-lived records in a loop, using ThreadMXBean.getThreadAllocatedBytes, after warm-up and with and without -XX:-DoEscapeAnalysis. Then make the record escape in three ways (store it in a static field, add it to a list, pass it to a method marked @DontInline or simply a large method) and measure each. Finally, compare the boxed Stream<Integer> from ch37's lab.

P5. JIT compilation and deoptimisation

Run a hot method over an array of one type, then switch to a mix of two types, with -XX:+PrintCompilation. Identify: - tier 3 and tier 4 compilations; - OSR compilations (%); - "made not entrant" after the switch; - the recompilation.

Then measure the per-call time before, during and after, and repeat with JMH using separate forks.

P6. Out-of-memory errors and where memory lives

Produce, in separate runs: - Java heap space (a list of 8 MB arrays in a 64 MB heap, with the GC log); - Metaspace (class loaders); - StackOverflowError (ch37); - optionally Direct buffer memory (allocateDirect with -XX:MaxDirectMemorySize=16m).

Then run a Spring-sized app (or any app) with -XX:NativeMemoryTracking=summary, read jcmd <pid> VM.native_memory summary, and build the memory budget for a 1 GB container.

P7. GC logs and collector comparison

Run an allocation-heavy service simulation (request-scoped objects plus a growing cache of 200 MB) for 60 s with G1, Parallel and ZGC, each with -Xlog:gc*:file=gc-%p.log. Parse the logs: - pause count; - pause p50, p99 and max; - total pause time; - heap after GC.

Compute GC CPU overhead from the -Xlog:gc+cpu lines, and write a one-paragraph recommendation.

P8. Inspect a running JVM

On a running process, use: - jcmd <pid> help; - VM.flags; - VM.system_properties; - GC.heap_info; - Thread.print; - GC.class_histogram; - Compiler.codecache; - VM.native_memory; - JFR.start, then JFR.dump.

Also read the defaults from ManagementFactory (loaded classes, max heap, collector names). Write an on-call runbook entry: "JVM is slow or using memory — first five commands".

P9. GC in Python and Go

In Python, create a reference cycle, delete the references, and show that it survives until gc.collect(). Then use weakref to break cycles. In Go, allocate 2 million small structs and read runtime.MemStats: the GC count and the total pause. Then: - set GOGC=50 and GOGC=400 and compare; - set GOMEMLIMIT and observe the GC frequency; - run GODEBUG=gctrace=1.

Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–40)

C1. A JVM health dashboard and runbook for TiffinBox

Expose JVM metrics from the order service: - heap used and committed per pool; - GC pause histograms and count by cause; - allocation rate; - metaspace; - code cache; - thread counts (platform and virtual); - class-loading counts; - safepoint time.

Get them through Micrometer or ManagementFactory and JFR streaming, and build a dashboard with alert rules. Then run three failure drills: - a memory leak; - a class-loader leak on redeploy (with DevTools-style restarts); - a humongous-allocation storm from 10 MB JSON payloads.

Diagnose each one using the dashboard and the runbook.

Combines: Volume 1's operating system memory concepts, Volume 2's frontend observability (ch32), ch35's memory per entry, ch38's thread diagnostics, and this chapter.

C2. Startup and warm-up optimisation

Measure the TiffinBox service's time to first request and to steady p99: - the baseline; - with an AOT cache (ch39); - with class-loading trimming (lazy beans, fewer starters); - with a warm-up phase that drives synthetic requests before readiness turns green; - optionally with a GraalVM native image.

Report the startup time, the first-minute p99, steady-state throughput and memory for each.

Combines: Volume 2's deployment and readiness concepts (ch31), ch39's runtime evolution, ch47's Spring Boot (ahead), and this chapter.

C3. A polyglot runtime comparison for the same service

Implement a small "menu lookup" service (an in-memory map of 100,000 dishes, JSON over HTTP) in Java, Go, Node and Python. Load-test each at the same rate and compare: - startup; - RSS; - p50 and p99 latency; - GC pauses (each runtime's own tool); - CPU per request.

Explain each difference using this chapter's concepts.

Combines: Volume 2's Node knowledge, ch33's language comparison, ch35's memory per entry, and this chapter's runtimes.

What the chapter leaves out

Java agents and instrumentation

-javaagent JARs use java.lang.instrument to transform classes as they load. That's how OpenTelemetry, APM tools and some profilers work. They affect startup time, can conflict with each other, and see every class. JDK 21 warns about dynamically loaded agents (JEP 451), and future releases may disallow them by default. Know which agents run in production and their overhead.

JIT compiler alternatives: Graal JIT and C2's future

The Graal compiler (written in Java) can replace C2 in GraalVM distributions. It's better at some optimisations, such as partial escape analysis and inlining through lambdas. Oracle GraalVM and the JDK's JVMCI make this pluggable. For most services C2 is fine, but Graal JIT is worth benchmarking for stream- or lambda-heavy code.

Memory analysis tools

Heap dumps (jcmd GC.heap_dump, -XX:+HeapDumpOnOutOfMemoryError) analysed in Eclipse MAT or VisualVM show retained sizes, dominator trees and paths to GC roots. They're the standard way to find leaks. JFR's Old Object Sample event finds leak candidates with low overhead in production. Learn MAT's "Leak Suspects" report and dominator tree before you need them in an incident (ch41).

Off-heap and direct memory

Netty, Kafka clients, gRPC and file-mapped I/O use direct buffers and native memory outside the Java heap. These are governed by -XX:MaxDirectMemorySize and counted by NMT. Leaks there show up as container OOM kills with a healthy-looking heap. Netty's leak detector (-Dio.netty.leakDetection.level) and NMT diagnose them.

Reference types: soft, weak, phantom and Cleaner

WeakReference (collected when only weakly reachable; used in WeakHashMap and caches keyed by objects), SoftReference (cleared under memory pressure; an unpredictable cache policy, so prefer size-bounded caches), PhantomReference and Cleaner (cleanup after an object becomes unreachable, the replacement for finalization). They interact with GC timing, and relying on them for important cleanup is fragile. Use try-with-resources first.

Senior exercises

S1. Write the JVM configuration standard for the platform

Write the standard launch configuration and policy for TiffinBox services: - JDK version; - heap via MaxRAMPercentage; - GC choice and when to deviate; - GC logging; - heap dumps on OOM; - ExitOnOutOfMemoryError; - NMT in staging; - JFR continuous recording; - the flags that are forbidden.

Give each setting's reason and its evidence from this chapter.

S2. Review a "performance fix" pull request

A PR claims "30% faster". It: - adds -XX:+UseParallelGC to the API service; - sets -Xmx to the container limit (4 GB of 4 GB); - adds -XX:-TieredCompilation; - replaces records with mutable reused objects "to avoid allocation"; - includes a benchmark that loops 1,000 times in main with System.nanoTime.

Write the review.

S3. Diagnose a latency regression after a deploy

After a deploy, the order service's p99 rose from 120 ms to 400 ms during the first 10 minutes after each instance starts, and then recovered. CPU is high during that window. The deploy added an OpenTelemetry Java agent and a new pricing module with a 4-implementation interface on the hot path. Write the investigation plan and the likely causes, the experiments to confirm them, and the fixes.

S4. Teach the JVM's three jobs with five outputs

Prepare a 20-minute talk using five outputs: - P2's lazy class initialisation; - the lab's tiered warm-up (8.1 → 0.9 ms against -Xint at 32 ms); - P4's escape analysis (0 bytes against 240 MB); - P5's deoptimisation log; - the lab's four collectors' pause times.

Frame it as "loading, compiling, collecting", with one practical rule per output.

S5. Plan a migration from Parallel GC and 32 GB heaps to a modern setup

A legacy reporting API runs on JDK 11 with Parallel GC and a 34 GB heap, has 2-second GC pauses during business hours, and customers complain about timeouts. Plan the move to JDK 25. Cover the heap sizing (compressed oops), collector choice (G1 against ZGC), measurement, code changes that reduce the live set, rollout and success criteria.