▚ The Software Engineer's Field Manual
Engineering track · E2 · Senior primer + drill

Java Deep Dive — Internals for the Nine-Year Engineer

"You have shipped Java for nine years. The staff round does not ask what a HashMap is. It asks why your service got slower after the JDK upgrade, what the 800 ms pause really was, and whether the virtual-thread migration you are proposing will stall under load. This chapter is the machine underneath your code, explained in plain words."

150 questions · answers collapsed For: senior/staff Java rounds Heavy on: JVM internals · memory model · GC · virtual threads

01 · Why this chapter existsThe Questions That Separate "Knows Java" From "Owns the JVM"

This chapter is about the machine your Java runs on, not the language. It covers what happens between your .java file and the instructions the CPU executes, and what the runtime does to your memory while your code is running.

Here is a real senior-round opener. "Your service was upgraded from JDK 17 to JDK 25 last night. CPU is pinned at 100 percent and throughput is down 30 percent. Nothing in the application changed. Go."

A candidate who knows the language well, but not the machine underneath it, will talk about thread pools and database connections.

A candidate who owns the JVM does something different. They ask for the compiler log. They check whether the just-in-time compiler is stuck in a loop of throwing away and re-compiling code. They look at which garbage collector the new JDK picked by default. They have the answer inside ten minutes.

Picture it: the opening diagnosis, in order

What you see: the same symptom (CPU 100 percent, throughput down 30 percent) has three different roots, and each leaves different evidence.

Symptom to root cause to first action.
SymptomLikely root causeEvidence to ask forFirst action
CPU 100 percent, throughput down, compiler threads busyThe JIT keeps discarding and recompiling the same method (a deoptimisation storm)-XX:+PrintCompilation shows the same method made not entrant every few secondsFind the call site whose types or branches keep changing
CPU high, long pauses in the GC logA different collector or different heap sizing is now in effect-Xlog:gc lines, and jcmd <pid> VM.flags for the collector actually chosenCompare flags and pause times between the two JDKs
CPU high, threads waiting on each otherContention or pinning, not the JVM machineryThread dump (Chapter E3 covers reading one)Follow the lock owner

The difference is not intelligence. It is whether anyone ever explained, in plain words, what happens between your .java file and the instructions the CPU executes.

That is what this chapter does. It assumes the language itself, which Chapter E1 teaches from zero.

It also deliberately avoids repeating what Chapter E3 drills across three hundred questions: equals and hashCode, collection internals, the monitor and synchronized, thread dumps, pool sizing arithmetic, the catalogue of OutOfMemoryError flavours. When one of those comes up here, you get a link, not a repeat.

What this chapter adds is depth and width. Six things, one per primer section:

The page has two halves.

The primer (sections 02–07) is six chapters, each built the same way: a concrete hook, the mechanism in plain words, a diagram, one complete program you can run with a single java Foo.java command on JDK 21 or newer, a paragraph that reads the program's output line by line, and a Brain Power question to answer before you look.

The drill (sections 08–11) is 150 questions in three kinds: knowledge questions that ask "why", production scenarios you answer in diagnosis order, and design prompts where you state assumptions, propose, and defend.

Every answer is collapsed. Say yours aloud first, then reveal, then read the likely follow-ups — because the follow-up is where senior rounds are decided.

Versions, as of August 2026. JDK 21 and JDK 25 are the two long-term-support releases you will meet in production. JDK 26 shipped in March 2026. JDK 27 is in release-candidate state, with general availability scheduled for 15 September 2026.

Every program on this page runs on JDK 21 unless it says otherwise. Every claim about a newer feature carries the JDK number and the JEP — the JDK Enhancement Proposal, which is the numbered design document each feature ships under.

Where a feature is still in preview, the page says so. "Is structured concurrency final yet?" is itself a question interviewers ask, to see whether you keep up.

02 · The primerFrom Source to Machine Code: javac, Class Loading, and the Two JIT Compilers

Java compiles twice. Once before the program runs, into a portable instruction set called bytecode, and again while it runs, turning the hottest bytecode into real machine code. Almost every surprising JVM behaviour lives somewhere in that second step.

Start with a puzzle you may have met. A plugin framework reloads a plugin jar, and immediately the log fills with ClassCastException: com.acme.Plugin cannot be cast to com.acme.Plugin.

Read that again. Same name on both sides of the "cannot be cast". Nobody renamed anything.

The exception is correct. By the end of this chapter you will be able to say exactly why in one sentence: a class in the JVM is identified by its name and the class loader that defined it, and the framework now has two loaders.

That sentence is the doorway into the whole pipeline, from your source file to the instructions the CPU runs. So let us walk that pipeline in order.

Bridge: you know compilers; Java has two of them, at different times

In C or Go, one compiler turns source into machine code before the program runs, and the CPU executes that code directly. Java splits the job in two.

That split buys three things at once. Java starts quickly, because nothing is compiled yet. It runs anywhere, because bytecode is portable. And on long-running services it ends up as fast as compiled languages.

The third one deserves a sentence of its own, because it surprises people. The JIT can beat an ahead-of-time compiler, because it knows things that compiler cannot: which branches are actually taken, which types actually show up, and which methods are actually hot.

The price is a warm-up period — and a whole class of production surprises that live inside it.

What javac produces: bytecode and the constant pool

A .class file has two halves that matter here.

The first is the bytecode for each method: a sequence of one-byte opcodes for a stack machine. iload_1 pushes local variable 1 onto an operand stack. iadd pops two values and pushes their sum. invokevirtual calls a method. There are no registers and no memory addresses anywhere, and that is exactly what makes bytecode portable.

The second is the constant pool — a table of every name, type descriptor, string literal and number the class refers to.

The two work together through one level of indirection. Bytecode never says "call String.length". It says "invoke the method described by constant-pool entry #17", and entry #17 says "class java/lang/String, name length, descriptor ()I".

That indirection is why linking can be lazy. The JVM only chases entry #17 to a real method the first time that instruction actually runs.

You can see all of this yourself with javap -c -v Foo.class. Reading its output is a skill interviewers test directly.

One instruction deserves special mention, because it powers most of modern Java: invokedynamic.

Instead of naming a method, it names a bootstrap method. That bootstrap is called once, the first time the instruction runs, to decide what the call site should do from then on. After that, the decision is cached.

Three everyday features are built on it:

So when you see invokedynamic in javap output, read it as: "the runtime decides how to do this, once, and caches the answer".

Picture it: reading bytecode with javap

The setup: four tiny methods, each one showing a different kind of instruction.

Calc.javaruns offline
class Calc {
    int add(int a, int b) { return a + b; }
    int len(String s)     { return s.length(); }
    String tag(int id)    { return "id=" + id; }
    Runnable job()        { return () -> System.out.println("hi"); }
}

Make the invisible visible: run javac Calc.java and then javap -c -p Calc.class. Slot 0 of an instance method is this, so a is slot 1 and b is slot 2.

javap -c -p Calc.class (trimmed)runs offline
# illustrative output: the #n numbers depend on the class
int add(int, int);
  Code:
     0: iload_1
     1: iload_2
     2: iadd
     3: ireturn

int len(java.lang.String);
  Code:
     0: aload_1
     1: invokevirtual #7      // Method java/lang/String.length:()I
     4: ireturn

java.lang.String tag(int);
  Code:
     0: iload_1
     1: invokedynamic #13,0   // InvokeDynamic #0:makeConcatWithConstants:(I)Ljava/lang/String;
     6: areturn

java.lang.Runnable job();
  Code:
     0: invokedynamic #19,0   // InvokeDynamic #1:run:()Ljava/lang/Runnable;
     5: areturn

The trace: this is add(3, 4) executing on the operand stack, one opcode per row.

operand stack traceruns offline
pc  opcode   locals [this, a, b]   operand stack (top on the right)
 0  iload_1  [Calc, 3, 4]          [3]       ✓ push local 1
 1  iload_2  [Calc, 3, 4]          [3, 4]    ✓ push local 2
 2  iadd     [Calc, 3, 4]          [7]       ✓ pop two, push the sum
 3  ireturn  [Calc, 3, 4]          []        ✓ pop 7 and return it

What you see: the call sites carry a #n index, not a method. javap -c -v prints the table behind it.

constant pool (javap -v, trimmed)runs offline
# illustrative output
   #7 = Methodref        #8.#9      // java/lang/String.length:()I
   #8 = Class            #10        // java/lang/String
   #9 = NameAndType      #11:#12    // length:()I
  #10 = Utf8             java/lang/String
  #11 = Utf8             length
  #12 = Utf8             ()I

Why: bytecode points at table entries, so the JVM can resolve each one lazily the first time the instruction runs. The two invokedynamic rows are the ones where the runtime, not javac, chooses the implementation.

Class loading: load, link, initialise, in that order

Bytecode gets into the JVM through class loaders — ordinary Java objects that turn a class name into a Class object.

Since JDK 9 there are three built-in loaders, arranged in a parent chain:

Loading is parent-first by default. When the application loader is asked for java.lang.String, it asks its parent, which asks the bootstrap loader, which finds it. Only if every parent says "not mine" does the child look in its own jars.

That is why you cannot replace java.lang.String by putting a class of that name on the classpath.

It is also the rule plugin frameworks bend on purpose. They write child-first loaders, so that a plugin can bring its own version of a library — which is exactly how the puzzle at the top of this section happens.

Now the sentence from the puzzle.

The loader that actually calls defineClass for a class is its defining loader. And the JVM identifies a class by the pair: (fully-qualified name, defining loader).

So two loaders that each define com.acme.Plugin — from the very same bytes — produce two different classes. Different Class objects, different static fields, and no cast relationship between them at all.

If the framework kept a reference to an object from the old loader, and now tries to cast it to the type loaded by the new loader, the cast fails. And the message prints the same name twice, because from the JVM's point of view the names were never the distinguishing part.

Picture it: why "Plugin cannot be cast to Plugin"

The setup: a framework defines the same plugin bytes through two loaders, as it does after a hot reload, and then casts an old instance.

PluginReload.javaruns offline
byte[] bytes = compilePlugin();                          // "public class Plugin {}"
Class<?> a = new MemoryLoader(bytes).loadClass("Plugin"); // loader A defines it
Class<?> b = new MemoryLoader(bytes).loadClass("Plugin"); // loader B defines it
Object fromA = a.getDeclaredConstructor().newInstance();
b.cast(fromA);   // ❌ TRAP: same name, same bytes, different defining loader

Make the invisible visible: the JVM keeps one Class object per (name, defining loader) pair.

memory pictureruns offline
 class loaders                          classes the JVM holds
 ------------------------------------   ---------------------------------
 application loader  (parent of both)   JvmTour, java.lang.* ...
        ^                ^
 MemoryLoader A     MemoryLoader B
        |                |
        v                v
   Class Plugin@A    Class Plugin@B     same name, same bytes, two identities

 fromA ---> instance whose class is Plugin@A

The trace: one line per step; the cast compares class identities, not names.

call traceruns offline
1  loader A defines "Plugin"        -> Class Plugin@A                      ✓
2  loader B defines "Plugin"        -> Class Plugin@B (a separate class)   ✓
3  fromA = new Plugin@A()                                                  ✓
4  b.cast(fromA): is Plugin@A the same as, or a subtype of, Plugin@B?      ✗ no
5  throw ClassCastException (both sides print the same name)               ✗

What you see: the exception text names both loaders, which is the whole diagnosis.

consoleruns offline
# illustrative output
same Class object? false   same name? true
ClassCastException: class Plugin cannot be cast to class Plugin (Plugin is in unnamed module of loader JvmTour$MemoryLoader @1b2c3d; Plugin is in unnamed module of loader JvmTour$MemoryLoader @4e5f6a)

Why: a class is identified by its name and its defining loader, so the two Plugin classes are strangers to each other.

The fix: put the shared contract (an interface) in the parent loader and let only the implementation live in the plugin loader. Then the cast is to a type both sides agree on.

Fix.javaruns offline
// api.jar: on the application classpath, defined once by the parent loader
public interface Plugin { String hello(); }

// ✅ FIX: the plugin loader's parent is the application loader, so Plugin resolves to ONE class
URLClassLoader loader = new URLClassLoader(new URL[] { pluginJar }, Plugin.class.getClassLoader());
Plugin p = (Plugin) loader.loadClass("com.acme.MyPlugin").getDeclaredConstructor().newInstance();
System.out.println(p.hello());   // Result: hi

What you see now: the cast succeeds even after a second reload, because both implementations implement the same parent-loaded interface.

consoleruns offline
# illustrative output
hi
reloaded plugin class loader differs from the old one? true   cast to Plugin still succeeds? true

The same rule shows up in a second disguise: LinkageError: loader constraint violation, raised when two loaders disagree about a type that a method signature crosses.

After loading come two more stages. First linking, then initialisation.

Linking has three steps, and they happen in this order:

Then comes initialisation: running the class's static initialiser. That is the method the JVM calls <clinit>, and it contains your static field assignments and static { } blocks, in source order.

The JVM initialises a class only on first active use. That means one of these five things:

Two things notably do not initialise a class: merely loading it, and referring to a compile-time constant in it.

One last detail, because it hides a nasty bug. Initialisation runs under a per-class lock. Two classes whose static initialisers touch each other, started from two threads at once, will deadlock — rarely seen, and very hard to diagnose if you do not know this rule.

Picture it: when <clinit> actually runs

The setup: one class with a compile-time constant and a real static field, and a main that touches them in turn.

InitDemo.javaruns offline
class Config {
    static final int MAX = 10;                 // compile-time constant
    static int count = init();                 // needs <clinit>
    static int init() { System.out.println("Config.<clinit> runs"); return 0; }
}
public class InitDemo {
    public static void main(String[] args) {
        System.out.println(Config.MAX);        // ✓ constant: no initialisation
        System.out.println("before");
        System.out.println(Config.count);      // ❌ TRAP: first active use, <clinit> runs HERE
    }
}

Make the invisible visible: javac copies a constant into the caller, so the first read has no getstatic on Config at all.

javap -c InitDemo.class (trimmed)runs offline
getstatic   #7   // Field java/lang/System.out
bipush      10                 // MAX was copied in: Config is never touched ✓
invokevirtual #13 // println:(I)V
...
getstatic   #31  // Field Config.count:I   <- first active use: <clinit> runs here ✗

The trace: the order of events at runtime.

call traceruns offline
1  println(Config.MAX)      prints 10, Config not even loaded            ✓
2  println("before")        prints before                                ✓
3  getstatic Config.count   Config: load -> link -> initialise
4    Config.<clinit>        runs init(), prints "Config.<clinit> runs"   ✓
5  println(Config.count)    prints 0                                     ✓

What you see: the init message appears after "before", not before it.

consoleruns offline
10
before
Config.<clinit> runs
0

Why: initialisation waits for the first active use, and a constant is not a use.

Picture it: two classes that deadlock in their static initialisers

The setup: A reads B while it initialises, and B reads A, and two threads start from opposite ends.

InitDeadlock.javaruns offline
class A { static int x = B.y + 1; }   // A.<clinit> needs B initialised
class B { static int y = A.x + 1; }   // B.<clinit> needs A initialised
// Thread 1: new Thread(() -> System.out.println(A.x)).start();
// Thread 2: new Thread(() -> System.out.println(B.y)).start();   // ❌ TRAP: opposite order

The trace: a time-ordered table of the two threads and the per-class initialisation locks.

thread interleavingruns offline
step  Thread 1                                   Thread 2
1     first use of A: takes A's init lock  ✓
2                                                first use of B: takes B's init lock  ✓
3     A.<clinit> reads B.y: B is being
      initialised by Thread 2, so wait     ✗
4                                                B.<clinit> reads A.x: A is being
                                                 initialised by Thread 1, so wait     ✗
5     both wait forever

What you see: both threads sit in their static initialisers and no exception is thrown.

thread dump (excerpt)runs offline
# illustrative output
"Thread-0" #21 RUNNABLE
    at B.<clinit>(InitDeadlock.java:2)
    at A.<clinit>(InitDeadlock.java:1)
"Thread-1" #22 RUNNABLE
    at A.<clinit>(InitDeadlock.java:1)
    at B.<clinit>(InitDeadlock.java:2)

Why: class initialisation takes an internal per-class lock, and each thread holds one while waiting for the other. The usual lock-based deadlock report does not cover this case, so you have to read the frames.

The fix: keep static initialisers free of references to classes that might refer back; move the shared value into a third class, or compute it lazily.

Fix.javaruns offline
class Shared { static final int BASE = 1; }                 // ✅ FIX: no back-reference
class A { static int x = Shared.BASE + 1; }
class B { static int y = Shared.BASE + 1; }
// Result: either start order finishes; Thread 1 prints 2, Thread 2 prints 2
Foo.java source javac Foo.class bytecode + constant pool at runtime class loader: load → link (verify, prepare, resolve) → initialise identity = (name, defining loader) · parent-first delegation <clinit> runs once, on first active use tier 0 · interpreter runs bytecode, counts calls and loop back-edges 200 calls tier 3 · C1 with profiling fast compile, simple code, records types and branches 5000 calls tier 4 · C2 inlining, escape analysis, speculation on the profile deoptimisation: a speculation failed (new subclass loaded, untaken branch taken) → back to the interpreter, re-profile, recompile compiled code lives in the code cache (default 240 MB); full cache = "compiler has been disabled" = back to interpreting watch it all with -XX:+PrintCompilation · jcmd <pid> Compiler.codecache · JFR jdk.Compilation events
Fig. E2.1 — Two compilers at two times: javac produces portable bytecode; the JVM loads, links and initialises it, then promotes hot methods through C1 to C2. The accent arrow is the part most engineers never see: compiled code can be thrown away and the method starts over in the interpreter.

Execution: the interpreter, then C1, then C2

When a method first runs, the interpreter executes its bytecode one instruction at a time. That is slow — roughly ten to fifty times slower than compiled code — but it needs no compilation to get started.

And while it runs, it profiles. It counts how many times each method is called and how many times each loop goes around. It records which concrete types show up at each call site, and which way each branch goes. Everything the JIT later does well, it does because of what the interpreter wrote down here.

HotSpot's tiered compilation then promotes methods in stages.

How a method climbs the tiers, and what triggers each step.
TierTriggerWhat you get
InterpreterFirst run.Slow execution, but full profiling.
C1 — tier 3About 200 invocations (-XX:Tier3InvocationThreshold=200).The client compiler. Compiles fast, produces decent code that still carries profiling counters.
C2 — tier 4About 5 000 invocations (-XX:Tier4InvocationThreshold=5000), or 40 000 loop iterations.The server compiler. Far slower to compile, but uses the accumulated profile to produce aggressive, specialised code.

Two details fill in the gaps. A method stuck inside a long loop gets compiled mid-execution, through on-stack replacement (OSR) — that is what the % flag means in compilation logs. And tiers 1 and 2 exist for trivial methods, and for when the C2 queue is backed up.

One thing that surprises people: each compile runs on a background compiler thread. Your request threads never wait for it. They keep running the older version until the new one is installed.

Picture it: the tiers on a timeline

The setup: the sum method from JvmTour below, called 20 000 times per batch.

Make the invisible visible: each batch is one row; the middle column is what is executing the method at that time.

JIT tier timelineruns offline
# illustrative output
batch  ns/call  executing as                    event
  1     110     tier 0, interpreter             counters pass 200 calls: C1 compile queued
  2      30     tier 3, C1 with profiling       ✓ about 4x faster, still counting
  3      30     tier 3, C1 with profiling       counters pass ~5 000 calls: C2 compile queued
  4      12     tier 4, C2                      ✓ unrolled, vectorised
  5-8    12     tier 4, C2                      ✓ steady state

What you see: the compile log lines for the same method, matching the timeline.

PrintCompilationruns offline
# illustrative output
  1234  312       3       JvmTour::sum (27 bytes)
  1310  340       4       JvmTour::sum (27 bytes)
  1311  312       3       JvmTour::sum (27 bytes)   made not entrant

Why: the third row is the old tier-3 version being retired now that tier 4 is installed, which is the healthy kind of "made not entrant".

What does C2 actually do that makes the code fast? Three optimisations carry most of the benefit.

That third one has a cliff in it, and it is worth knowing exactly where the cliff is. Two types at a call site still work; the site is bimorphic and C2 emits two guarded direct calls (-XX:TypeProfileWidth=2).

At three or more types the site becomes megamorphic. Now it is a real virtual dispatch through a table, with no inlining at all. Expect a 3–10× slowdown on that hot path. This is the single most common reason a tidy abstraction runs slower in production than it did in your benchmark.

Picture it: a call site going megamorphic

The setup: one hot loop calls an interface method, and over the life of the process more implementations show up.

Shapes.javaruns offline
interface Shape { double area(); }
record Circle(double r)          implements Shape { public double area() { return Math.PI * r * r; } }
record Square(double s)          implements Shape { public double area() { return s * s; } }
record Triangle(double b, double h) implements Shape { public double area() { return 0.5 * b * h; } }

static double total(Shape[] shapes) {
    double t = 0;
    for (Shape s : shapes) t += s.area();   // ❌ TRAP: the profile of THIS call site decides the code
    return t;
}

Make the invisible visible: the profile recorded at the s.area() site, and what C2 emits for each profile.

call site profileruns offline
types seen at s.area()      what C2 compiles
1  Circle                   if (type == Circle) { inlined body } else uncommon trap         ✓ monomorphic
2  Circle, Square           two guarded inlined bodies, else uncommon trap                  ✓ bimorphic
3+ Circle, Square, Triangle table dispatch (vtable/itable), no inlining across the call     ✗ megamorphic

The trace: the same array is fed in two different orders.

call traceruns offline
shapes = [C, S, T, C, S, T, ...]  (mixed)
  s.area() sees C, S, T at the SAME site     -> megamorphic, dispatch each time, no inlining  ✗
shapes grouped as [C, C, C ... S, S, S ... T, T, T]  and one loop per type
  each loop's site sees ONE type             -> monomorphic, inlined, loop can be optimised   ✓

What you see: the inlining decisions printed by a diagnostic flag, and the timing.

consoleruns offline
# illustrative output  (java -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining ...)
mixed:    @ 12   Shape::area (0 bytes)   virtual call
grouped:  @ 12   Circle::area (11 bytes)   inline (hot)

mixed   total(): 9.0 ns per element
grouped total(): 1.5 ns per element

Why: at three or more types the compiler stops guessing and uses a real virtual call, which blocks inlining and everything that depends on it.

The fix: give each hot site at most two types, for example by grouping by type and using one loop per type.

Grouped.javaruns offline
// ✅ FIX: each loop's call site sees exactly one (final) type
static double total(Circle[] cs, Square[] ss, Triangle[] ts) {
    double t = 0;
    for (Circle c : cs)   t += c.area();
    for (Square s : ss)   t += s.area();
    for (Triangle g : ts) t += g.area();
    return t;                                // Result: all three sites inline
}

What you see now: the same diagnostic flag, with an inlined body at each site (the timing row above).

Speculation can be wrong, and the JVM handles that with deoptimisation.

Compiled code contains uncommon traps at every point where the compiler assumed something — this branch is never taken, this reference is never null, this interface has only one implementation.

When an assumption fails, the trap fires and four things happen in sequence. The compiled frame is converted back into interpreter frames. The method is marked "not entrant", so no new calls enter the compiled version. The method re-profiles. Eventually it recompiles.

A single deoptimisation costs microseconds, so it is nothing to worry about on its own.

The problem is a deoptimisation storm — deoptimising and recompiling the same method over and over. It happens when a branch flips between rare and common, or when a new class keeps appearing at a call site.

And a storm looks exactly like the opener of this chapter: CPU at 100 percent, throughput down, nothing in the application changed.

The evidence is specific, so you can go and check for it. -XX:+PrintCompilation printing "made not entrant" for the same method every few seconds, or JFR's jdk.Deoptimization events arriving in bursts.

Picture it: a deoptimisation storm

The setup: a method whose hot branch flips every few seconds, so each compiled version is built on an assumption that stops being true.

The trace: one cycle, repeated.

deoptimisation cycleruns offline
1  C2 compiles handle(): branch "premium" never taken -> uncommon trap     ✓
2  premium request arrives -> trap fires                                    ✗
3  compiled frame -> interpreter frames; method marked not entrant
4  interpreter runs and re-profiles (slow)
5  C2 recompiles handle() with the new profile                              ✓
6  traffic mix flips back -> go to step 2                                   ✗

What you see: the same method retired again and again.

PrintCompilationruns offline
# illustrative output
 41210  901       4       Svc::handle (212 bytes)
 41233  887       4       Svc::handle (212 bytes)   made not entrant
 46702  955       4       Svc::handle (212 bytes)
 46710  901       4       Svc::handle (212 bytes)   made not entrant
 52188 1010       4       Svc::handle (212 bytes)
 52195  955       4       Svc::handle (212 bytes)   made not entrant

Why: every cycle throws away optimised code and spends compiler-thread CPU to rebuild it, so CPU stays high while useful work drops.

JIT symptoms, root causes and actions.
SymptomRoot causeAction
Same method made not entrant every few secondsDeoptimisation storm: a branch or receiver type keeps changingFind the unstable call site; split it or make the branch stable
One hot path permanently 3–10 times slower after a rolloutA third type reached a call site (megamorphic)Group by type or keep hot sites at two types
Compiler stops, everything runs slowlyCode cache fullCheck jcmd <pid> Compiler.codecache; raise -XX:ReservedCodeCacheSize

See it: two loaders, one name; then a method warming up

The program below does both halves of this chapter in one file.

First it compiles a tiny class from a string, in memory, using the JDK's own compiler, and defines it through two different class loaders — reproducing the "cannot be cast to itself" exception on purpose.

Then it runs a small hot method in batches and prints how long each batch took, so you can watch the interpreter hand over to C1, and then to C2.

Run it with -XX:+PrintCompilation and filter for the method's name to see the tiers being installed.

Step-by-step: what JvmTour.java does, in plain English
  1. The MemoryLoader class extends ClassLoader and overrides findClass so that, when asked for Plugin, it calls defineClass on a byte array held in memory. It sets its parent to the application loader, so every other class name delegates upward as normal; only Plugin is defined locally.
  2. compilePlugin() obtains the JDK's compiler through ToolProvider.getSystemJavaCompiler(), wraps the source text in a SimpleJavaFileObject, and wraps the standard file manager in a ForwardingJavaFileManager whose getJavaFileForOutput returns an in-memory object that captures the class bytes. The compile task runs and the captured bytes are returned. No file is written to disk.
  3. loaderDemo() defines Plugin through two separate MemoryLoader instances, prints whether the two Class objects are the same (they are not), creates an instance through loader A, and attempts to cast it to the class from loader B inside a try block. The cast throws ClassCastException and the program prints the message, which names the same class on both sides.
  4. sum(int[] a) is the method we will watch the JIT compile: a plain loop adding array elements. It is small enough to be inlined and hot enough to reach C2 quickly.
  5. jitDemo() runs sum in eight batches of 20 000 calls each, measuring each batch with System.nanoTime() and printing the average nanoseconds per call. A sink field receives the result so the compiler cannot delete the work as unused.
  6. main runs the two demos in order. The command line in the header shows how to run it with -XX:+PrintCompilation and a grep that keeps only the compilation lines for sum plus the program's own output.
JvmTour.java · JDK 21+ · java -XX:+PrintCompilation JvmTour.java 2>&1 | grep -E 'JvmTour::sum|batch|Plugin|same'runs offline
import javax.tools.*;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.List;

public class JvmTour {

    // A loader that defines exactly one class, Plugin, from bytes it holds in memory.
    static final class MemoryLoader extends ClassLoader {
        private final byte[] bytes;
        MemoryLoader(byte[] bytes) { super(JvmTour.class.getClassLoader()); this.bytes = bytes; }
        @Override protected Class<?> findClass(String name) throws ClassNotFoundException {
            if (name.equals("Plugin")) return defineClass(name, bytes, 0, bytes.length);
            throw new ClassNotFoundException(name);
        }
    }

    // Compile "public class Plugin {}" to bytes without touching the file system.
    static byte[] compilePlugin() throws Exception {
        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        var source = new SimpleJavaFileObject(URI.create("string:///Plugin.java"), JavaFileObject.Kind.SOURCE) {
            @Override public CharSequence getCharContent(boolean ignore) { return "public class Plugin { public String hello() { return \"hi\"; } }"; }
        };
        var out = new ByteArrayOutputStream();
        var fm = new ForwardingJavaFileManager<StandardJavaFileManager>(javac.getStandardFileManager(null, null, null)) {
            @Override public JavaFileObject getJavaFileForOutput(Location l, String cls, JavaFileObject.Kind k, FileObject sib) {
                return new SimpleJavaFileObject(URI.create("bytes:///" + cls), k) {
                    @Override public OutputStream openOutputStream() { return out; }
                };
            }
        };
        if (!javac.getTask(null, fm, null, null, null, List.of(source)).call()) throw new IllegalStateException("compile failed");
        return out.toByteArray();
    }

    static void loaderDemo() throws Exception {
        byte[] bytes = compilePlugin();
        Class<?> a = new MemoryLoader(bytes).loadClass("Plugin");
        Class<?> b = new MemoryLoader(bytes).loadClass("Plugin");
        System.out.println("same Class object? " + (a == b) + "   same name? " + a.getName().equals(b.getName()));
        Object fromA = a.getDeclaredConstructor().newInstance();
        try {
            b.cast(fromA);                       // the cast that plugin frameworks get wrong
            System.out.println("cast succeeded (unexpected)");
        } catch (ClassCastException e) {
            System.out.println("ClassCastException: " + e.getMessage());
        }
    }

    static long sink;                             // keeps the JIT from deleting the work below

    static long sum(int[] a) {                    // the method we watch move through the tiers
        long s = 0;
        for (int x : a) s += x;
        return s;
    }

    static void jitDemo() {
        int[] data = new int[64];
        for (int i = 0; i < data.length; i++) data[i] = i;
        for (int batch = 1; batch <= 8; batch++) {
            long t0 = System.nanoTime();
            for (int i = 0; i < 20_000; i++) sink += sum(data);
            long perCall = (System.nanoTime() - t0) / 20_000;
            System.out.println("batch " + batch + ": " + perCall + " ns per call");
        }
    }

    public static void main(String[] args) throws Exception {
        loaderDemo();
        jitDemo();
    }
}

Read the output. It comes in two parts: the loader puzzle, then the warm-up.

The first line says same Class object? false same name? true. Two loaders, two classes, one name — the puzzle from the top of this section, reproduced on purpose.

The next line is the exception itself: class Plugin cannot be cast to class Plugin (Plugin is in unnamed module of loader JvmTour$MemoryLoader @1b2c3d; Plugin is in unnamed module of loader JvmTour$MemoryLoader @4e5f6a).

Since JDK 11 the JVM prints the loader of each side precisely so this is diagnosable. When you meet this in production, those two loader names are the whole diagnosis.

Then the batches, which show the method warming up. On a typical laptop:

Interleaved with those lines, PrintCompilation prints rows like 1234 312 3 JvmTour::sum (27 bytes), and later 1310 340 4 JvmTour::sum (27 bytes).

The columns are: milliseconds since start, a compile id, the tier, the method, and its bytecode size. So those two rows are the same method arriving at tier 3, then at tier 4.

Two markers are worth recognising on sight. A row with a % was an on-stack replacement of the running loop. A row ending in made not entrant is an earlier tier being retired because a better one is installed.

That second one is the healthy form of deoptimisation. When you see "made not entrant" for the same method repeating every few seconds in a production log, that is the unhealthy form — and that is your deoptimisation storm.

🧠 Brain power

Before reading on: a hot method calls shape.area() where shape is an interface. In staging, only Circle and Square exist. In production, a third implementation, Polygon, is loaded on the first request that needs it, several minutes after startup. What happens to the compiled code for the hot method at that moment, and what does it look like from the outside?

Reveal the answer

Until Polygon loads, C2 compiled the call site as bimorphic: two guarded direct calls, with both area() bodies inlined. Loading a third implementation invalidates that assumption.

Two mechanisms can fire, depending on what the compiler leaned on.

  • If it relied on class hierarchy analysis — the JVM's knowledge that only two classes implement the interface — then merely loading Polygon immediately deoptimises every compiled method that depended on that fact. This happens before any Polygon instance exists. The compiled code is marked not entrant, and running frames convert back to interpreter frames at their next safepoint.
  • If it relied on the runtime profile instead, nothing happens at load time. The first Polygon instance that actually reaches the call site hits the uncommon trap, and the same deoptimisation happens then.

From the outside you see three things in sequence. A brief latency bump on that path — microseconds to a few milliseconds, while it runs interpreted and re-profiles. A made not entrant line in PrintCompilation. Then a recompile.

And here is the part that matters. In that recompile the call site is now megamorphic: no inlining, a table dispatch, and a permanently slower steady state for that path.

The senior answer says two things the ordinary answer misses. The slowdown is permanent, not transient. And the fix is either to keep hot sites at two types, or to split the call site per type.

Quick reference — source to machine code

bytecode
A portable instruction set for a stack machine. No registers, no memory addresses — that is what makes it portable.
constant pool
The table of every name, type and literal a class refers to. Bytecode points at entry numbers, not at methods, which is what lets linking be lazy.
invokedynamic
"The runtime decides how to do this, once, and caches the answer." Powers lambdas, string concatenation since JDK 9, and record equals/hashCode/toString.
The three loaders
Bootstrap (java.base) → platform (rest of the JDK) → application (your classpath). Parent-first by default.
A class's identity
(fully-qualified name, defining loader). Two loaders defining the same bytes produce two unrelated classes — which is the whole explanation for "Plugin cannot be cast to Plugin".
Linking, in order
Verification (well-formed and type-safe) → preparation (statics to default values) → resolution (symbolic references to direct ones, lazily).
First active use
What triggers <clinit>: new instance, static method call, non-constant static field access, Class.forName, or subclass initialisation. Loading alone does not.
The tiers
Interpreter (profiles) → C1 at ~200 invocations → C2 at ~5 000 invocations or 40 000 loop iterations. OSR compiles a loop mid-flight; that is the % in the log.
deoptimisation
An assumption failed, so compiled code is discarded and the method falls back to the interpreter. One is harmless. The same method repeating every few seconds is a storm, and it looks like "CPU 100%, throughput down, nothing changed".
monomorphic → bimorphic → megamorphic
One type at a call site inlines. Two still inline. Three or more means table dispatch, no inlining, and a permanently slower path.

03 · The primerThe Java Memory Model, Properly: Happens-Before, volatile, Final Fields and VarHandles

The Java Memory Model is the set of rules that says when one thread is guaranteed to see what another thread wrote. If no rule connects your write to someone else's read, that thread may never see it — and the compiler is allowed to keep it that way forever.

A worker thread spins on while (!stop) { work(); }. Another thread sets stop = true. In your unit test the worker exits within a millisecond.

In production it does not. After the service has been running for a few minutes, the worker never exits and the deploy hangs on shutdown. There is no exception and no log line. One CPU core sits at 100 percent forever.

Most engineers who have met this bug learned the fix — the word volatile — without learning the rule that made the bug legal in the first place. That is why they cannot say whether the next, slightly different piece of code is safe.

This chapter gives you the rule. It is called the Java Memory Model (JMM), it is precise, and once you can state it you can reason about any piece of concurrent Java without guessing.

Bridge: the compiler and the CPU both reorder your code, on purpose

You already accept two things about the machinery under your code. An optimising compiler may reorder statements that do not depend on each other. A modern CPU executes instructions out of order and buffers writes for a while before they reach memory.

Neither is visible to single-threaded code. The rules guarantee that one thread always observes its own actions in program order, so the reordering is real but undetectable from inside that thread.

Both become visible the moment a second thread reads what the first one wrote. The JMM is the contract that says exactly when a write by one thread is guaranteed to be seen by a read in another thread. It says it in terms of a single relation: happens-before.

The rule: happens-before

Read it as a plain sentence: if action A happens-before action B, then everything A did is visible to B, and A appears to come before B.

Happens-before is not about wall-clock time. Two actions that occurred a full second apart on a clock have no visibility guarantee between them unless a happens-before edge connects them. Time does not create the edge; only the rules below do.

There are eight rules. Reciting eight flat items is hard, and it is not how you use them anyway. So here they are in four groups, organised by the question you actually ask at the keyboard: what do I have to do to get this edge?

Group 1 — the edge you get for free

Group 2 — the edges you ask for by writing something

These two are the ones you reach for deliberately. They answer almost every "how do I make this safe" question.

Group 3 — the edges the runtime hands you around a thread's life

You get these three just by starting, joining, or interrupting a thread. Most people use them every day without noticing they are memory-model rules.

Group 4 — the edge from construction, and the one that connects everything

Transitivity is worth a second look, because it is the one people skip. On its own, the volatile rule only promises something about the volatile field itself. Chained through transitivity, it promises something about all your ordinary fields. That is the whole trick, and the diagram below is a picture of it.

Everything the java.util.concurrent library promises is expressed with these same edges. Putting a value into a ConcurrentHashMap happens-before a later get of that key. Submitting a task to an executor happens-before the task runs. A CountDownLatch.countDown() happens-before await() returning.

The JMM's central promise follows. First, a definition: two accesses conflict when two threads touch the same variable and at least one of them is writing. A program in which every conflicting access is ordered by happens-before is data-race-free, and a data-race-free program behaves as if every action happened in one single global sequence. That is the whole payoff — you get to reason about your program as one ordered list of steps.

A program with even one data race gets no such guarantee. In that case the compiler is allowed to do things that look absurd when you read the source, such as hoisting a field read out of a loop because nothing in that thread ever writes the field.

Back to the spinning worker: what the compiler is allowed to write instead

Now apply the rule to the opener. stop is a plain field. The worker's loop never writes it, and there is no happens-before edge from the main thread's write to the worker's read. The two accesses conflict and nothing orders them, so the program has a data race and the JMM owes it nothing.

C2, the optimising just-in-time compiler, is therefore allowed to read stop once before the loop and keep the value in a register. Written back out as Java, the loop it actually compiles is this:

what you wrote → what C2 may compilereasoning, not runnable
// What you wrote:
while (!stop) {          // re-reads the field every iteration, you assume
    work();
}

// What C2 is legally allowed to compile it into, because nothing
// in THIS thread writes `stop` and no happens-before edge exists:
boolean cached = stop;   // one read, hoisted out of the loop, kept in a register
while (!cached) {
    work();              // if `cached` was false, this loop never ends
}

Read that second version carefully, because it is the whole bug. The loop condition no longer touches memory at all. Another thread can set the field a thousand times and the worker will never look again.

This also explains the timing that makes the bug so confusing. In the interpreter, and in code compiled by C1, the read happens every iteration and the bug is invisible. C2 only compiles the loop after it has run a few thousand iterations and been judged hot. The bug appears "only after a few minutes in production" because that is when C2 got to it — and a unit test that runs for a millisecond never gets there.

Picture it: the spinning worker, step by step

The setup: a plain flag, a worker that polls it, and a main thread that sets it.

Worker.javaruns offline
static boolean stop;                                  // ❌ TRAP: plain field, no happens-before edge

Thread worker = new Thread(() -> { while (!stop) { work(); } });
worker.start();
Thread.sleep(500);
stop = true;                                          // main thread writes
worker.join();                                        // never returns once C2 compiled the loop

Make the invisible visible: the two threads, one row per step, after C2 has compiled the loop.

thread interleavingruns offline
step  worker thread (C2 code)                    main thread
1     cached = stop  (reads false)  ✓
2     loop: work(); test cached ...  ✓
3                                                sleep(500) ends
4                                                stop = true  (plain write, no edge to the worker)
5     loop: test cached (still false)  ✗
6     ... forever, one core at 100 percent  ✗     join() waits for ever  ✗

What you see: a thread that stays alive, with no exception and no log line.

consoleruns offline
# illustrative output
plain read   : worker still running 2 s after the flag was set? true

Why: no edge connects the write to the read, so the loop may keep its first value.

The fix: make the write and the read a volatile pair, which creates the edge.

WorkerFixed.javaruns offline
static volatile boolean stop;                         // ✅ FIX: volatile write happens-before later volatile read
// Result: the worker re-reads the field every iteration and exits

What you see now: the same line, with the answer flipped.

consoleruns offline
# illustrative output
  volatile read worker exited after 41522318 iterations
volatile read : worker still running 2 s after the flag was set? false
Thread A (writer) data = 42; (plain write) program order ready = true; (volatile write) Thread B (reader) if (ready) (volatile read → true) program order int x = data; (plain read → 42) synchronizes-with by transitivity: data = 42 happens-before x = data, so x must be 42 without the volatile pair there is no edge: B may read data as 0, or the JIT may hoist the read out of a loop
Fig. E2.2 — A happens-before edge is built from a volatile write/read pair (or a lock, a thread start, a join). The edge carries every earlier plain write in A to every later plain read in B. Remove the edge and the plain reads have no guarantee at all.

volatile, cheaply understood

A volatile field gives you two guarantees and withholds a third.

What that costs you depends entirely on the CPU, and the difference between two CPUs is the reason this bug travels.

On x86, which has a strong memory model called total store order, a volatile read is just a normal load. Only the volatile write costs anything: one full memory fence, emitted as a lock-prefixed instruction, running tens of nanoseconds under contention.

On ARM the model is weaker, so both sides need work — special load-acquire and store-release instructions. This matters to you now rather than in theory, because Graviton and Apple silicon are ordinary deployment targets.

Put those two together and you get the trap. Code with a missing volatile can pass every test on x86 and corrupt data on ARM. The x86 hardware was silently providing ordering that the JMM never promised, and moving to ARM takes the gift away.

Picture it: volatile does not make count++ atomic

The setup: two threads each add 1 000 000 times to a volatile counter.

LostUpdate.javaruns offline
static volatile int count;
Runnable r = () -> { for (int i = 0; i < 1_000_000; i++) count++; };   // ❌ TRAP: read, add, write
Thread a = new Thread(r), b = new Thread(r);
a.start(); b.start(); a.join(); b.join();
System.out.println(count);

Make the invisible visible: count++ is three steps, and the threads interleave between them.

thread interleavingruns offline
step  Thread A                    Thread B                  count in memory
1     read count -> 5  ✓                                    5
2                                 read count -> 5  ✓        5
3     write 6                                               6
4                                 write 6  ✗ lost update    6   (should be 7)

What you see: a total below two million, different on every run.

consoleruns offline
# illustrative output
1387412

Why: volatile makes each read and each write visible, but the read-add-write sequence as a whole is not one indivisible step.

The fix: use an atomic read-modify-write.

Atomic.javaruns offline
static final AtomicInteger count = new AtomicInteger();
Runnable r = () -> { for (int i = 0; i < 1_000_000; i++) count.incrementAndGet(); };   // ✅ FIX

What you see now: the exact total, every run.

consoleruns offline
2000000

Picture it: why a missing volatile can pass on x86 and fail on ARM

The setup: a plain data field published through a plain flag.

Handoff.javaruns offline
static int data;
static boolean ready;                // ❌ TRAP: should be volatile

// Thread A:  data = 42;  ready = true;
// Thread B:  while (!ready) { }  print(data);

Make the invisible visible: with no edge, the two writes in A may become visible to B in either order.

thread interleavingruns offline
step  Thread A (writer)             Thread B (reader)
1     data = 42   (sits in a store buffer)
2     ready = true  (reaches memory first)  ✗ reordered
3                                   read ready -> true
4                                   read data  -> 0   ✗ stale

What you see: a rare zero, mostly on weakly ordered CPUs.

consoleruns offline
# illustrative output
x86 (total store order):  42
ARM (weaker model):       0   (occasionally)

Why: x86 happens to keep stores in order, which the JMM never promised, so the bug hides there.

The fix: declare ready volatile.

HandoffFixed.javaruns offline
static volatile boolean ready;       // ✅ FIX: the volatile write carries data = 42 with it
// Result: B prints 42 on every CPU

What you see now: 42 on both CPUs.

consoleruns offline
# illustrative output
x86:  42
ARM:  42

Final fields and safe publication

There is one way to hand an object to other threads with no lock and no volatile at all. Make its fields final.

The JMM adds a special rule for final fields. It is sometimes called the freeze. When a constructor finishes, the values of that object's final fields are guaranteed visible to any thread that later gets a reference to it — even if the reference arrived through a data race.

This is what makes immutable objects thread-safe by construction. It is also what records rely on.

The rule has exactly one condition: the reference must not escape before the constructor finishes. An object escapes when something outside the constructor can reach it too early. Three ways a constructor leaks this:

In all three cases another thread can see the object before the freeze happens. It then reads the final fields and finds default values — zero, or null.

Picture it: a constructor that leaks this

The setup: an object with a final field that registers itself before its constructor finishes.

Leaky.javaruns offline
class Leaky {
    static Leaky last;                 // plain static field
    final int v;
    Leaky() {
        last = this;                   // ❌ TRAP: escapes before the freeze
        v = 7;
    }
}

Make the invisible visible: the object as another thread can see it, mid-construction.

memory pictureruns offline
static Leaky.last ---> [ Leaky object ]
                         header
                         v = 0        <- default value, v = 7 has not run yet  ✗

The trace: the two threads, one row per step.

thread interleavingruns offline
step  Thread A (constructing)        Thread B (reader)
1     allocate Leaky, v = 0
2     last = this   (escapes)  ✗
3                                    l = Leaky.last (non-null)
4                                    print(l.v)  -> 0  ✗ not 7
5     v = 7; constructor ends (freeze happens too late)

What you see: a final field that appears to change.

consoleruns offline
# illustrative output
reader saw v = 0

Why: the freeze guarantee only covers references obtained after the constructor has finished.

The fix: publish only after construction, from a factory.

LeakyFixed.javaruns offline
class Leaky {
    static Leaky last;
    final int v;
    private Leaky() { v = 7; }
    static Leaky create() {
        Leaky l = new Leaky();         // ✅ FIX: constructor has finished
        last = l;                      // even a racy read of `last` now sees v = 7
        return l;
    }
}

What you see now: the reader sees 7 or sees null, never 0.

consoleruns offline
# illustrative output
reader saw v = 7

The general name for getting an object to another thread with all of its state visible is safe publication. The list of safe ways is short, and it is worth memorising:

Anything else is a race.

Picture it: which publications are safe

The setup: one holder class published four ways to a reader thread.

Publish.javaruns offline
class Holder { int n; final int f; Holder() { n = 1; f = 2; } }
static Holder plain;                       // A: plain field
static volatile Holder vol;                // B: volatile field
// C: reader gets it through a ConcurrentHashMap / executor submit
// Writer: plain = new Holder();  vol = new Holder();
Reader behaviour for each publication route.
Writer action / reader lineOutcome
plain = new Holder(), reader sees non-null plain.nSilently wrong: may read n == 0
plain = new Holder(), reader reads plain.fWorks: final field is frozen, reads 2
vol = new Holder(), reader reads vol.nWorks: volatile edge covers n and f
Reader reads the object after ConcurrentHashMap.get or an executor handoffWorks: the library supplies the edge

Rule per row: the final field is protected by the freeze, an ordinary field needs a real edge, and the volatile write supplies one for everything written before it.

VarHandles: choosing exactly how much ordering to pay for

Since JDK 9, java.lang.invoke.VarHandle gives you a typed handle to a single field or array element. Through that handle you pick how much ordering you want to pay for.

There are four access modes. Think of them as a ladder: each rung costs a little more and promises a little more.

The four VarHandle access modes, cheapest first.
ModeWhat it promisesReach for it when
PlainNothing beyond ordinary single-thread program order.The field is not shared across threads.
OpaqueThe access really happens — it cannot be hoisted out of a loop or optimised away. Accesses to that one variable stay in a consistent order across threads. It orders nothing else.A progress counter or stop flag that another thread polls.
Acquire / releaseA setRelease makes everything written before it visible to a getAcquire that reads the written value. It skips the full fence a volatile write pays on x86.Handing a finished object from one thread to another.
VolatileThe full guarantee — identical to the volatile keyword.You need ordering against every other access, not just this one.

The Atomic* classes expose the same ladder. You will see it as setOpaque, setRelease, getAcquire, and the compare-and-set family.

One detail tells you how practitioners actually use this. The internals of java.util.concurrent are written almost entirely in acquire/release mode. That rung is exactly enough for a handoff, and no more.

Picture it: opaque versus release/acquire

The setup: one thread fills a result and flags it; another polls the flag.

Handoff.javaruns offline
static int result;                        // plain
static boolean done;                      // accessed only through DONE
static final VarHandle DONE = /* findStaticVarHandle(Handoff.class, "done", boolean.class) */ null;

// Writer:  result = 99;  DONE.setRelease(true);
// Reader:  while (!(boolean) DONE.getAcquire()) { }  print(result);
One example under each access mode of the flag.
Code lineOutcome
Reader loops on a plain read of doneSilently wrong: loop may never end
Reader loops on getOpaque(), then reads resultThe loop ends, but result may still be stale (opaque orders nothing else)
Writer setRelease(true), reader getAcquire(), then reads resultWorks: reads 99
Writer and reader both use the volatile modeWorks, with a stronger and costlier guarantee than needed

Rule: opaque is for a flag that nothing else depends on; release/acquire is for handing over data. The two modes differ in what they carry along, not in whether the read happens.

See it: the JIT hoists the read, then a VarHandle stops it

The program below reproduces the spinning-worker bug deterministically on any HotSpot build, then fixes it with an opaque read through a VarHandle. It is one of the few memory-model demonstrations that does not depend on luck, because it exercises the compiler's reordering rather than the CPU's.

Step-by-step: what Visibility.java does, in plain English
  1. Two static fields hold the flags: plainStop, an ordinary boolean, and handleStop, also an ordinary boolean, but which the worker will read only through a VarHandle named STOP obtained with MethodHandles.lookup().findStaticVarHandle(...). The handle is created once in a static initialiser, which is the standard idiom.
  2. spinUntil(BooleanSupplier stopped) is the worker's loop: it counts iterations while the supplied check returns false. The supplier is a lambda so that the same loop body can be run with the plain read and with the handle read.
  3. run(String label, BooleanSupplier check, Runnable setStop) starts a platform thread running spinUntil, sleeps 500 ms so that C2 has ample time to compile the loop (it needs tens of thousands of iterations; the loop makes millions in 500 ms), then calls setStop to set the flag and joins the worker with a 2-second timeout. It prints whether the worker exited.
  4. The first run uses a plain read, () -> plainStop. Once compiled by C2 the read is hoisted out of the loop, so the worker never sees the update and the join times out. The program marks that thread as a daemon so the JVM can still exit.
  5. The second run uses () -> (boolean) STOP.getOpaque(). Opaque mode forbids the compiler from eliminating or hoisting the read, so every iteration re-reads memory and the worker exits within microseconds of the flag being set.
  6. main runs both and prints the two results side by side, so the difference is visible in two lines.
Visibility.java · JDK 21+ · java Visibility.java (add -Xint to see the bug vanish when the JIT is off)runs offline
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.function.BooleanSupplier;

public class Visibility {

    static boolean plainStop;                     // read directly: the JIT may hoist the read out of the loop
    static boolean handleStop;                    // read through a VarHandle in opaque mode: the read must happen
    static final VarHandle STOP;
    static {
        try {
            STOP = MethodHandles.lookup().findStaticVarHandle(Visibility.class, "handleStop", boolean.class);
        } catch (ReflectiveOperationException e) { throw new ExceptionInInitializerError(e); }
    }

    static long spinUntil(BooleanSupplier stopped) {
        long n = 0;
        while (!stopped.getAsBoolean()) n++;      // no lock, no volatile: only the read itself decides
        return n;
    }

    static void run(String label, BooleanSupplier check, Runnable setStop) throws InterruptedException {
        Thread worker = new Thread(() -> System.out.println("  " + label + " worker exited after " + spinUntil(check) + " iterations"));
        worker.setDaemon(true);                   // so a stuck worker cannot keep the JVM alive
        worker.start();
        Thread.sleep(500);                        // long enough for C2 to compile the loop
        setStop.run();
        worker.join(2_000);
        System.out.println(label + ": worker still running 2 s after the flag was set? " + worker.isAlive());
    }

    public static void main(String[] args) throws InterruptedException {
        run("plain read   ", () -> plainStop, () -> plainStop = true);
        run("opaque read  ", () -> (boolean) STOP.getOpaque(), () -> STOP.setOpaque(true));
    }
}

Read the output. Two pairs of lines, showing the bug and then the fix.

The first result line says plain read : worker still running 2 s after the flag was set? true, and no "worker exited" line ever appears for it. The compiled loop read plainStop once, and never again.

Now run the same program with java -Xint Visibility.java, which disables the JIT entirely. The same line says false, with an iteration count of a few million, because the interpreter re-reads the field every time.

That single flag flip is the most convincing evidence you can put in front of a colleague who believes "it works on my machine" means the code is correct.

The second pair of lines is the fix: opaque read worker exited after 41 522 318 iterations, followed by opaque read : … ? false.

Opaque mode costs almost nothing on any CPU — it is a plain load that the compiler is simply not allowed to hoist — and it is exactly the guarantee this loop needs.

A volatile field would work too, and would additionally order the surrounding accesses, which this loop does not need. Choosing the weaker mode on purpose, and being able to say why, is the senior move.

🧠 Brain power

Before reading on: a colleague replaces a volatile reference to an immutable Config record with a plain field, arguing "records are immutable, the final-field rule makes them safe to share". Readers now occasionally see the previous config for a long time after a reload. Is the colleague right about the final-field rule? What did they miss?

Reveal the answer

They are half right, and the half they have wrong is the important half.

The final-field rule guarantees that whichever Config object a reader obtains, its fields are fully visible. Nobody will see a half-built record.

What it does not guarantee is that the reader obtains the latest object.

The reference field itself is plain, so there is no happens-before edge from the reload thread's store to the request thread's load. The JIT may keep the old reference in a register across a loop, and on a weak-memory CPU the store may simply not be visible yet.

That is why readers see the previous config.

The two rules cover different things. final protects the inside of the object. Publishing the reference still needs volatile, an AtomicReference, or a VarHandle in release/acquire mode.

The right design is a volatile Config current, or an AtomicReference<Config>, read once per request into a local variable — so that one request sees one consistent snapshot.

Quick reference — the Java Memory Model

happens-before
If A happens-before B, everything A did is visible to B. It comes from the rules below, never from clock time.
data race
Two threads touch the same variable, at least one writes, and no happens-before edge connects them. A program with one race gets zero guarantees.
The eight edges
  • Program order — within one thread, each action to the next.
  • Monitor lock — unlock, to every later lock of the same monitor.
  • Volatile — a write, to every later read of that field.
  • Thread start — start(), to everything in the new thread.
  • Thread termination — everything in a thread, to a join() that returns.
  • Interruption — interrupt(), to the target noticing.
  • Final fields — end of constructor, to any read through a properly published reference.
  • Transitivity — A to B, B to C, therefore A to C.
volatile
Gives visibility and ordering. Does not give atomicity: count++ still loses updates.
safe publication
Static initialiser, volatile field or AtomicReference, final fields, a lock, or a concurrent collection / executor / thread start. Anything else is a race.
VarHandle modes
Plain → opaque → acquire/release → volatile. Cheapest first. Opaque for a polled flag, acquire/release for a handoff.
Why it only breaks in production
C2 compiles a loop after a few thousand iterations, and only then hoists the racy read into a register. A millisecond-long unit test never gets there.

04 · The primerMemory and Garbage Collection: Object Layout, G1, ZGC, and the Levers That Matter

Garbage collection is the JVM finding every object your program can still reach, and reclaiming everything else. Each collector is a different bargain between pause time, CPU cost and memory used — and you cannot have all three.

A payments service runs on a 16 GB heap with G1 and a configured pause goal of 50 milliseconds. Its p99 latency is 800 milliseconds, and every spike lines up with a garbage-collection pause.

The on-call engineer lowers -XX:MaxGCPauseMillis to 20. The p99 gets worse.

That is not a paradox. It is what happens when you turn a knob without knowing what it is connected to.

By the end of this chapter you will know three things: what every major collector does with your objects, which three numbers in a GC log tell you what is wrong, and why "lower the pause goal" was the wrong move here.

Bridge: you already manage memory; the JVM just does it in bulk

In a language with manual memory management, you allocate and free each object yourself.

Java allocates for you. And instead of freeing objects one at a time, it periodically finds everything still reachable from the program's roots — thread stacks, static fields, and a few JVM-internal references — and treats everything else as garbage.

That is the entire idea. Every collector you will meet is a different strategy for doing that one thing.

They differ because each optimises for a different cost: the least pause time, the least CPU, or the least memory. There are several collectors precisely because you cannot have all three at once.

What an object is, in bytes

Every object starts with a header. On a 64-bit HotSpot with default settings that header is 12 bytes, made of two parts:

After the header come the fields, reordered by the JVM to reduce padding. Then the whole object is padded out to a multiple of 8 bytes.

That arithmetic explains some numbers worth memorising. new Object() is 16 bytes. An Integer is 16 bytes — 12 of header plus 4 of value. An empty String is 24 bytes, plus its byte array of 16.

Picture it: an object, byte by byte

The setup: two small classes, one with 8 bytes of fields and one with mixed field sizes.

Layouts.javaruns offline
class Point { int x; int y; }

class Order {
    long    id;
    int     qty;
    boolean paid;
    String  note;      // a reference: 4 bytes with compressed oops
}

Make the invisible visible: a layout dump in the format of the OpenJDK JOL tool (a separate library, org.openjdk.jol), with byte counts.

object layout (JOL style)runs offline
# illustrative output
Point object internals:
OFFSET  SIZE   TYPE DESCRIPTION
     0     8        (object header: mark word)
     8     4        (object header: class pointer)
    12     4    int Point.x
    16     4    int Point.y
    20     4        (padding to a multiple of 8)
Instance size: 24 bytes            (12 header + 8 fields + 4 padding)

Order object internals:
     0     8        (object header: mark word)
     8     4        (object header: class pointer)
    12     4    int Order.qty
    16     8   long Order.id
    24     4 String Order.note
    28     1 boolean Order.paid
    29     3        (padding)
Instance size: 32 bytes            (12 header + 17 fields + 3 padding)

The trace: the arithmetic for a million values shows why the header matters.

size arithmeticruns offline
int[1_000_000]               16 (array header) + 4 x 1_000_000                      =  ~4 MB   ✓
List<Integer>, 1_000_000     array of refs: 4 x 1_000_000                           =  ~4 MB
                             + one Integer each: 16 x 1_000_000                     = ~16 MB
                             total                                                  = ~20 MB   ✗ 5x bigger

object with 5 references    compressed oops: 12 + 5 x 4 = 32 bytes
                            heap above 32 GB: 12 + 5 x 8 = 52 -> padded to 56 bytes   ✗ 75% bigger

Why: every object pays for a header and padding, and every reference pays 4 bytes (or 8 above 32 GB).

The fix: store primitives in primitive arrays on hot paths, and keep the heap at or under about 31 GB so references stay 4 bytes.

Compact.javaruns offline
int[] values = new int[1_000_000];        // ✅ FIX: ~4 MB, no per-element object
// java -Xmx31g ...                       // ✅ FIX: stays inside compressed-oops range

One change is coming that moves all of these. Compact object headers have been a product feature since JDK 25 (JEP 519, -XX:+UseCompactObjectHeaders) and are on by default in JDK 27 (JEP 534). They shrink the header to 8 bytes, which typically cuts total heap use by 10 to 20 percent on object-heavy workloads.

References themselves are 4 bytes, not 8 — as long as the heap is at most 32 GB.

This is compressed oops, where "oop" means ordinary object pointer. The trick is alignment: because objects sit on 8-byte boundaries, the low three bits of every address are always zero. So a 32-bit value, shifted left by three, can address 32 GB.

Cross that 32 GB line and the effects cascade. Every reference doubles to 8 bytes. Every object holding references gets bigger. Cache lines hold fewer of them.

The consequence is genuinely counter-intuitive, and interviewers like it for that reason: a 40 GB heap can hold less live data than a 31 GB one.

You can stretch the limit to 64 GB with -XX:ObjectAlignmentInBytes=16, at a density cost. But the usual advice is simpler: stay at or below 31 GB, or go well beyond it and accept the cost.

One footnote that explains a real sizing decision. ZGC does not use compressed oops at all, which is part of why it wants more memory than G1 for the same live set.

Allocation: the fast path is a pointer bump

Allocation in Java is fast because most of the time it is a single pointer increment.

Each thread owns a thread-local allocation buffer (TLAB) — a chunk of the young generation reserved for that thread alone.

So new compiles to this: "add the object size to my TLAB's top pointer; if it still fits, done". No lock, no search, roughly ten instructions.

Two slow paths sit behind that. When the TLAB is full, the thread goes and gets a new one from the shared area. When the young generation itself is full, a young collection runs.

Which gives you the single most useful number in GC tuning. The allocation rate, in megabytes per second, determines how often young collections happen — and that is why the cheapest GC fix is very often a code change that allocates less.

Picture it: a pointer bump, and what allocation rate means

The setup: a request loop that creates 24-byte objects, running in a thread with its own TLAB.

memory pictureruns offline
# TLAB of thread T1 (a slice of eden)
|-- used by T1 ----------|top|------ free ------|end|
                          ^
new Order(): size = 32 bytes
1  top + 32 <= end ?    yes  ✓  -> object starts at old top, top += 32   (no lock)
2  top + 32 <= end ?    no   ✗  -> slow path: take a new TLAB from eden
3  eden has no room     ✗       -> young collection

The trace: worked example with real numbers.

allocation rate arithmeticruns offline
eden size              400 MB
allocation rate        200 MB/s
young collection every 400 / 200 = 2 s
halve the rate to 100 MB/s -> every 4 s   ✓   (half the collections, same heap)

What you see: the same arithmetic shows up in the log as spacing between young pauses.

consoleruns offline
# illustrative output  (-Xlog:gc, rate 200 MB/s)
[10.0s][info][gc] GC(5) Pause Young (Normal) (G1 Evacuation Pause) 410M->12M(1024M) 4.1ms
[12.0s][info][gc] GC(6) Pause Young (Normal) (G1 Evacuation Pause) 412M->12M(1024M) 4.0ms

Generations, and why G1 has regions

The generational hypothesis is an empirical observation, not a theory: most objects die young. A request creates hundreds of temporary objects and drops them, while a handful of caches and connection objects live for hours.

Generational collectors exploit that shape directly. New objects go in a young generation that is collected often and cheaply — only live objects get copied out, and the dead ones cost nothing at all. Survivors are promoted, after a few collections, into an old generation that is collected rarely.

There is a catch, and the machinery built to handle it shows up in every GC interview. An old object may point at a young one. A young collection has to know about those pointers — without scanning the whole old generation to find them, which would defeat the purpose.

HotSpot solves it with a write barrier: a few instructions the JIT emits after every reference store. The barrier marks the containing area as "dirty", in either a card table or a per-region remembered set.

That barrier is the real price of generational collection, and you pay it on every reference write in your program. Making it cheaper is ongoing work — JDK 26's G1 changes (JEP 522) were largely about exactly that.

G1 is the default collector for most workloads — and from JDK 27, under JEP 523, the default everywhere, including the small containers that previously got Serial.

Its central idea is that the heap is divided into equal regions, each 1 to 32 MB, sized so that there are about 2 048 of them.

Any region can be eden, survivor, or old at a given moment. That flexibility is the point: it lets G1 resize the young generation on the fly to meet a pause goal.

A young collection stops the world, copies live objects out of all eden and survivor regions into fresh survivor or old regions, and frees the sources. Note what its duration scales with — the amount of live data, not the size of the heap.

When the old generation passes a threshold (-XX:InitiatingHeapOccupancyPercent, adaptive by default), G1 starts a concurrent marking cycle alongside your threads, to work out how much garbage each old region holds.

It then follows that with a few mixed collections: young collections that also evacuate the old regions holding the most garbage, cheapest first. That is what "garbage first" means, and it is where the collector gets its name.

Two failure modes are worth knowing by name, because both show up in production logs.

Now the opener. MaxGCPauseMillis is a goal, and G1 meets it mainly by shrinking the young generation so that each young collection has less to copy.

Follow that through and the engineer's change makes its own kind of sense — the wrong kind. Lower the goal, and the young generation shrinks. Collections happen more often. More objects get promoted before they had time to die. The old generation fills faster. Mixed collections come sooner and do more work. The tail gets worse.

But the deeper mistake was diagnostic, not mechanical. Those 800 ms pauses were almost certainly not young collections at all. The log would have shown one of two things: full GCs after evacuation failure, meaning the live set is too close to the heap size, or humongous churn.

The fix is a bigger heap or less live data. Not a tighter goal.

Picture it: why lowering the pause goal made p99 worse

The setup: a 16 GB heap on G1, with the goal changed from 50 ms to 20 ms.

command linesruns offline
# before
java -Xmx16g -XX:MaxGCPauseMillis=50 -jar payments.jar
# after   ❌ TRAP: a smaller goal means a smaller young generation
java -Xmx16g -XX:MaxGCPauseMillis=20 -jar payments.jar

Make the invisible visible: the chain of cause and effect, one step per line.

trace of the knobruns offline
1  goal 50 -> 20 ms         G1 shrinks eden so each young pause copies less   ✓ (each pause shorter)
2  eden is smaller          young collections happen more often               ✗
3  objects get less time    more survive and are promoted early               ✗
   to die
4  old generation fills     concurrent marking starts sooner, mixed pauses    ✗
   faster                   do more work
5  live set near heap size  no free region to copy into: to-space exhausted   ✗
6  fallback                 single-threaded full GC, compacting everything    ✗  (the 800 ms spike)

What you see: the log of the spike is a full GC, not a young pause.

consoleruns offline
# illustrative output
[3601.2s][info][gc] GC(881) To-space exhausted
[3601.3s][info][gc] GC(881) Pause Young (Normal) (G1 Evacuation Pause) 15801M->15702M(16384M) 311.4ms
[3601.3s][info][gc] GC(882) Pause Full (G1 Compaction Pause) 15702M->14980M(16384M) 812.7ms

Why: the 800 ms spike was never a young collection, so tuning the young pause goal could not touch it.

The fix: read the log first, then give the collector room: a bigger heap, or less live data. Restore the goal.

command lineruns offline
# ✅ FIX: headroom for evacuation, goal back to 50
java -Xmx24g -XX:MaxGCPauseMillis=50 -jar payments.jar

What you see now: young pauses only, and the heap floor well below the maximum.

consoleruns offline
# illustrative output
[3601.2s][info][gc] GC(881) Pause Young (Normal) (G1 Evacuation Pause) 14210M->9020M(24576M) 38.6ms

Picture it: a humongous object in a 2 MB region

The setup: a service on a 4 GB heap reads each upload into a 1.5 MB array. Region size is 4 GB / 2048 = 2 MB.

Upload.javaruns offline
byte[] buf = new byte[1_500_000];      // ❌ TRAP: 1.5 MB is more than half of a 2 MB region
in.readNBytes(buf, 0, buf.length);

Make the invisible visible: the region the array occupies.

memory pictureruns offline
region size 2 MB (2048 KB)
humongous threshold = half a region = 1024 KB

[ H: byte[1.5 MB] ....................... | 0.5 MB unused ]     one region per buffer  ✗
[ E: many small young objects share one region ............... ]   ✓

What you see: pauses caused by the humongous allocation while most of the heap is free.

consoleruns offline
# illustrative output  (-Xlog:gc)
[42.0s][info][gc] GC(30) Pause Young (Concurrent Start) (G1 Humongous Allocation) 1403M->1311M(4096M) 9.1ms
[44.0s][info][gc] GC(31) Pause Young (Concurrent Start) (G1 Humongous Allocation) 1409M->1318M(4096M) 9.4ms

Why: each array gets a whole region of its own, wasting 0.5 MB, and humongous allocations count toward the marking threshold, so they trigger collections early.

The fix: a larger region makes the same array an ordinary allocation; streaming removes it.

command lineruns offline
# ✅ FIX: 8 MB regions, humongous threshold becomes 4 MB
java -Xmx4g -XX:G1HeapRegionSize=8m -jar upload.jar

What you see now: the cause label disappears from the young pauses.

consoleruns offline
# illustrative output
[42.0s][info][gc] GC(30) Pause Young (Normal) (G1 Evacuation Pause) 1100M->40M(4096M) 5.2ms
G1 symptoms, root causes and actions.
Symptom in the logRoot causeAction
Pauses with cause G1 Humongous Allocation, heap mostly freeLarge arrays above half a regionRaise -XX:G1HeapRegionSize, or stream instead of buffering
To-space exhausted then Pause FullEvacuation failure: no free region to copy intoMore heap, less live data; do not lower the pause goal
Young pauses frequent and short, old generation growingPause goal too low, or very high allocation rateRestore the goal; allocate less
Young pauses growing round by roundLive set growing (survivors to copy)Check for a leak or a cache without a bound
G1 heap: ~2048 equal regions (here 8 × 4), roles change over time E E O O free E S O O H (humongous) E O free E O S O O 90% free E O O 85% free E free O O S free O E E eden · S survivor · O old · H humongous (≥ half a region, own contiguous regions) · "O 90%" = old region 90% garbage after marking Young collection (stop-the-world, frequent) copy live objects out of ALL E and S regions into fresh S/O regions; cost ∝ live data, not heap old fills past IHOP Concurrent marking (runs beside your threads) finds how much garbage each old region holds; short pauses: Remark, Cleanup Mixed collections (a few, stop-the-world) young regions + the garbage-richest old regions ("garbage first"); no free region to copy into = full GC -XX:MaxGCPauseMillis is met by resizing the young generation; -XX:G1HeapRegionSize decides what counts as humongous
Fig. E2.3 — G1's heap is a grid of regions whose roles change. Young collections are cheap because they copy only survivors; the accent step, mixed collections, is where old garbage is reclaimed and where the pause goal, the region size, and the live set decide whether the collector keeps up or falls back to a full GC.

ZGC, Shenandoah, Parallel: the other strategies

ZGC makes a different trade. It does almost all of its work — including moving objects — concurrently with your threads. Its pauses stay under a millisecond regardless of heap size, right up to terabytes.

The trick is coloured pointers. ZGC stores a few metadata bits inside each 64-bit reference, which is exactly why it cannot use compressed oops.

Every reference load then passes through a load barrier: a few instructions that check the colour and, if the object has moved since the reference was written, fix the reference up on the spot. Your threads repair pointers as they use them, so the collector never has to stop the world to do it.

Picture it: the load barrier at work

The setup: your thread reads a reference field of an object that ZGC has just relocated.

call traceruns offline
1  thread executes:  Node n = holder.next;      (load barrier runs after the load)
2  barrier checks the colour bits in the reference:
   good colour -> use it as is                                            ✓
   bad colour  -> object moved: look up the new address, fix the field    ✗ (slow path, once)
3  the field now holds the new address with a good colour (self-healing)  ✓
4  next read of holder.next takes the fast path                           ✓

What you see: the cost is a few instructions on every reference load, which is part of ZGC's throughput price, in exchange for pauses that do not grow with the heap.

Since JDK 21 ZGC is generational (JEP 439), which cut its CPU cost dramatically. That mode became the default in JDK 23, and the old single-generation mode was removed in JDK 24 (JEP 490).

ZGC's failure mode is not a long pause. It is an allocation stall: if your threads allocate faster than the concurrent cycle reclaims, a thread that needs memory simply waits until the cycle finishes. The log says so explicitly.

Three things cure a stall. A bigger heap — ZGC wants headroom, commonly 20 to 30 percent above the live set plus whatever you allocate during a cycle. More concurrent GC threads (-XX:ConcGCThreads). Or a lower allocation rate.

Picture it: an allocation stall

The setup: a ZGC service with a 10 GB live set, allocating 1 GB per second, on a 12 GB heap.

headroom arithmeticruns offline
live set                      10 GB
heap                          12 GB   -> headroom = 2 GB
allocation rate               1 GB/s
one concurrent cycle takes    3 s     -> needs 3 GB of headroom while it runs
2 GB < 3 GB                   ✗ threads run out of memory mid-cycle and wait

heap 14 GB -> headroom 4 GB   ✓ 4 GB >= 3 GB, no stall

What you see: the stall lines name the thread that had to wait.

consoleruns offline
# illustrative output  (-Xlog:gc)
[120.4s][info][gc] Allocation Stall (http-nio-8080-exec-7) 83.201ms
[120.4s][info][gc] Allocation Stall (http-nio-8080-exec-2) 80.477ms

Why: ZGC never stops the world to reclaim, so when allocation outruns the concurrent cycle the only choice is to make the allocating thread wait.

The fix: add headroom, add concurrent threads, or allocate less.

command lineruns offline
# ✅ FIX: 14 GB heap, and more concurrent GC threads if CPU allows
java -XX:+UseZGC -Xmx14g -XX:ConcGCThreads=4 -jar app.jar

What you see now: no stall lines in the same window.

consoleruns offline
# illustrative output
(no "Allocation Stall" lines; request p99 follows the application, not the collector)

The other collectors each exist for one specific reason, and it is worth being able to name that reason rather than the collector.

The collectors, and the one situation each is the right answer for.
CollectorWhat it does differentlyChoose it when
G1Region-based, concurrent marking, mixed collections. The default.You have no specific reason to change. This is the boring correct answer.
ZGCConcurrent everything, via coloured pointers and load barriers. Sub-millisecond pauses at any heap size.Pause time is the thing you are being judged on, and you can pay in memory and a few percent of throughput.
ShenandoahRed Hat's collector. Same goal as ZGC, similar barrier design. Generational since JDK 25 (JEP 521).You want ZGC's properties on a distribution that ships it. It is in most distributions, but not Oracle's.
ParallelFully stop-the-world, all cores, no barriers beyond the card table.A batch job where only total run time matters. Often 10–20 percent faster than G1, and pauses are irrelevant.
SerialOne thread, tiny footprint.A container with a single CPU.
Epsilon (JEP 318)Allocates and never collects.Tests, and services that restart before they can fill the heap.
Choose the collector, as of August 2026 (JDK 21 and 25).
Choose…When…Because… / watch out for…
G1 (default)Heaps up to ~32 GB, mixed workloads, pause goal in the tens of milliseconds acceptableBest all-round throughput per pause; compressed oops; humongous objects and evacuation failure are its two failure modes; keep the heap at 2–3× the live set
Generational ZGC (-XX:+UseZGC)p99 must not see GC pauses; heaps from a few GB to terabytes; you can afford 10–20% more memory and some CPUSub-millisecond pauses always; no compressed oops, so objects are bigger; allocation stalls if the heap has too little headroom; check ConcGCThreads under CPU limits
Generational ShenandoahSame goals as ZGC on a distribution that ships it (Red Hat, Amazon Corretto, Eclipse Temurin), or heaps too small for ZGC's headroomSimilar behaviour and trade-offs to ZGC; not in Oracle JDK builds
Parallel (-XX:+UseParallelGC)Batch jobs, data pipelines, anything measured by total run time rather than latencyHighest throughput, multi-second pauses on large heaps, simplest to reason about
SerialContainers with 1 CPU and under ~1 GB, CLIs, sidecarsSmallest footprint; note JDK 27 defaults even these to G1 (JEP 523), so set it explicitly if you want it
Do NOT tune the young generation by hand on G1Ever, unless you have a measured reason-Xmn/NewRatio disable the adaptive sizing that meets the pause goal; the levers that matter are heap size, region size, pause goal, and allocation rate

One rule and one example per row of the first table:

The rest of the process: metaspace, off-heap, and what "memory" means to the kernel

The heap is only part of a JVM process. Several other regions grow independently of it, and any of them can be the thing that kills your container.

The kernel sees none of that breakdown. It sees one number: the process's resident set size (RSS).

And a Kubernetes memory limit kills on RSS, not on heap use. That is why "the pod was OOM-killed while the heap was at 40 percent" is a real and common incident rather than a contradiction.

Picture it: the pod killed at 40 percent heap

The setup: a container limit of 3 GB, a JVM started with -Xmx2g, and a service that uses 200 threads and direct buffers.

memory pictureruns offline
# container limit 3072 MB (what the kernel kills on)
|-- Java heap (-Xmx2g) ......... 2048 MB --|
|-- metaspace ..................  150 MB --|
|-- code cache .................   50 MB --|
|-- thread stacks 200 x 1 MB ...  200 MB --|
|-- direct buffers .............  400 MB --|
|-- GC structures ..............  150 MB --|
total RSS at full heap           2998 MB   -> ✗ one burst past 3072 MB and the kernel kills it

The trace: the order of events during the incident.

call traceruns offline
1  heap fills to its 2048 MB limit, which is normal                      ✓
2  traffic burst: more threads, more direct buffers                      ✗
3  RSS crosses the 3072 MB limit                                         ✗
4  kernel OOM-killer terminates the JVM; no Java exception, no heap dump ✗

What you see: the platform reports the kill, while the JVM log ends mid-sentence.

consoleruns offline
# illustrative output  (kubectl describe pod)
    Last State:     Terminated
      Reason:       OOMKilled
      Exit Code:    137

Make the invisible visible: native memory tracking splits the process into categories.

jcmd VM.native_memory summaryruns offline
# illustrative output  (-XX:NativeMemoryTracking=summary)
Total: reserved=4100MB, committed=2990MB
-  Java Heap  (reserved=2048MB, committed=2048MB)
-  Class      (committed=150MB)
-  Thread     (committed=200MB)    # 200 threads
-  Code       (committed=50MB)
-  GC         (committed=150MB)
-  Other      (committed=400MB)    # direct buffers

Why: the kernel counts everything the process holds, and the heap is only one part of it.

The fix: leave headroom: size the heap as a fraction of the limit and cap the off-heap parts.

command lineruns offline
# ✅ FIX: heap 60% of the limit, direct memory capped
java -XX:MaxRAMPercentage=60 -XX:MaxDirectMemorySize=256m -jar app.jar

What you see now: the same load stays inside the limit.

jcmd VM.native_memory summaryruns offline
# illustrative output
Total: reserved=3400MB, committed=2480MB     # below the 3072 MB limit
-  Java Heap  (committed=1843MB)
-  Other      (committed=256MB)

The tool for this is native memory tracking. Start the JVM with -XX:NativeMemoryTracking=summary, then run jcmd <pid> VM.native_memory summary — or baseline followed later by summary.diff. You get the process broken down into heap, class, thread, code, GC, symbol, internal and other categories.

A native leak shows up as a category that grows in the diff while the heap stays flat. Four suspects cover most cases:

Finally, the distinction interviewers love: leak versus footprint versus pressure. All three look like "we are using too much memory", and they have three different fixes.

To tell them apart, plot heap use after each collection — the floor, not the peaks.

Reading the shape of the post-collection heap floor.
ShapeWhat it isThe fix
A floor that rises over hours and never comes back down.LeakFind the retained path in a heap dump.
A floor that is high but flat.Footprint — the live set is simply large.Add memory, or move data off-heap.
A steep sawtooth, with a low floor.Pressure — allocation so fast that collections are constant.Allocate less.

The fastest first evidence is two jcmd <pid> GC.class_histogram outputs taken ten minutes apart.

Picture it: leak, footprint and pressure on one chart

The setup: three services, each with the heap used after every collection plotted over time (the floor).

heap floor shapesruns offline
leak       used after GC:   ▁▁▂▂▃▃▄▄▅▅▆▆▇▇██    rising, never recovers      ✗  -> heap dump
footprint  used after GC:   ▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆    high and flat               ✗  -> more memory or off-heap
pressure   used after GC:   ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁    low floor, many collections ✓  -> allocate less

What you see: two class histograms ten minutes apart show which class grows in a leak.

jcmd GC.class_histogramruns offline
# illustrative output
# t = 0 min
 num     #instances         #bytes  class name (module)
   1:        412310       33001480  [B (java.base@21)
   2:         81220       12995200  com.acme.SessionData
# t = 10 min
   1:        419034       33600210  [B (java.base@21)
   2:        640555      102488800  com.acme.SessionData      <- 8x more instances: the leak

For the full catalogue of leak patterns and OutOfMemoryError messages, see Chapter E3's memory section.

See it: the same allocation pattern under G1 and under ZGC

Step-by-step: what GcTour.java does, in plain English
  1. The program keeps a List<byte[]> called retained, which grows steadily to represent the live set (a cache filling up), and allocates far more short-lived garbage on the side to represent request traffic.
  2. gcTotals() walks ManagementFactory.getGarbageCollectorMXBeans() and sums the collection count and total pause time across all collectors, so the program can report, from inside, how much time the JVM spent paused. The bean names differ by collector (G1 Young Generation, G1 Concurrent GC, ZGC Minor Pauses, and so on) and are printed once.
  3. The loop runs ten rounds. Each round allocates 50 000 temporary 4 KB arrays (about 200 MB of garbage) and also appends 2 000 arrays of 16 KB to retained (32 MB of new live data per round, 320 MB by the end). A running checksum touches each temporary array so the JIT cannot remove the allocation.
  4. After each round it prints the round number, the used heap in MB from Runtime, the number of collections so far, and the cumulative pause time in milliseconds, so you can watch pause time grow with the live set under G1 and stay flat under ZGC.
  5. The suggested command lines pin the heap at 1 GB so both runs are comparable, and -Xlog:gc prints one line per collection alongside the program's own output. The second command switches the collector to generational ZGC; the third writes the full log to a file the way a production service should.
GcTour.java · JDK 21+ · java -Xmx1g -Xlog:gc GcTour.java | java -Xmx1g -XX:+UseZGC -Xlog:gc GcTour.java | production: -Xlog:gc*:file=/var/log/app/gc.log:time,uptime,level,tags:filecount=5,filesize=50mruns offline
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;

public class GcTour {

    static final List<byte[]> retained = new ArrayList<>();   // the live set: grows every round
    static long checksum;                                     // keeps the temporary arrays "used"

    record Totals(long count, long millis) {}

    static Totals gcTotals() {
        long count = 0, millis = 0;
        for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
            count  += Math.max(0, gc.getCollectionCount());
            millis += Math.max(0, gc.getCollectionTime());
        }
        return new Totals(count, millis);
    }

    public static void main(String[] args) {
        System.out.println("collectors: " + ManagementFactory.getGarbageCollectorMXBeans().stream().map(GarbageCollectorMXBean::getName).toList());
        for (int round = 1; round <= 10; round++) {
            for (int i = 0; i < 50_000; i++) {              // ~200 MB of garbage per round
                byte[] tmp = new byte[4096];
                tmp[i % 4096] = (byte) i;
                checksum += tmp[(i * 7) % 4096];
            }
            for (int i = 0; i < 2_000; i++) retained.add(new byte[16 * 1024]);   // +32 MB live per round
            Runtime rt = Runtime.getRuntime();
            long usedMb = (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024);
            Totals t = gcTotals();
            System.out.printf("round %2d: live≈%4d MB  used=%4d MB  collections=%3d  total pause=%4d ms%n",
                    round, retained.size() * 16 / 1024, usedMb, t.count(), t.millis());
        }
        System.out.println("checksum " + checksum + " (ignore; it exists so the work cannot be optimised away)");
    }
}

Read the output. Take G1 first, then ZGC, because the contrast is the lesson.

Under G1 the first line names [G1 Young Generation, G1 Concurrent GC, G1 Old Generation]. Then the -Xlog:gc lines interleave with the rounds, looking like this:

[0.412s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 612M->101M(1024M) 4.812ms

Read that as: the fourth collection, a normal young pause, heap went from 612 MB used down to 101 MB used out of 1 024 MB committed, and it took 4.8 ms.

Watch two things as the rounds proceed.

First, the number after the arrow — the heap left after collection — climbs by about 32 MB per round. That is the live set. It is the number a leak investigation cares about, and the number before the arrow is the one people wrongly quote.

Second, the young pauses get slightly longer as more survivors have to be copied. Around round 7 or 8 you will see three lines in sequence: Pause Young (Concurrent Start), then Concurrent Mark Cycle, then Pause Young (Mixed). That is the old generation crossing the occupancy threshold, marking running, and mixed collections beginning to reclaim old regions.

The program's own line shows total pause time rising to perhaps 60–120 ms over the run.

What you see: an illustrative G1 run, matching the description above.

console (G1)runs offline
# illustrative output  (java -Xmx1g -Xlog:gc GcTour.java)
collectors: [G1 Young Generation, G1 Concurrent GC, G1 Old Generation]
[0.412s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 612M->101M(1024M) 4.812ms
round  4: live≈ 125 MB  used= 640 MB  collections=  4  total pause=  21 ms
[1.900s][info][gc] GC(18) Pause Young (Concurrent Start) (G1 Evacuation Pause) 700M->260M(1024M) 9.2ms
[1.910s][info][gc] GC(19) Concurrent Mark Cycle
[2.100s][info][gc] GC(20) Pause Young (Mixed) (G1 Evacuation Pause) 650M->240M(1024M) 11.4ms
round 10: live≈ 312 MB  used= 700 MB  collections= 40  total pause=  96 ms

Under ZGC everything reads differently. The collector list is [ZGC Minor Cycles, ZGC Minor Pauses, ZGC Major Cycles, ZGC Major Pauses]. The log lines say Garbage Collection (Allocation Rate) — a cause, rather than a pause name.

And the cumulative pause total stays in single-digit milliseconds for the whole run. The work did not disappear; it moved out of pauses and into concurrent cycles, where it shows up as CPU instead.

What you see: the same program under ZGC, for a line-by-line comparison with the G1 run.

console (ZGC)runs offline
# illustrative output  (java -Xmx1g -XX:+UseZGC -Xlog:gc GcTour.java)
collectors: [ZGC Minor Cycles, ZGC Minor Pauses, ZGC Major Cycles, ZGC Major Pauses]
[0.500s][info][gc] GC(2) Garbage Collection (Allocation Rate) ...      # a cause, not a pause name
round  4: live≈ 125 MB  used= 700 MB  collections=  4  total pause=   1 ms
round 10: live≈ 312 MB  used= 780 MB  collections= 12  total pause=   3 ms

One experiment is worth running. Shrink the heap to -Xmx400m under ZGC and you will eventually see Allocation Stall (main) lines. That is the collector telling you it could not keep up — and it is the first line to search for when a ZGC service's latency spikes.

🧠 Brain power

Before reading on: a service on G1 with a 4 GB heap and -XX:G1HeapRegionSize left at its default (2 MB for that heap size) reads uploaded files into byte[] buffers of 1.5 MB each, a few thousand per minute. GC logs show a young collection every two seconds even though used heap never exceeds 35 percent. What is happening, and which single flag fixes it?

Reveal the answer

Each 1.5 MB array is larger than half of a 2 MB region, so G1 treats it as humongous and gives it a whole region of its own.

That wastes 0.5 MB per buffer. More importantly, it allocates the array outside the thread-local buffers, directly in old space.

Humongous allocations also count toward the marking threshold, so in G1's accounting they trigger collections early. You can confirm it in the log: -Xlog:gc+humongous lines, or a G1 Humongous Allocation cause on the pauses.

There are two fixes, and a good answer gives both.

  • The one-flag fix: -XX:G1HeapRegionSize=8m, or 4 MB. Regions must be a power of two between 1 and 32 MB. This makes a 1.5 MB array an ordinary young allocation that dies cheaply.
  • The better long-term fix: stream uploads through a reused buffer instead of materialising each file. That removes the allocation entirely.

And the answer to give in the room adds one more thing: how you would confirm the diagnosis in the log before changing anything.

Quick reference — memory and garbage collection

object header
12 bytes on 64-bit HotSpot: an 8-byte mark word (hash, age, lock state) plus a 4-byte class pointer. Compact headers (JDK 25+, default in 27) cut it to 8 and save 10–20% of heap.
compressed oops
4-byte references, available while the heap is ≤ 32 GB. Past that they double, and a 40 GB heap can hold less live data than a 31 GB one.
TLAB
Each thread's private slice of eden. new is a pointer bump — no lock, ~10 instructions. Allocation rate is what drives young-collection frequency.
generational hypothesis
Most objects die young. Cost of it: a write barrier on every reference store, feeding a card table or remembered set.
G1 vocabulary
Regions (1–32 MB, ~2048 of them) · young collection · concurrent marking · mixed collections ("garbage first") · humongous (> half a region) · evacuation failure / "to-space exhausted" → full GC.
ZGC
Coloured pointers plus a load barrier on every reference read. Sub-millisecond pauses at any heap size. Failure mode is an allocation stall, not a long pause. Needs 20–30% headroom.
Why lowering MaxGCPauseMillis backfires
G1 meets the goal by shrinking the young gen. Smaller young gen → more frequent collections → premature promotion → old gen fills faster → worse tail.
leak vs footprint vs pressure
Plot the heap floor after collection. Rising floor = leak (heap dump). High flat floor = footprint (more memory, or off-heap). Steep sawtooth = pressure (allocate less).
Why the pod dies at 40% heap
Kubernetes kills on RSS, and RSS includes metaspace, code cache, thread stacks, direct buffers and GC structures. Diagnose with -XX:NativeMemoryTracking=summary plus jcmd VM.native_memory.
Reading a GC log line
612M->101M(1024M) 4.812ms — before, after, committed, duration. The number after the arrow is the live set, and it is the one that matters.

05 · The primerModern Concurrency: What a Virtual Thread Is Made Of, and Where It Still Gets Stuck

A virtual thread is a stack that lives in the heap instead of in the kernel, run by a small pool of real threads. That makes threads cheap enough to have a million of them — until one of them blocks without letting go of the real thread underneath it.

A team flips one property — spring.threads.virtual.enabled=true — on a service that fans out to a dozen slow partner APIs. In the load test, throughput triples.

In production, on the first busy morning, the service stalls. CPU at 15 percent. Every request timing out. And a thread dump that shows nothing useful, because the threads that matter are not in it.

They roll back, and conclude that virtual threads "do not work".

They do work. The team hit two well-documented edges, and both are visible in advance if you know what a virtual thread actually is.

This chapter takes it apart. The basics — platform threads, the monitor, executors and CompletableFuture — live in Chapter E3 and are assumed here.

Bridge: a thread is a stack plus something that runs it

A platform thread is a one-to-one wrapper around an operating-system thread. The kernel owns its stack, typically a 1 MB reservation. The kernel schedules it. And blocking it in a socket read parks the kernel thread itself.

That is why a service cannot have a hundred thousand of them, and why you learned to size pools in the first place.

A virtual thread, final since JDK 21 (JEP 444), separates those two halves.

Its stack lives in the Java heap as ordinary objects. It is run by a small pool of platform threads called carriers.

Here is what happens when one blocks. The JVM copies its stack frames off the carrier into a heap object called a stack chunk, and hands the carrier to another virtual thread. When the blocking operation completes, the frames are copied back onto some carrier and it continues where it left off.

The numbers are what make this matter. Creating one costs about a microsecond and around a kilobyte, so a million of them fit.

Which means the "one thread per request" style you already know becomes affordable again for I/O-bound work.

The mechanism: continuations, carriers, and the scheduler

The heap-stack trick is called a continuation — internally jdk.internal.vm.Continuation. It is a piece of code that can be paused at a point and resumed later, with its local variables intact.

So the whole of a virtual thread is: a continuation plus a scheduler.

The scheduler is a ForkJoinPool in first-in-first-out mode. Its parallelism defaults to the number of available processors (-Djdk.virtualThreadScheduler.parallelism), and its maximum size is 256 (maxPoolSize).

Two words are worth fixing now, because everything else uses them. Mounting is putting a virtual thread on a carrier. Unmounting is taking it off.

Every blocking operation in the JDK was reworked around those two. Instead of parking the carrier, a blocking call registers interest in the event — a socket becoming readable, a lock becoming free, a timer expiring — then unmounts and lets the carrier go.

The implementations differ, but the outcome is the same. Sockets use a small set of poller threads under the hood. Thread.sleep uses a timer. ReentrantLock, BlockingQueue, Semaphore and everything built on LockSupport.park all unmount cleanly.

Picture it: one virtual thread, mounted and unmounted

The setup: a virtual thread that does some work, waits for a socket read, then does more work.

Handler.javaruns offline
Thread.ofVirtual().start(() -> {
    String request = parse();                 // runs on a carrier
    String reply = partnerApi.call(request);  // blocks on a socket: unmounts here
    respond(reply);                           // continues, maybe on another carrier
});

Make the invisible visible: one row per moment: which carrier runs what, and where the virtual thread's frames live.

mount and unmount timelineruns offline
time  carrier-1                     VT#1 (where are its frames?)
t0    mount VT#1, run parse()       on carrier-1's stack                         ✓
t1    VT#1 starts the socket read   registers with the poller
t2    unmount VT#1                  copied into a heap stack chunk (~1 KB)       ✓ carrier is free
t3    mount VT#2, run its code      VT#1 waits in the heap, costing no carrier   ✓
t4    poller: reply has arrived     VT#1 handed to the scheduler's queue
t5    carrier-3 mounts VT#1         frames copied back; continues after call()   ✓

What you see: a virtual thread prints the carrier it is mounted on, so a change of worker is the visible trace of t2 to t5.

consoleruns offline
# illustrative output
before sleep: VirtualThread[#31]/runnable@ForkJoinPool-1-worker-1
after sleep:  VirtualThread[#31]/runnable@ForkJoinPool-1-worker-3  (remounted on another carrier)

One case could not be fixed. File I/O cannot be made non-blocking on most operating systems, so for those calls the JVM temporarily adds a carrier to compensate.

Pinning is the name for a virtual thread that blocks without unmounting, holding its carrier hostage.

Do the arithmetic and the danger is obvious. With a parallelism of 8, eight pinned virtual threads freeze the entire scheduler. That is the production stall in the opener.

In JDK 21 the big pinning cause was synchronized. A virtual thread that blocked inside a synchronized block, or in Object.wait(), stayed on its carrier — because the monitor implementation tied the lock to the carrier thread.

JDK 24 fixed that with JEP 491, by rewriting monitors to be virtual-thread-aware. As of JDK 24 and later, synchronized and Object.wait unmount like everything else.

Two things still pin, as of August 2026:

The evidence is a JFR event, jdk.VirtualThreadPinned, which since JDK 24 records both the reason and the carrier.

Picture it: pinning, with and without JEP 491

The setup: eight virtual threads each sleep 200 ms inside a synchronized block, using one lock per task so that only the carrier is shared. The scheduler is limited to one carrier.

Pinning.javaruns offline
// java -Djdk.virtualThreadScheduler.parallelism=1 Pinning.java
static final Object[] LOCKS = new Object[8];
static { for (int i = 0; i < 8; i++) LOCKS[i] = new Object(); }

for (int i = 0; i < 8; i++) {
    final int n = i;
    Thread.startVirtualThread(() -> {
        synchronized (LOCKS[n]) {                 // ❌ TRAP on JDK 21: blocking in here pins the carrier
            try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        }
    });
}

Make the invisible visible: who owns the single carrier over time.

carrier timeline (JDK 21)runs offline
time      carrier-1                          VT#2 .. VT#8
0 ms      VT#1 enters synchronized, sleeps   waiting in the scheduler queue
          PINNED: carrier held, idle         cannot mount                        ✗
200 ms    VT#1 leaves the block              VT#2 mounts, sleeps, pinned again   ✗
...       eight sleeps run one after another
1600 ms   VT#8 done                          8 x 200 ms
carrier timeline (JDK 24 and later)runs offline
time      carrier-1                          VT#2 .. VT#8
0 ms      VT#1 sleeps inside synchronized    sleep unmounts VT#1                 ✓
0 ms      carrier-1 runs VT#2, then VT#3...  each one sleeps and unmounts        ✓
200 ms    all eight wake, finish             about 200 ms in total

What you see: on JDK 21 you can ask the JVM to print a stack trace whenever a pinned thread blocks.

consoleruns offline
# illustrative output  (java -Djdk.tracePinnedThreads=full ... on JDK 21)
Thread[#22,ForkJoinPool-1-worker-1,5,CarrierThreads]
    java.base/java.lang.VirtualThread$VThreadContinuation.onPinned(VirtualThread.java:183)
    ...
    java.base/java.lang.Thread.sleep(Thread.java:509)
    Pinning.lambda$main$0(Pinning.java:11) &lt;== monitors:1

Why: on JDK 21 the monitor is tied to the carrier thread, so a virtual thread that blocks while holding it cannot leave the carrier.

The fix: on JDK 21 use a ReentrantLock in your own code; on JDK 24 or later no change is needed for synchronized.

PinningFixed.javaruns offline
static final ReentrantLock[] LOCKS = new ReentrantLock[8];   // one lock per task, created up front

ReentrantLock lock = LOCKS[n];
lock.lock();                                      // ✅ FIX: a blocked ReentrantLock holder can unmount
try { Thread.sleep(200); } finally { lock.unlock(); }

What you see now: no pinned-thread trace, and the sleeps overlap.

consoleruns offline
# illustrative output
(no "onPinned" trace; total time about 200 ms with eight locks)

The second edge the team hit was simpler, and it has nothing to do with pinning. Their platform-thread pool of 200 had been acting as a throttle on the database. Removing it let 20 000 virtual threads pile onto a 20-connection pool.

Which is the sentence to remember about all of this. Virtual threads do not make anything faster. They let more requests wait at once — and the next bottleneck is always whatever those requests are waiting for.

Picture it: 20 000 virtual threads and a 20-connection pool

The setup: the old code ran at most 200 requests at a time; the virtual-thread version runs as many as arrive.

Handler.javaruns offline
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {   // was: newFixedThreadPool(200)
    for (Request r : requests) exec.submit(() -> db.query(r));   // ❌ TRAP: pool of 20 connections behind this
}

Make the invisible visible: who holds a connection and who waits, before and after.

memory pictureruns offline
before:  200 threads  ->  20 hold a connection, 180 wait         (the pool was the throttle)
after:   20 000 VTs   ->  20 hold a connection, 19 980 wait      ✗

capacity  = 20 connections / 0.05 s per query = 400 queries per second
last wait = 19 980 / 400 per second          = about 50 s       ✗ longer than every timeout

What you see: connection-pool timeouts and a service that looks idle.

consoleruns offline
# illustrative output
HikariPool-1 - Connection is not available, request timed out after 30000ms.
CPU 15 percent, requests timing out

Why: virtual threads let more requests wait at once. They do not add database capacity.

The fix: limit the resource, not the threads.

Limited.javaruns offline
static final Semaphore DB = new Semaphore(20);                   // ✅ FIX: matches the pool

exec.submit(() -> { DB.acquire(); try { return db.query(r); } finally { DB.release(); } });

What you see now: waiting is bounded by the semaphore and shed at the edge, not discovered at the pool timeout.

consoleruns offline
# illustrative output
20 queries in flight, the rest queue at the semaphore; pool timeouts: 0
heap: virtual threads = stack chunks (~1 KB each, hundreds of thousands) VT #1 parked VT #2 parked VT #3 runnable VT #4 parked VT #5 runnable … VT #99 999 scheduler: ForkJoinPool, FIFO, parallelism = CPUs, max 256 carriers mount unmount on block carrier (platform) threads, one per CPU carrier 1: running VT #3 → socket read → registers with poller, unmounts, takes VT #5 carrier 2: running VT #7 → ReentrantLock.lock() blocks → unmounts → takes VT #8 carrier 3: VT #9 blocks inside a native (JNI/FFM) frame → PINNED carrier is held; JFR jdk.VirtualThreadPinned fires with the reason carrier 4: VT #12 in synchronized + Object.wait → unmounts on JDK 24+ (JEP 491), pinned on 21 the next ceiling is whatever the threads wait for: a 20-connection pool serves 20 requests at a time no matter how many threads wait
Fig. E2.4 — A virtual thread is a heap-resident stack that is mounted on a carrier only while it runs. Blocking normally unmounts it; the marked case, blocking under a native frame, pins the carrier, and enough pinned threads freeze the scheduler.

Structured concurrency and scoped values: the two companions

Cheap threads change how you write fan-out. Two companion features exist to make that style safe, and interviewers ask about both — partly to see whether you track what is final and what is still preview.

Structured concurrency is a rule before it is an API: a set of tasks started together should finish together, and be owned by one place in the code — the way a try block owns its resources.

The API is java.util.concurrent.StructuredTaskScope. You fork subtasks inside a scope, then join them with a policy called a Joiner: all must succeed, the first success wins, or collect everything.

The guarantee is what makes it worth using. When the scope closes, every subtask has either finished or been cancelled. No thread leaks, and the thread dump shows the tree rather than a flat list.

Its status, as of August 2026, is the detail to get right in an interview. It was a fifth preview in JDK 25 (JEP 505), a sixth in JDK 26 (JEP 525), and a seventh — still preview — is in JDK 27 (JEP 533). So it needs --enable-preview on every JDK you can run today.

Picture it: structured concurrency cancels the sibling

The setup: two subtasks in parallel; one of them fails.

Fanout.javaruns offline
// JDK 25 shape, preview: java --enable-preview --source 25 Fanout.java
try (var scope = StructuredTaskScope.open()) {
    StructuredTaskScope.Subtask<String> user   = scope.fork(() -> fetchUser(id));
    StructuredTaskScope.Subtask<String> orders = scope.fork(() -> fetchOrders(id));   // throws
    scope.join();                                // ✅ waits for both, or cancels the rest on failure
    return user.get() + orders.get();
}

The trace: the same failure with a plain executor and with a scope.

call traceruns offline
plain ExecutorService                          StructuredTaskScope
1  submit fetchUser, submit fetchOrders        1  fork fetchUser, fork fetchOrders
2  fetchOrders throws                          2  fetchOrders throws
3  caller sees the failure at get()            3  scope cancels fetchUser (interrupt)     ✓
4  fetchUser keeps running: leaked thread  ✗   4  join() returns; scope closes with
                                                  no subtask left running                 ✓

Scoped values, by contrast, are final in JDK 25 (JEP 506).

A ScopedValue is an immutable, per-thread value bound for the duration of a block — ScopedValue.where(REQUEST_ID, id).run(...). Everything called inside can read it, and subtasks forked in a structured scope inherit it automatically.

It exists to replace ThreadLocal for request context, and the reason is arithmetic. A ThreadLocal is mutable and lives as long as its thread. With a million virtual threads, a million copies of a per-thread cache is a memory problem.

Picture it: a million copies of a per-thread value

The setup: a per-thread cache of an expensive object, and the scoped-value alternative.

Context.javaruns offline
static final ThreadLocal<SimpleDateFormat> FMT =
    ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));   // ❌ TRAP: one copy per thread

static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance(); // ✅ FIX: immutable, bound for a block
ScopedValue.where(REQUEST_ID, id).run(() -> handle());                    // inside: REQUEST_ID.get()
// outside the block: REQUEST_ID.get() throws NoSuchElementException

Make the invisible visible: the arithmetic of one copy per virtual thread.

memory arithmeticruns offline
formatter cached per thread        50 KB
platform threads (200)             200 x 50 KB       =  10 MB      ✓
virtual threads (1 000 000)        1 000 000 x 50 KB =  50 GB      ✗
shared immutable formatter         1 x 50 KB         =  50 KB      ✓

See it: throughput, carrier switching, and the JDK 21 versus 24 pinning difference

Step-by-step: what LoomTour.java does, in plain English
  1. timed(String label, Runnable body) measures how long body takes and prints it in milliseconds; every demo goes through it so the numbers line up.
  2. sleepers(ExecutorService pool, int n) submits n tasks that each sleep for 100 ms (standing in for a slow HTTP call) and waits for all of them by closing the executor, which since JDK 19 blocks until submitted tasks finish. It is called twice: once with a fixed pool of 200 platform threads, and once with Executors.newVirtualThreadPerTaskExecutor(), both for 10 000 tasks.
  3. carrierSwitch() starts one virtual thread that prints Thread.currentThread(), sleeps, and prints it again. The toString of a virtual thread includes the carrier it is mounted on (@ForkJoinPool-1-worker-3), so if the second line shows a different worker, you have watched an unmount and a remount with your own eyes. It may also be the same worker; the program says so either way.
  4. pinningProbe() starts 8 virtual threads that each enter a synchronized block on a shared lock and sleep 200 ms inside it. With the scheduler's parallelism forced to 1 by the command-line property, JDK 21 pins the single carrier inside the block, so the eight sleeps serialise and the demo takes about 1 600 ms; on JDK 24 or later, JEP 491 lets the thread unmount inside synchronized, and the same code finishes in about 200 ms. The program prints the JDK version alongside so the reader can match number to cause.
  5. main runs the four demos in order. The suggested command sets jdk.virtualThreadScheduler.parallelism=1 so the pinning difference is unmistakable; without it, the eight threads spread over several carriers and the difference is smaller.
LoomTour.java · JDK 21+ · java -Djdk.virtualThreadScheduler.parallelism=1 LoomTour.java (run on 21 and on 24+ to see JEP 491)runs offline
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.CountDownLatch;

public class LoomTour {

    static void timed(String label, Runnable body) {
        long t0 = System.nanoTime();
        body.run();
        System.out.printf("%-42s %6d ms%n", label, (System.nanoTime() - t0) / 1_000_000);
    }

    static void sleepers(ExecutorService pool, int n) {
        try (pool) {                                        // close() waits for every submitted task
            for (int i = 0; i < n; i++) pool.submit(() -> { Thread.sleep(100); return null; });
        }
    }

    static void carrierSwitch() throws InterruptedException {
        Thread vt = Thread.ofVirtual().unstarted(() -> {
            String before = Thread.currentThread().toString();
            try { Thread.sleep(50); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
            String after = Thread.currentThread().toString();
            System.out.println("before sleep: " + before);
            System.out.println("after sleep:  " + after + (before.equals(after) ? "  (same carrier this time)" : "  (remounted on another carrier)"));
        });
        vt.start();
        vt.join();
    }

    static final Object LOCK = new Object();

    static void pinningProbe() throws InterruptedException {
        CountDownLatch done = new CountDownLatch(8);
        for (int i = 0; i < 8; i++) {
            Thread.startVirtualThread(() -> {
                synchronized (LOCK) {                       // JDK 21: pins the carrier while sleeping; JDK 24+: unmounts
                    try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
                }
                done.countDown();
            });
        }
        done.await(10, TimeUnit.SECONDS);
    }

    public static void main(String[] args) throws Exception {
        System.out.println("JDK " + Runtime.version() + ", scheduler parallelism = " + System.getProperty("jdk.virtualThreadScheduler.parallelism", "(default = CPUs)"));
        timed("10 000 × sleep(100) on 200 platform threads", () -> sleepers(Executors.newFixedThreadPool(200), 10_000));
        timed("10 000 × sleep(100) on virtual threads",      () -> sleepers(Executors.newVirtualThreadPerTaskExecutor(), 10_000));
        carrierSwitch();
        timed("8 virtual threads sleeping inside synchronized", () -> { try { pinningProbe(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } });
    }
}

Read the output. There are three things in it: the throughput comparison, the carrier switch, and the version test.

The first timed line says about 5 050 ms. That is arithmetic you can check: 10 000 tasks of 100 ms on 200 threads is 50 rounds of 100 ms, plus overhead.

The second says about 130 ms. All 10 000 virtual threads sleep at once on a single carrier, because sleeping unmounts them and a timer wakes them.

That 40× ratio is the whole promise of virtual threads. And note carefully what it is not: no task got faster. More of them waited at the same time.

Next, the carrier lines. They look like before sleep: VirtualThread[#31]/runnable@ForkJoinPool-1-worker-1.

With parallelism 1, the "after" line names the same worker. On a default run you will often see worker-1 become worker-3 — the visible trace of an unmount and a remount.

The last line is the version test, and it is the one worth showing your team.

On JDK 21 it prints about 1 600 ms. The first virtual thread entered the block and slept while pinned to the only carrier, so the other seven could not even start until it finished. The sleeps ran one after another.

On JDK 24 or 25 the same line prints about 200 ms, because JEP 491 lets a virtual thread unmount while holding a monitor and reacquire it when it wakes.

So if your production JDK is 21, that 1 600 is the number to put in front of the team before enabling virtual threads under a framework full of synchronized.

The alternative fixes on 21 are two: use ReentrantLock in your own code, and take a JFR recording with jdk.VirtualThreadPinned enabled to find the third-party ones.

What you see: an illustrative JDK 21 run of LoomTour with the command shown in its header. The last line is the one that changes between JDK 21 and later releases.

consoleruns offline
# illustrative output  (JDK 21, parallelism = 1)
JDK 21.0.5, scheduler parallelism = 1
10 000 × sleep(100) on 200 platform threads    5050 ms
10 000 × sleep(100) on virtual threads          130 ms
before sleep: VirtualThread[#31]/runnable@ForkJoinPool-1-worker-1
after sleep:  VirtualThread[#31]/runnable@ForkJoinPool-1-worker-1  (same carrier this time)
8 virtual threads sleeping inside synchronized 1600 ms

There are no dumb questions

If virtual threads are so cheap, why not run CPU-bound work on them too?
Because there is no time-slicing between virtual threads. A virtual thread keeps its carrier until it blocks or finishes, so a long computation on one of them delays every other virtual thread queued for that carrier, and eight of them delay everything. CPU-bound work belongs on a fixed pool of platform threads sized to the cores, and the two kinds can hand results to each other through ordinary futures or queues.
Should I pool virtual threads to limit how many run at once?
No. Pooling them defeats the point and reintroduces the queueing you removed. Limit the resource instead: a Semaphore with 50 permits around the outbound call, a connection pool with a fixed maximum, a bounded queue in front of the consumer. The thread is free; the thing it waits for is not, and that is what the limit should protect.
Why does my thread dump not show virtual threads?
jstack and jcmd Thread.print list platform threads only, so you see carriers running "something" and nothing about the thousands of parked virtual threads. Use jcmd <pid> Thread.dump_to_file -format=json /tmp/threads.json, which includes every virtual thread and, if you used structured concurrency, the parent-child tree. For "which virtual threads are stuck where", a JFR recording with jdk.VirtualThreadPinned and jdk.ThreadPark events is the better tool.
Is ThreadLocal broken with virtual threads?
It works exactly as before; each virtual thread gets its own value. The problems are cost and lifetime: a ThreadLocal that caches a 50 KB formatter per thread now does so a million times, and a value set in a request thread is thrown away with the thread instead of being reused. Prefer ScopedValue (final in JDK 25) for request context, and share expensive immutable objects instead of caching them per thread.

Quick reference — virtual threads

virtual thread
A stack that lives in the Java heap, run by a small pool of platform threads. ~1 microsecond and ~1 KB to create, so a million fit. Final since JDK 21 (JEP 444).
carrier
The real platform thread a virtual thread runs on. The scheduler is a FIFO ForkJoinPool; parallelism defaults to the CPU count, max size 256.
mount / unmount
Putting a virtual thread on a carrier, and taking it off. A blocking call registers interest in the event, unmounts, and releases the carrier.
continuation
Code that can be paused and resumed with its locals intact. A virtual thread is a continuation plus a scheduler — that is the whole definition.
pinning
Blocking without unmounting, holding the carrier hostage. Eight pinned threads freeze a parallelism-8 scheduler.
What still pins (Aug 2026)
A native frame on the stack (JNI or FFM) that then blocks, and a class initialiser that blocks. synchronized stopped pinning in JDK 24 (JEP 491). Evidence: the jdk.VirtualThreadPinned JFR event.
The trap that is not pinning
The old thread pool was throttling something downstream. Remove it and 20 000 virtual threads hit a 20-connection pool.
The one-sentence summary
Virtual threads do not make anything faster. They let more requests wait at once — so the next bottleneck is whatever they are waiting for.
Structured concurrency
StructuredTaskScope: fork subtasks, join with a Joiner, and every subtask is finished or cancelled when the scope closes. Still preview in JDK 27 (JEP 533) — needs --enable-preview.
Scoped values
Final in JDK 25 (JEP 506). An immutable per-thread value bound for a block, inherited by forked subtasks. Replaces ThreadLocal for request context.

06 · The primerThe Modern Language and Platform: Records, Sealed Types, Pattern Matching, Gatherers, FFM, Modules

The features added since Java 8 are not syntax sugar. Each one moves an error from production to compile time, or moves work out of your code and into the runtime where it is done once and done right.

Here is a code review from a JDK 8-era codebase running on JDK 21.

A payment result is a class with a status enum and five nullable fields, three of which are meaningful only for one status. Every consumer has an if (status == DECLINED) chain.

Last quarter a new status, PENDING_REVIEW, was added. Two of the nine consumers were missed, and the bug reached production.

The same domain, written with the language as it exists now, is a sealed interface with three records — and the compiler refuses to build the two consumers that forgot the new case.

That refusal is the point of most of what this chapter covers. The modern features are not syntax sugar. They move errors from production to compile time, or move work out of your code into the runtime where it is done once and done right.

The missed consumer, step by step

The setup: the JDK 8-era result class: one shape for every outcome, with a status enum deciding which fields mean anything.

JDK 8 style: PaymentResult.javaruns offline
class PaymentResult {
    enum Status { APPROVED, DECLINED, PENDING_REVIEW }  // PENDING_REVIEW added last quarter
    Status status;
    String id;          // only meaningful when APPROVED
    Long amountCents;   // only meaningful when APPROVED
    String reason;      // only meaningful when DECLINED
    String queue;       // only meaningful when PENDING_REVIEW
}

static String describe(PaymentResult r) {
    if (r.status == Status.APPROVED) return "ok " + r.id;
    if (r.status == Status.DECLINED) return "no: " + r.reason;
    return "unknown";   // ❌ TRAP: PENDING_REVIEW lands here and nothing complains
}

Make the invisible visible: one object, with three of its five fields silently meaningless.

memory pictureruns offline
stack                    heap
-----                    ----
r  ───────────────────►  PaymentResult
                           status      ──► PENDING_REVIEW
                           id          ──► null
                           amountCents ──► null
                           reason      ──► null
                           queue       ──► "fraud-team"

The trace: last quarter, nine consumers each had to learn about the new status.

trace of the releaseruns offline
consumers 1-7   updated to handle PENDING_REVIEW        ✓ compiles, correct
consumer 8      if-chain ends in "unknown"              ✗ compiles, wrong
consumer 9      if-chain ends in "unknown"              ✗ compiles, wrong
build           green                                   ✗ nothing flagged the two misses
production      customers see "unknown"                 ✗ bug reaches users

Why: the status is ordinary runtime data, so the compiler has no way to know the set of outcomes is closed or that a consumer forgot one.

The fix: a sealed interface with one record per outcome, and consumers written as a switch with no default.

sealed version: PaymentResult.javaruns offline
sealed interface PaymentResult permits Approved, Declined, Pending {}
record Approved(String id, long amountCents) implements PaymentResult {}
record Declined(String reason) implements PaymentResult {}
record Pending(String queue) implements PaymentResult {}   // ✅ FIX: the new case is a new type

static String describe(PaymentResult r) {
    return switch (r) {
        case Approved a -> "ok " + a.id();
        case Declined d -> "no: " + d.reason();
        // ❌ forgot Pending, and there is no default
    };
}

What you see now: the build refuses, at the exact line of each consumer that forgot the case.

consoleruns offline
# illustrative output
Billing.java:41: error: the switch expression does not cover all possible input values
        return switch (r) {
               ^
Refunds.java:88: error: the switch statement does not cover all possible input values
2 errors

Versions matter in interviews, so every feature below carries its JDK number and its status as of August 2026. The syntax basics of records and sealed types are in Chapter E1; here we go into what they generate and what they change.

Records and sealed hierarchies: data with a closed shape

A record (final since JDK 16) is a class whose state is exactly its declared components. The compiler generates the private final fields, a canonical constructor, the accessors, and equals, hashCode and toString.

Those last three are not written out as bytecode. They are invokedynamic call sites, bootstrapped by java.lang.runtime.ObjectMethods.

So a record with twenty components costs one small method each, generated at first use rather than at compile time.

A compact canonical constructor — written without a parameter list — is where validation and normalisation go. It runs before the fields are assigned.

Three properties of records are worth holding on to, because each answers a common question:

What the compiler generates for a record

The setup: a record with a compact constructor that validates.

Range.javaruns offline
record Range(int lo, int hi) {
    Range {                                   // compact canonical constructor
        if (lo > hi) throw new IllegalArgumentException("lo > hi");
    }
}

Make the invisible visible: the class you did not have to write, shown as the code the compiler effectively produces.

what the compiler generatesruns offline
final class Range extends java.lang.Record {
    private final int lo;
    private final int hi;

    Range(int lo, int hi) {                   // canonical constructor, same access as the record
        if (lo > hi) throw new IllegalArgumentException("lo > hi");  // your compact body runs FIRST
        this.lo = lo;                         // field assignments are appended automatically
        this.hi = hi;
    }
    public int lo() { return lo; }
    public int hi() { return hi; }

    public final String  toString()          { /* invokedynamic ObjectMethods.bootstrap */ }
    public final int     hashCode()          { /* invokedynamic ObjectMethods.bootstrap */ }
    public final boolean equals(Object o)    { /* invokedynamic ObjectMethods.bootstrap */ }
}

What you see: javap -c Range shows a toString that is one invokedynamic and a return, with no field-by-field code.

javap -cruns offline
public final java.lang.String toString();
  Code:
     0: aload_0
     1: invokedynamic #17,  0   // InvokeDynamic #0:toString:(LRange;)Ljava/lang/String;
     6: areturn

The shallow-immutability trap

The setup: a record whose component is an array.

Batch.javaruns offline
record Batch(int[] ids) {}

var b = new Batch(new int[] {1, 2});
b.ids()[0] = 99;                                   // ❌ TRAP: the record is "immutable", the array is not
System.out.println(Arrays.toString(b.ids()));
System.out.println(new Batch(new int[] {1}).equals(new Batch(new int[] {1})));

Make the invisible visible: the record owns a reference, not the array; anyone holding the array can change it.

memory pictureruns offline
stack                 heap
-----                 ----
b ───────────────►  Batch              int[]
                      ids ───────────►  [ 99 | 2 ]
caller's array ─────────────────────────┘   (same array object, shared)

What you see: the "immutable" data changed, and two records with equal-looking arrays are not equal.

consoleruns offline
[99, 2]
false

Why: a record is shallowly immutable, and its generated equals compares the array references with equals, which for arrays means identity.

The fix: copy on the way in and on the way out, and override equals if you need content equality.

Batch.java (fixed)runs offline
record Batch(int[] ids) {
    Batch { ids = ids.clone(); }                   // ✅ FIX: defensive copy in the compact constructor
    public int[] ids() { return ids.clone(); }     // ✅ FIX: defensive copy in the accessor
}

What you see now: the same program leaves the data untouched.

consoleruns offline
[1, 2]
false      // still false: arrays compare by identity, so override equals/hashCode for content equality

A sealed interface or class (final since JDK 17) lists its permitted subtypes with permits. Each of those must then be final, sealed, or explicitly non-sealed.

That closed list is the whole mechanism. It is what lets the compiler check exhaustiveness.

The setup: one sealed interface with two permitted subtypes, and two classes that try to join the hierarchy.

Shape.javaruns offline
sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}     // records are implicitly final
final class Square implements Shape {}
class Oval implements Shape {}                  // ❌ not listed in permits
final class Triangle implements Shape {}        // ❌ same problem, even though it is final

What you see: which declarations the compiler accepts.

Pattern matching for switch: the compiler counts the cases

Pattern matching for switch and record patterns are both final in JDK 21 (JEP 441 and JEP 440). A switch can now do five things it could not before:

Now the safety net. When the selector is a sealed type and the switch has no default, the compiler requires every permitted subtype to be covered. Leave one out and the build fails.

Which leads directly to the senior advice: do not write default on a sealed switch. A default silently swallows exactly the case the compiler would otherwise have caught for you.

There is one runtime edge to know about. If a library adds a new permitted subtype and your already-compiled exhaustive switch meets it, the JVM throws MatchException. So changing a sealed set is a breaking change for consumers.

What the compiler generates for a pattern switch

The setup: the exhaustive switch from the opener, with a record pattern and a guard.

Describe.javaruns offline
static String describe(PaymentResult r) {
    return switch (r) {
        case Approved(var id, var cents) when cents > 10_000 -> "big " + id;
        case Approved a                                      -> "ok " + a.id();
        case Declined d                                      -> "no: " + d.reason();
        case Pending p                                       -> "queued " + p.queue();
    };
}

Make the invisible visible: the switch is not a chain of instanceof tests you can see. It becomes one invokedynamic that answers "which case index matches", plus a hidden default that throws.

what the compiler generates (simplified)runs offline
Object sel = Objects.requireNonNull(r);   // null selector -> NullPointerException (no case null)
int restart = 0;
while (true) {
    switch (invokedynamic typeSwitch(sel, restart)) {   // SwitchBootstraps.typeSwitch, labels: Approved, Approved, Declined, Pending
        case 0: /* destructure Approved(id, cents); if !(cents > 10_000) { restart = 1; continue; } */ return "big " + id;
        case 1: return "ok " + ((Approved) sel).id();
        case 2: return "no: " + ((Declined) sel).reason();
        case 3: return "queued " + ((Pending) sel).queue();
        default: throw new MatchException(null, null);  // the case the compiler proved cannot happen
    }
}

The trace: what happens when a default is added versus left out, after a fourth permitted type, Escalated, is added.

call traceruns offline
add record Escalated to permits ...
  switch WITHOUT default   -> recompile                  ✓ error: switch does not cover all possible input values
  switch WITH default      -> recompile                  ✗ compiles; Escalated silently takes the default branch

What you see: the runtime edge: a library jar adds Escalated, and your jar, compiled against the old library, is not recompiled.

consoleruns offline
# illustrative output
Exception in thread "main" java.lang.MatchException
    at Billing.describe(Billing.java:12)
    at Billing.main(Billing.java:30)

Why: the compiler wrote "any other type" as a throw because, at compile time, there was no other type. The new subtype arrived after.

The fix: treat adding a permitted subtype as a breaking change: bump the library version, and recompile the consumers. Do not add default to hide it.

Sequenced collections and stream gatherers

Two library additions changed everyday code.

Sequenced collections (JDK 21, JEP 431) added SequencedCollection, SequencedSet and SequencedMap above List, Deque, LinkedHashSet, LinkedHashMap and TreeMap.

They bring getFirst(), getLast(), addFirst(), removeLast() and reversed(). So "the last element" no longer needs list.get(list.size() - 1), and a LinkedHashMap can finally be iterated backwards.

The setup: reading and reversing a list the old way and the JDK 21 way.

SequencedDemo.javaruns offline
List<String> xs = new ArrayList<>(List.of("a", "b", "c"));
String oldLast = xs.get(xs.size() - 1);   // before 21: index arithmetic, throws on an empty list
String last    = xs.getLast();            // JDK 21
List<String> v = xs.reversed();           // a VIEW, not a copy
xs.add("d");                              // ❌ TRAP: if you expected a snapshot, this changes v too
System.out.println(v);
List.<String>of().getFirst();             // NoSuchElementException on an empty collection

Make the invisible visible: reversed() does not copy. It is a second window onto the same elements.

memory pictureruns offline
xs ──►  ArrayList  [ a | b | c | d ]
                      ▲
v  ──►  reversed view ┘   reads the same array from the end: d, c, b, a

What you see: the view saw the later add.

consoleruns offline
[d, c, b, a]

Stream gatherers (final in JDK 24, JEP 485) are the missing half of the Stream API. Collectors let you write custom terminal operations; gatherers let you write custom intermediate ones.

A Gatherer has four parts, three of them optional:

The built-ins in java.util.stream.Gatherers cover the common cases: windowFixed(n), windowSliding(n), fold, scan, and mapConcurrent(max, fn).

That last one is worth singling out. mapConcurrent runs the function on virtual threads with bounded concurrency, while preserving order — a small fan-out tool that needs no executor at all.

The setup: windows over a stream, which the Stream API could not express before gatherers.

GathererDemo.javaruns offline
Stream.of(1, 2, 3, 4, 5).gather(Gatherers.windowFixed(2)).toList();
Stream.of(1, 2, 3, 4, 5).gather(Gatherers.windowSliding(2)).toList();

Make the invisible visible: each gatherer holds state between elements and emits when it decides to.

what the gatherer doesruns offline
windowFixed(2)      state = current window
  1 -> [1]            nothing emitted
  2 -> [1,2]          emit [1, 2], start a new window
  3 -> [3]
  4 -> [3,4]          emit [3, 4]
  5 -> [5]            ...end of stream: the finisher emits the partial window [5]

What you see: fixed windows do not overlap, sliding windows do.

consoleruns offline
[[1, 2], [3, 4], [5]]
[[1, 2], [2, 3], [3, 4], [4, 5]]

The Foreign Function & Memory API: native code without JNI

The FFM API (final in JDK 22, JEP 454) replaces two old things at once: JNI, the painful way to call C, and the misuse of sun.misc.Unsafe for off-heap memory.

Three types carry it.

The arena kinds are worth knowing individually, because picking the wrong one is how people get into trouble:

The four arenas, and who frees the memory.
ArenaThreadingFreed when
Arena.ofConfined()Single thread.You close it. Deterministic.
Arena.ofShared()Any thread.You close it.
Arena.ofAuto()Any thread.The garbage collector decides.
Arena.global()Any thread.Never.

Access a closed segment and you get an IllegalStateException — not a crash. That is exactly the safety JNI never had.

The setup: a segment used after the arena that owns it was closed.

ArenaDemo.javaruns offline
MemorySegment seg;
try (Arena arena = Arena.ofConfined()) {
    seg = arena.allocate(8);
    seg.set(ValueLayout.JAVA_LONG, 0, 42L);
}                                            // arena closed here: the 8 native bytes are freed
long v = seg.get(ValueLayout.JAVA_LONG, 0);  // ❌ TRAP: the segment object outlived its memory

Make the invisible visible: the segment is only a view (address plus size plus a lifetime handle). The memory belongs to the arena.

memory pictureruns offline
before close                                after close
------------                                -----------
seg ──► [ base, size 8, scope ]             seg ──► [ base, size 8, scope: CLOSED ]
                │                                         ✗ no memory behind it
                ▼
        native block (8 bytes) ◄── owned by arena

What you see: a Java exception at the access, with the JVM still running.

consoleruns offline
# illustrative output
Exception in thread "main" java.lang.IllegalStateException: Already closed
    at java.base/jdk.internal.foreign.MemorySessionImpl.alreadyClosed(MemorySessionImpl.java:...)

Why: every access checks the segment's scope first, so a dangling use becomes an exception, where JNI or Unsafe would read freed memory.

The fix: finish all uses inside the arena's try block, or pick an arena whose lifetime matches the data.

ArenaDemo.java (fixed)runs offline
try (Arena arena = Arena.ofConfined()) {
    MemorySegment seg = arena.allocate(8);
    seg.set(ValueLayout.JAVA_LONG, 0, 42L);
    long v = seg.get(ValueLayout.JAVA_LONG, 0);   // ✅ FIX: use it while the arena is open
    System.out.println(v);
}

What you see now: the access succeeds.

consoleruns offline
42

Which arena to pick comes down to one question: who is allowed to close the memory, and when?

Calling a native function takes three steps:

  1. Look up the symbol: Linker.nativeLinker().defaultLookup().find("strlen").
  2. Describe its signature: a FunctionDescriptor built from ValueLayouts.
  3. Call the handle: invoke the resulting MethodHandle like any Java method, and the JIT will inline the call.

Because native code can corrupt the JVM, calling it is a restricted operation. Since JDK 24 (JEP 472) you must pass --enable-native-access=ALL-UNNAMED, or name the module. Otherwise the JVM warns, and a future release will refuse outright.

The same "integrity by default" campaign is deprecating the Unsafe memory methods (JEP 471). They warn as of JDK 24, and --sun-misc-unsafe-memory-access=allow|warn|debug|deny controls the behaviour while libraries migrate.

Modules and jlink

The Java Platform Module System (JPMS, JDK 9) gives a jar a module-info.java. That file declares what the jar requires, which packages it exports for compilation and opens for reflection, and which services it uses or provides.

Since JDK 17 the JDK's own internals are strongly encapsulated. Reflective access into java.base internals fails with InaccessibleObjectException unless you pass --add-opens java.base/java.lang=ALL-UNNAMED.

That is why so many startup scripts carry that flag, and now you know what it is buying them.

The setup: a library that reaches into a private field of a JDK class.

Peek.javaruns offline
Field f = String.class.getDeclaredField("value");
f.setAccessible(true);      // ❌ TRAP: java.base does not open java.lang to your code

Make the invisible visible: the module descriptor of java.base decides who may use reflection on what.

who may reach whatruns offline
java.base  exports java.lang          -> your code may call public members          ✓
java.base  opens   java.lang          -> (not open to you)                          ✗ no deep reflection
--add-opens java.base/java.lang=ALL-UNNAMED   -> opens it to the classpath          ✓

What you see: the exception names the member, the module and the package that is closed.

consoleruns offline
# illustrative output
java.lang.reflect.InaccessibleObjectException: Unable to make field private final byte[] java.lang.String.value accessible:
    module java.base does not "opens java.lang" to unnamed module @1b2c3d4

Why: since JDK 17 the JDK's internals are strongly encapsulated, with no switch to turn that off globally.

The fix: prefer a supported API. If a library really needs the access, open the one package it needs.

consoleruns offline
java --add-opens java.base/java.lang=ALL-UNNAMED -jar app.jar     # ✅ FIX (a workaround; upgrade the library when you can)

What you see now: setAccessible(true) returns normally.

consoleruns offline
# illustrative output
$ java --add-opens java.base/java.lang=ALL-UNNAMED Peek
(no exception: the field is readable)

Most application code still lives on the classpath, in the unnamed module. That is fine, and it is not something to fix.

Modules pay off in three specific places:

That last one has a number attached that makes the case on its own. A jlink image — jlink --add-modules java.base,java.sql,java.net.http --strip-debug --compress zip-6 --output runtime — is typically 40–60 MB, instead of a 300 MB JDK. Which is exactly what a distroless container image wants.

JDK 25 made modules easier to use, with module import declarations (import module java.base;, JEP 511).

From module-info to a 50 MB image

The setup: a small module declaration, and the command that tells you which JDK modules it needs.

module-info.javaruns offline
module com.acme.billing {
    requires java.sql;                       // needed at compile time and run time
    exports com.acme.billing.api;            // public API for other modules
    opens com.acme.billing.model to com.fasterxml.jackson.databind;   // reflection allowed only for Jackson
}

Make the invisible visible: jdeps lists the JDK modules the jar really uses, and jlink packs only those.

consoleruns offline
# illustrative output
$ jdeps --print-module-deps --ignore-missing-deps app.jar
java.base,java.sql

$ jlink --add-modules java.base,java.sql --strip-debug --compress zip-6 --output runtime
$ du -sh runtime /opt/jdk
48M   runtime
310M  /opt/jdk

Why: a full JDK ships about seventy modules, and your program uses a handful of them.

The roadmap you will be asked about

Interviewers ask "what changed between 21 and 25" to see whether you follow the platform. Here is the answer as of August 2026, one row per release.

JDK 21 to 27: what shipped in each release.
ReleaseWhat it brought
JDK 21
Sept 2023 · LTS
Virtual threads. Sequenced collections. Record patterns and pattern matching for switch. Generational ZGC, as an option.
JDK 22FFM finalised. Unnamed variables (_).
JDK 23Generational ZGC became the default. String templates withdrawn after previews in 21 and 22 — still withdrawn, with no replacement shipped.
JDK 24Pinning on synchronized removed (JEP 491). Gatherers and the Class-File API finalised. The Leyden ahead-of-time cache (JEP 483). SecurityManager disabled for good (JEP 486).
JDK 25
Sept 2025 · LTS
Scoped values finalised. Compact object headers became a supported product feature. Generational Shenandoah. Module import declarations. Compact source files with instance main methods, so void main() { println("hi"); } is a complete program (JEP 512). Flexible constructor bodies — statements before super(...) (JEP 513). JFR CPU-time profiling. Structured concurrency stayed in preview.
JDK 26
March 2026
The AOT cache extended to every collector, including ZGC. G1's write barrier made cheaper.
JDK 27
Due 15 Sept 2026
G1 becomes the default in every environment. Compact object headers on by default. A JSON API in the JDK (JEP 540). Structured concurrency in its seventh preview — still not final.

If you remember one thing from that table for an interview, make it the last row. "Still not final after seven previews" is the kind of detail that shows you actually follow the platform.

See it: the whole modern toolkit in one file

The program below is pinned to JDK 25 because it uses gatherers (final in 24) and FFM (final in 22) alongside the JDK 21 features. It models the payment result from the opener, switches over it exhaustively, uses a sequenced map and two gatherers, and finishes by calling the C library's strlen through FFM, without a line of C.

Step-by-step: what ModernTour.java does, in plain English
  1. A sealed interface PaymentResult permits exactly three records: Approved (with an id and an amount), Declined (with a reason), and Pending (with a review queue name). Approved has a compact constructor that rejects non-positive amounts before the fields are assigned.
  2. describe(PaymentResult r) is a switch with three type-and-record patterns and one guard, and no default. Delete any case and the file stops compiling; that is the exhaustiveness check in action.
  3. sequencedDemo() builds a LinkedHashMap of results in insertion order, then uses the JDK 21 methods firstEntry(), lastEntry() and reversed() to read it from both ends without index arithmetic.
  4. gathererDemo() runs a stream of the same results through Gatherers.windowFixed(2) to batch them in pairs, and through a custom gatherer, dedupeConsecutive(), that drops an element when it equals the previous one. The custom gatherer is built with Gatherer.ofSequential(initializer, integrator): the state is a one-element array holding the last element seen, and the integrator pushes downstream only when the current element differs.
  5. ffmDemo() looks up strlen in the C library through Linker.nativeLinker().defaultLookup(), describes its signature as "takes a pointer, returns a C long", obtains a MethodHandle, allocates a C string in a confined arena with arena.allocateFrom("..."), and invokes the handle. The arena is closed by try-with-resources, which frees the native memory deterministically.
  6. main calls the four demos. The header shows the flag that makes the native call quiet: --enable-native-access=ALL-UNNAMED. Without it, JDK 24+ prints a warning naming the restricted method and the module that called it.
ModernTour.java · JDK 25 · java --enable-native-access=ALL-UNNAMED ModernTour.javaruns offline
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.util.*;
import java.util.stream.Gatherer;
import java.util.stream.Gatherers;
import java.util.stream.Stream;

public class ModernTour {

    sealed interface PaymentResult permits Approved, Declined, Pending {}
    record Approved(String id, long amountCents) implements PaymentResult {
        Approved { if (amountCents <= 0) throw new IllegalArgumentException("amount must be positive"); }
    }
    record Declined(String reason) implements PaymentResult {}
    record Pending(String reviewQueue) implements PaymentResult {}

    static String describe(PaymentResult r) {
        return switch (r) {                                   // no default: the compiler checks all three
            case Approved(var id, var cents) when cents > 1_000_000 -> "large approval " + id + " (" + cents / 100 + " units)";
            case Approved(var id, var cents) -> "approved " + id;
            case Declined(var reason) -> "declined: " + reason;
            case Pending(var queue) -> "waiting in " + queue;
        };
    }

    static void sequencedDemo() {
        SequencedMap<String, PaymentResult> byOrder = new LinkedHashMap<>();
        byOrder.put("o-1", new Approved("p-1", 4_500));
        byOrder.put("o-2", new Declined("insufficient funds"));
        byOrder.put("o-3", new Pending("manual-review"));
        System.out.println("first: " + byOrder.firstEntry() + "   last: " + byOrder.lastEntry());
        System.out.println("reversed keys: " + byOrder.reversed().keySet());
    }

    static <T> Gatherer<T, ?, T> dedupeConsecutive() {
        return Gatherer.ofSequential(
            () -> new Object[1],                              // state: the last element pushed
            (state, element, downstream) -> {
                if (Objects.equals(state[0], element)) return true;   // skip a repeat, keep going
                state[0] = element;
                return downstream.push(element);
            });
    }

    static void gathererDemo() {
        List<PaymentResult> results = List.of(
            new Approved("p-1", 4_500), new Approved("p-1", 4_500), new Declined("fraud"),
            new Declined("fraud"), new Pending("kyc"), new Approved("p-9", 250_000_000));
        System.out.println("pairs:   " + results.stream().gather(Gatherers.windowFixed(2)).map(w -> w.stream().map(ModernTour::describe).toList()).toList());
        System.out.println("deduped: " + results.stream().gather(dedupeConsecutive()).map(ModernTour::describe).toList());
    }

    static void ffmDemo() throws Throwable {
        Linker linker = Linker.nativeLinker();
        MethodHandle strlen = linker.downcallHandle(
            linker.defaultLookup().find("strlen").orElseThrow(),
            FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
        try (Arena arena = Arena.ofConfined()) {
            MemorySegment cString = arena.allocateFrom("payments-service");   // null-terminated, off-heap
            long len = (long) strlen.invokeExact(cString);
            System.out.println("strlen via FFM: " + len + "  (segment " + cString.byteSize() + " bytes incl. terminator)");
        }                                                     // arena closed: memory freed now, not by GC
    }

    public static void main(String[] args) throws Throwable {
        System.out.println(describe(new Pending("manual-review")));
        sequencedDemo();
        gathererDemo();
        ffmDemo();
    }
}

Read the output. Four things print, and each demonstrates a different feature.

The first line, waiting in manual-review, came from the third case of the switch.

To feel the compiler doing its job, comment that case out and rerun. The error reads the switch expression does not cover all possible input values — which is exactly the bug from the opener, caught before it can exist.

The sequenced lines print first: o-1=Approved[id=p-1, amountCents=4500] last: o-3=Pending[reviewQueue=manual-review] and reversed keys: [o-3, o-2, o-1]. Note the record's generated toString naming each component for you.

The gatherer lines show pairs: as three lists of two descriptions, and deduped: as four entries — the two repeated records were dropped by comparing with the generated equals. The last of them reads large approval p-9 (2500000 units), because the guard fired.

The final line is strlen via FFM: 16 (segment 17 bytes incl. terminator). That is a call into the C library with no JNI, no header file, and no Unsafe. The 17 is the arena's allocation including the null terminator; the 16 is what C counted.

One experiment worth running: drop the --enable-native-access flag. The line is then preceded by WARNING: A restricted method in java.lang.foreign.Linker has been called, together with advice to pass the flag.

That is the warning a production team meets the day they upgrade to JDK 24 or 25 with a native-backed library on the classpath.

🧠 Brain power

Before reading on: a colleague argues that because switches over sealed types are exhaustive, it is safe to expose PaymentResult as the public return type of a shared library and add subtypes in later versions "since consumers' code will just stop compiling and they will fix it". What actually happens to a consumer service that is not recompiled when the library's new version is deployed underneath it?

Reveal the answer

The consumer does not stop compiling — because it is not being compiled. It is already running.

Here is what happened. The exhaustive switch was compiled against the old set of three permitted types, and javac emitted a hidden fallback branch for "a value that matches none of the cases". That branch throws java.lang.MatchException.

So the first time the library returns the new subtype, the consumer throws that exception at runtime, on a production request, with a stack trace pointing at a switch that looks perfectly correct in the source.

Which gives the rule: adding a permitted subtype is a binary-incompatible change for every consumer that switched exhaustively.

The library author has three choices, and none of them is free:

  • Version the sealed type — a new interface for the new shape.
  • Keep the sealed set closed, and model new outcomes inside an existing subtype.
  • Document that consumers must write a default that fails safely — and give up compile-time exhaustiveness in exchange.

The senior answer names MatchException, explains that separate compilation is the cause, and then states which of the three policies the library should pick, and why.

Quick reference — modern language and platform

record
State is exactly the declared components. equals/hashCode/toString are invokedynamic sites, not bytecode. Shallowly immutable; deserialises through the canonical constructor.
sealed
permits a closed list of subtypes, each final, sealed or non-sealed. The closed list is what makes exhaustiveness checkable.
The rule for sealed switches
Never write default. It swallows exactly the case the compiler would have caught.
MatchException
Thrown when an already-compiled exhaustive switch meets a newly added permitted subtype. Adding to a sealed set is a binary-incompatible change.
Sequenced collections
JDK 21. getFirst(), getLast(), addFirst(), removeLast(), reversed().
Gatherers
JDK 24. Custom intermediate stream ops (collectors do terminal ones). Built-ins: windowFixed, windowSliding, fold, scan, and mapConcurrent — bounded fan-out on virtual threads, order preserved, no executor.
FFM
MemorySegment (bounds-checked, long-indexed) + Arena (lifetime) + Linker (native function → MethodHandle). Closed segment gives IllegalStateException, not a crash. Needs --enable-native-access since JDK 24.
Why your startup script has --add-opens
JDK internals are strongly encapsulated since JDK 17. Reflection into java.base fails with InaccessibleObjectException without it.
jlink
A runtime image with only the modules you need. 40–60 MB instead of a 300 MB JDK — what a distroless image wants.
The version answer
21 virtual threads · 22 FFM final · 23 generational ZGC default, string templates withdrawn · 24 no more synchronized pinning, gatherers final · 25 scoped values final · 26 cheaper G1 barrier · 27 G1 everywhere, compact headers on. Structured concurrency: still preview.

07 · The primerPerformance and Observability: JFR, Profilers, Safepoints, Honest Benchmarks, and Startup

Performance work is asking the machine a precise question and reading its answer honestly. Most wrong conclusions come from a measurement that answered a different question than the one you meant to ask.

A team benchmarks two JSON parsers with a quick loop and a stopwatch. Parser A wins by 3×. They switch, and production gets slower.

Look at what their benchmark actually measured. Parser A parsing the same 200-byte document ten million times, with the result thrown away, after the JIT had turned most of the work into nothing.

Now look at production. 40 KB documents of varying shape, through a call site that sees six different types.

Neither number was wrong. They were answers to different questions.

The setup: the same two parsers, measured two ways.

Make the invisible visible: the two measurements side by side, one row per thing that differs.

What the quick loop measured versus what production does.
ThingStopwatch loopProduction
DocumentThe same 200 bytes, ten million times40 KB documents of varying shape
ResultThrown away, so the JIT may delete the workUsed, so all the work is real
Call siteOne parser type, so it is inlinedSix types, so the call is not inlined
JIT stateWarmed on one shapeProfile polluted by many shapes
AnswerParser A wins by 3xParser A is slower

What you see: a loop that reports a time no parser can reach.

consoleruns offline
# illustrative output
parseA: 10,000,000 parses in 12 ms   ->  1.2 ns per 200-byte document    ✗ impossible: the loop was optimised away

Why: the stopwatch measures the JIT's shortcuts, not the parser. The rest of this chapter is the toolkit that removes those shortcuts.

This chapter is about asking the machine the right question and reading its answer. Five tools do that work:

The everyday toolkit of thread dumps and CPU triage lives in Chapter E3. This chapter goes underneath it.

JFR: the recorder that is always allowed in production

JDK Flight Recording (JFR) is an event recorder built into the JVM.

Hundreds of event types — from "a thread parked" to "a GC phase ended" to "this method was compiled" — are written into thread-local buffers at about one percent overhead, then dumped to a .jfr file on demand.

There are two ways to start it:

  1. At launch: -XX:StartFlightRecording=filename=/var/log/app/rec.jfr,maxage=1h,maxsize=500m,settings=profile, which keeps a rolling last hour in memory.
  2. On a running process: jcmd <pid> JFR.start duration=60s filename=/tmp/rec.jfr settings=profile.

A handful of events answer most questions, and it is worth knowing which one to reach for before you open the file.

The JFR events that answer real questions.
EventAnswers
jdk.ExecutionSampleWhere CPU time goes. A sampled Java stack, every 10–20 ms per thread. The basis of the CPU profile.
jdk.ObjectAllocationSampleWho allocates.
jdk.JavaMonitorEnter, jdk.ThreadParkWho waits on what, and for how long.
jdk.GCPhasePause, jdk.SafepointBeginThe pauses.
jdk.Compilation, jdk.DeoptimizationWhat the JIT is doing — including deoptimisation storms.
jdk.VirtualThreadPinnedWhich virtual threads pinned their carrier, and why.
jdk.OldObjectSampleLong-lived objects with their allocation stacks. With path-to-gc-roots=true, this is the cheapest leak detector available.

JDK 25 added two things worth knowing. CPU-time sampling on Linux (JEP 509), which attributes time by actual CPU use rather than by wall-clock sampling. And method timing and tracing events you can point at named methods (JEP 520).

To read a file, three commands cover most needs: jfr summary rec.jfr, jfr print --events jdk.GCPhasePause rec.jfr, and jfr view (JDK 21+) with built-in views such as hot-methods, allocation-by-class and gc-pauses.

For graphical work, JDK Mission Control's automated analysis page lists the findings in plain language.

The setup: a latency complaint on a live service, and no restart allowed.

consoleruns offline
$ jcmd 4242 JFR.start duration=60s filename=/tmp/rec.jfr settings=profile
$ jfr summary /tmp/rec.jfr
$ jfr view hot-methods /tmp/rec.jfr

Make the invisible visible: the recording as a count of events, then as a ranked list of methods.

What you see: the output of the three commands.

consoleruns offline
# illustrative output
Started recording 1. The result will be written to:
/tmp/rec.jfr

 Event Type                          Count  Size (bytes)
 ===================================================
 jdk.ExecutionSample                  2980         61200
 jdk.GCPhasePause                       41          1900
 jdk.ObjectAllocationSample           5120        140000

Method                                      Samples  Percent
------------------------------------------- -------  -------
com.acme.Parser.scan(CharSequence)              412   41.20%
java.util.regex.Pattern.matcher(CharSequence)   166   16.60%

Why: JFR sampled every thread about every 10-20 ms and wrote the stacks into per-thread buffers, so the cost was low enough to leave on.

Symptom to JFR event to what you read.
SymptomEvent to look atCommand
CPU is highjdk.ExecutionSamplejfr view hot-methods rec.jfr
Allocation rate is high, GC runs oftenjdk.ObjectAllocationSamplejfr view allocation-by-class rec.jfr
Latency spikes, CPU is lowjdk.JavaMonitorEnter, jdk.ThreadParkjfr print --events jdk.JavaMonitorEnter rec.jfr
Pausesjdk.GCPhasePause, jdk.SafepointBeginjfr view gc-pauses rec.jfr
Heap keeps growingjdk.OldObjectSample with path-to-gc-roots=trueJDK Mission Control, leak view

Safepoints: what a pause actually is

The JVM sometimes needs every Java thread to stop at a known, safe point, so it can do something to the world underneath them — move objects, install or discard compiled code, take a thread dump, write a heap dump.

A safepoint is such a point. Compiled code contains a cheap poll at method returns and loop back-edges, asking "has a safepoint been requested?"

When one is requested, the JVM waits for every thread to reach its next poll before the operation can begin.

That waiting is the time to safepoint, and it is where invisible pauses live. Three things make everyone else wait:

Here is the part that makes this hard to diagnose. GC logs report the pause from the moment the operation starts. The wait before it is not in that number.

So when users see 300 ms stalls and the GC log says 5 ms, run with -Xlog:safepoint and read the line: Reaching safepoint: 280 ms, At safepoint: 5 ms, Total: 285 ms.

The setup: a worker thread that copies a very large array while every other thread waits for a pause.

Copier.javaruns offline
// one thread, one huge copy
System.arraycopy(src, 0, dst, 0, 500_000_000);   // ❌ TRAP: no poll inside the copy, so a pending safepoint waits

Make the invisible visible: the timeline of one stop-the-world operation, one row per step.

The trace: the VM asks every thread to stop, and one thread cannot until its copy finishes.

safepoint timelineruns offline
t=0 ms     VM thread: requests safepoint, arms the poll
t=0 ms     workers 1-7: reach their next poll and park       ✓
t=0 ms     worker 8: inside the 500 MB arraycopy             ✗ no poll in the copy
t=280 ms   worker 8: copy done, reaches a poll and parks     ← "Reaching safepoint" ends
t=280 ms   VM thread: all stopped, GC runs for 5 ms          ← "At safepoint" (the only part the GC log reports)
t=285 ms   all threads resume

What you see: the GC log and the safepoint log disagree.

consoleruns offline
# illustrative output
[gc] GC(17) Pause Young (Normal) (G1 Evacuation Pause) 5.1ms
[safepoint] Safepoint "G1CollectForAllocation", Time since last: 1.2 s, Reaching safepoint: 280 ms, At safepoint: 5 ms, Total: 285 ms

Why: the GC log starts its clock when the operation begins. The wait for the slowest thread happened before that.

The fix: copy in slices, so the thread passes a poll between slices.

Copier.java (fixed)runs offline
final int SLICE = 8_000_000;
for (int off = 0; off < total; off += SLICE) {
    int n = Math.min(SLICE, total - off);
    System.arraycopy(src, off, dst, off, n);     // ✅ FIX: a poll between slices lets the VM stop us
}

What you see now: the same two logs, now in agreement.

consoleruns offline
# illustrative output
[gc] GC(18) Pause Young (Normal) (G1 Evacuation Pause) 5.0ms
[safepoint] Safepoint "G1CollectForAllocation", Time since last: 1.1 s, Reaching safepoint: 0.2 ms, At safepoint: 5 ms, Total: 5.2 ms

There is a second reason to understand safepoints: safepoint bias.

Any tool that collects stacks at safepoints — including jstack and older profilers — can only ever see threads at poll sites. It therefore attributes time to the method containing the nearest poll, rather than to the code actually running.

JFR's execution sampler and async-profiler both sample without safepoints, and do not have this bias.

The setup: a hot loop whose real cost is a hash function, with no poll inside the hash.

Hot.javaruns offline
for (int i = 0; i < n; i++) {
    sum += hash(data[i]);     // all the real CPU time is here
}                             // loop back-edge: a safepoint poll lives here

Make the invisible visible: the same run, profiled two ways.

profile comparisonruns offline
# illustrative output
safepoint-biased profiler            unbiased (JFR / async-profiler)
-------------------------            -------------------------------
Hot.run (loop back-edge)    97%      Hot.hash                  71%
Hot.hash                     1%      Hot.run (array load)      22%

Why: a sampler that stops threads at safepoints sees only frames with a poll, so every sample lands on the loop edge.

async-profiler and flame graphs

async-profiler is the profiler most JVM performance engineers reach for.

It combines the kernel's perf_events sampling with a JVM interface that reconstructs Java stacks at arbitrary points. So it sees native frames, JIT frames and GC frames in one picture — with no safepoint bias.

Attach with asprof -d 30 -e cpu -f /tmp/cpu.html <pid> and you get a flame graph.

Read one like this. Every horizontal bar is a stack frame. Its width is the share of samples that had that frame on the stack. Bars stack upward, from the thread root to the leaf that was actually running.

Then look for the widest plateaus near the top. That is where the CPU went.

The setup: collapsed stacks, which are the raw input of a flame graph: one line per distinct stack, with its sample count.

collapsed stacksruns offline
# illustrative output  (stack from root to leaf ; sample count)
Thread.run;Handler.handle;String.split;Pattern.compile        420
Thread.run;Handler.handle;JsonParser.parse;HashMap.put        180
Thread.run;Handler.handle;JsonParser.parse;String.intern      100

Make the invisible visible: the same data drawn as a flame graph, widest bar first.

flame graph as ASCII (width = samples)runs offline
                         [Pattern.compile  ][HashMap.put][intern]
                         [String.split     ][JsonParser.parse   ]
                         [Handler.handle                        ]
                         [Thread.run                            ]
                         0%                                    100%

The trace: how to read it, in order.

  1. Start at the bottom: Thread.run is the root, present in every sample.
  2. Go up: each bar is a callee of the bar below it.
  3. Compare widths: Pattern.compile is 420 of 700 samples, so 60% of the CPU.
  4. Act on the top plateau: compile the pattern once, not per call.
Question to async-profiler mode.
QuestionModeWhy
What burns CPU?-e cpuSamples only running threads
Why is this request slow?-e wallIncludes threads that sleep or wait
Who allocates the most?-e allocAttributes bytes to the allocating stack
Who waits on locks?-e lockShows contended monitor time

Three modes matter beyond cpu, and picking the right one is most of the skill:

One container caveat. The kernel may forbid perf_events via perf_event_paranoid, in which case async-profiler falls back to a timer and loses native frames. Note it and move on.

one stop-the-world operation, seen on a wall-clock timeline time → safepoint requested poll page armed; threads stop at their next poll "Reaching safepoint": 280 ms one thread is in a long compiled loop without a poll, or a 500 MB arraycopy, or native code; every other thread is already stopped and waiting NOT in the GC log · visible with -Xlog:safepoint "At safepoint" 5 ms GC pause, deopt, dump this is the GC log threads resume users saw 285 ms; the GC log said 5 ms a sampler that stops threads AT safepoints only ever sees frames containing a poll → safepoint bias JFR jdk.ExecutionSample and async-profiler sample threads wherever they are → no bias
Fig. E2.5 — A stop-the-world operation has two parts. The GC log reports only the second; the first, the wait for the slowest thread to reach a poll, is the pause users feel and the GC log never mentions. The same poll sites are all a safepoint-biased profiler can see.

JMH: benchmarks that resist your own optimism

The stopwatch benchmark from the opener fails in four standard ways. The Java Microbenchmark Harness (JMH, the OpenJDK project's own tool) exists to block each one of them.

The four ways a hand-written benchmark lies, and what JMH does about each.
The lieWhat goes wrongJMH's answer
Dead-code eliminationThe result is never used, so C2 removes the computation entirely.Return the value, or hand it to a Blackhole — an object whose consume method the JIT cannot see through.
Constant foldingThe input is a literal, so the compiler computes the answer once.Inputs live in @State fields, which the compiler must treat as unknown.
Warm-up and OSRA single long loop measures OSR-compiled code, which can differ from the normally compiled method. And the first seconds measure the interpreter.Warm-up iterations, then measurement iterations, across several forked JVMs — because the profile C2 builds differs run to run, and one JVM is one sample.
Wrong modeThroughput averages hide the tail.Mode.SampleTime, for percentiles.

Two profilers are worth adding to a run. -prof gc shows allocation per operation, and -prof perfasm shows the generated assembly.

The setup: the stopwatch loop next to a JMH benchmark of the same parser.

hand-written loopruns offline
long t0 = System.nanoTime();
for (int i = 0; i < 10_000_000; i++) {
    parserA.parse("{\"a\":1}");       // ❌ TRAP: constant input, result unused
}
System.out.println((System.nanoTime() - t0) / 1_000_000 + " ms");
ParseBench.java (JMH)runs offline
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class ParseBench {
    String doc;                                                  // ✅ FIX: input lives in @State
    Parser parserA = new ParserA();

    @Setup
    public void load() throws IOException { doc = Files.readString(Path.of("sample-40k.json")); }

    @Benchmark
    public Object parse() { return parserA.parse(doc); }         // ✅ FIX: returned, so it cannot be dropped
}

Make the invisible visible: what the JIT is allowed to do to the first version.

what C2 may do to the loopruns offline
parserA.parse("{\"a\":1}")   input is a constant   -> constant folding: compute once
result is never read         -> dead-code elimination: delete the call
10,000,000 iterations of nothing -> the loop itself disappears

What you see: the loop reports an impossible time, and JMH reports a believable one.

consoleruns offline
# illustrative output
hand-written loop:   12 ms for 10,000,000 parses

Benchmark         Mode  Cnt     Score    Error  Units
ParseBench.parse  avgt   10  41250.3  ± 812.4  ns/op

One example per row of the table above, with the rule to remember:

And remember the rule JMH's own authors keep repeating: a benchmark answers one narrow question, about one call site, with one input shape. Production is a different question.

The honest check is an A/B canary with JFR running on both sides.

Startup: CDS, the AOT cache, and native image

"Java starts slowly" has three causes, in the order they hit you:

Three technologies attack them, and they are not alternatives — they sit on a spectrum.

Class-data sharing (CDS) stores parsed, verified class metadata in an archive that is memory-mapped at startup. The JDK ships one for its own classes.

AppCDS extends that to your classes: -XX:ArchiveClassesAtExit=app.jsa on a training run, then -XX:SharedArchiveFile=app.jsa in production. Or -XX:+AutoCreateSharedArchive to do both in one step.

The Leyden ahead-of-time cache goes further, and it arrived over three releases:

Typical results as of 2026: startup times cut roughly in half, and time-to-peak-throughput cut by a similar fraction. With no change to your code, and no closed-world restrictions.

GraalVM native image is the other end of the spectrum. It compiles the whole program ahead of time into a native executable, with a closed world — no class loading at runtime, and reflection only where declared in metadata.

You get startup in tens of milliseconds and a small footprint. You pay in long builds, lower peak throughput than C2 (unless you use profile-guided optimisation), and a different debugging and profiling story.

The 2026 rule of thumb: native image for functions, command-line tools and scale-to-zero services; the AOT cache for everything long-running.

There is a third option worth knowing by name. CRaC — checkpoint and restore of an already-warm JVM — is shipped by some vendors, but is not in mainline OpenJDK.

The setup: one service, and the three costs between java -jar and the first fast request.

Make the invisible visible: the startup timeline, with the technology that attacks each stretch.

startup timelineruns offline
# illustrative, not to scale
|-- load + verify + link classes --|-- static init + framework reflection --|-- interpreter, then C1, then C2 --> peak
   CDS / AppCDS / AOT cache (24+)       AOT cache helps a little; native image       AOT cache profiles (25+)
   native image: done at build time     runs much of it at build time                native image: no warm-up at all

The trace: how to build and use the AOT cache on JDK 25.

consoleruns offline
# training run: records loaded and linked classes and method profiles
java -XX:AOTCacheOutput=app.aot -jar app.jar --training-workload

# production run: starts from the cache  ✓
java -XX:AOTCache=app.aot -jar app.jar
Technology versus cost it removes.
TechnologyClass load, verify, linkStatic init, reflectionWarm-upPrice
AppCDSYesNoNoA training run and an archive per build
AOT cache (24-26)Yes, classes arrive loaded and linkedPartlyPartly, profiles from JDK 25One training run, no code change
Native imageNo class loading at runtimeMuch of it moves to build timeNo JIT warm-upClosed world, long builds, lower peak throughput

Reflection, proxies, and why frameworks are slow to start

Frameworks are built on three runtime mechanisms this chapter would be incomplete without.

Reflection — Class.getDeclaredMethods, Method.invoke — is how Spring finds your annotations and calls your handlers.

Since JDK 18 (JEP 416) Method.invoke is implemented with method handles, so after warm-up it is close to a direct call. The cost that remains is the scanning.

Which explains two things at once: why frameworks cache reflection results, and why build-time frameworks like Micronaut and Quarkus move the work to compile time with annotation processors.

Proxies are generated classes that stand in front of yours. java.lang.reflect.Proxy handles interfaces; a generated subclass through ByteBuddy or CGLIB handles classes. This is what makes @Transactional work, and it is covered in Chapter E4.

Two JDK changes matter here. Since JDK 15, such classes can be hidden classes (JEP 371) — not discoverable by name, and unloadable independently. And since JDK 24 the JDK ships a Class-File API (JEP 484), so frameworks can generate bytecode without a third-party library that breaks on every JDK release.

The setup: a transactional service method and the proxy that makes @Transactional work.

OrderService.javaruns offline
@Service
class OrderService {
    @Transactional
    public void place(Order o) { /* business logic only */ }
}

Make the invisible visible: the object the caller actually holds is not an OrderService. It is a generated subclass.

call traceruns offline
caller
  └─► OrderService$$SpringCGLIB$$0   (generated proxy, a subclass)
        1. begin transaction            ✓
        2. super.place(order)  ──►  OrderService.place   (your code)
        3. commit, or rollback on exception   ✓

Why: the framework wraps your class at startup using reflection to find the annotations, so the cost is the scan and the class generation, not the later calls.

Last, Java serialization, which is a security topic more than a performance one.

Never deserialise untrusted bytes with ObjectInputStream without a filter. Reconstructing an arbitrary object graph runs arbitrary readObject methods, and a chain of innocent-looking library classes — a gadget chain — can be arranged to execute code.

The JDK's answer is ObjectInputFilter (JEP 290), set process-wide with -Djdk.serialFilter='com.acme.**;java.base/*;!*'. That is an allow-list that rejects everything else. Per-stream filter factories exist too (JEP 415).

The better answer is a data format that cannot express code in the first place.

The setup: a service that reads an object from bytes sent by a client.

Reader.javaruns offline
Object o = new ObjectInputStream(socket.getInputStream()).readObject();   // ❌ TRAP: untrusted bytes, no filter

Make the invisible visible: what deserialisation does with those bytes.

call traceruns offline
readObject()
  └─► read class name from the stream            (chosen by the attacker)
        └─► run that class's readObject()        ✗ code you did not write runs
              └─► chain of library classes ...   ✗ a gadget chain reaches an exec-like call

The fix: an allow-list filter, set per stream or for the whole process.

Reader.java (fixed)runs offline
ObjectInputFilter f = ObjectInputFilter.Config.createFilter("com.acme.**;java.base/*;!*");   // ✅ FIX: allow-list, reject the rest
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
in.setObjectInputFilter(f);

What you see now: a disallowed class is rejected before its code runs.

consoleruns offline
# illustrative output
java.io.InvalidClassException: filter status: REJECTED

See it: record a JFR file from inside the program and read it back

Step-by-step: what PerfTour.java does, in plain English
  1. The program creates a jdk.jfr.Recording, enables three events by name (jdk.ObjectAllocationSample with stack traces, jdk.GCPhasePause, and jdk.ExecutionSample at a 10 ms interval), and starts it. This is the same thing -XX:StartFlightRecording does, done from Java so the example is self-contained.
  2. churn() is the workload: it builds many short-lived String and ArrayList objects and a running checksum, for about 1.5 seconds of allocation-heavy CPU work, the kind that both the allocation sampler and the execution sampler will attribute to it.
  3. The recording is stopped and dumped to perftour.jfr in the working directory with recording.dump(Path).
  4. report() opens the file with RecordingFile.readAllEvents, which returns every recorded event as a RecordedEvent. For allocation samples it takes the top frame of each event's stack trace and sums the sampled bytes per method name; for GC pauses it counts and sums durations; for execution samples it counts top frames. It prints the top five methods by allocated bytes and by CPU samples.
  5. The header command shows the equivalent command-line inspection with the jfr tool, jfr view allocation-by-class perftour.jfr and jfr summary perftour.jfr, so you can compare the program's own report with the JDK's.
PerfTour.java · JDK 21+ · java PerfTour.java ; jfr summary perftour.jfr ; jfr view allocation-by-class perftour.jfrruns offline
import jdk.jfr.Recording;
import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordingFile;
import java.nio.file.Path;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

public class PerfTour {

    static long checksum;

    static void churn() {
        long until = System.nanoTime() + 1_500_000_000L;
        List<String> batch = new ArrayList<>();
        while (System.nanoTime() < until) {
            batch.clear();
            for (int i = 0; i < 2_000; i++) batch.add("order-" + i + "-" + (i * 31));   // allocation-heavy on purpose
            checksum += batch.get(batch.size() - 1).hashCode();
        }
    }

    static String topFrame(RecordedEvent e) {
        var st = e.getStackTrace();
        if (st == null || st.getFrames().isEmpty()) return "(no stack)";
        var m = st.getFrames().get(0).getMethod();
        return m.getType().getName() + "." + m.getName();
    }

    static void report(Path file) throws Exception {
        Map<String, Long> allocBytes = new HashMap<>();
        Map<String, Long> cpuSamples = new HashMap<>();
        long pauses = 0; Duration pauseTotal = Duration.ZERO;
        for (RecordedEvent e : RecordingFile.readAllEvents(file)) {
            switch (e.getEventType().getName()) {
                case "jdk.ObjectAllocationSample" -> allocBytes.merge(topFrame(e), e.getLong("weight"), Long::sum);
                case "jdk.ExecutionSample"        -> cpuSamples.merge(topFrame(e), 1L, Long::sum);
                case "jdk.GCPhasePause"           -> { pauses++; pauseTotal = pauseTotal.plus(e.getDuration()); }
                default -> { }
            }
        }
        System.out.println("GC pauses: " + pauses + ", total " + pauseTotal.toMillis() + " ms");
        System.out.println("top allocators (sampled bytes):");
        allocBytes.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()).limit(5)
                  .forEach(en -> System.out.printf("  %-60s %,12d%n", en.getKey(), en.getValue()));
        System.out.println("top CPU frames (samples):");
        cpuSamples.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()).limit(5)
                  .forEach(en -> System.out.printf("  %-60s %,12d%n", en.getKey(), en.getValue()));
    }

    public static void main(String[] args) throws Exception {
        Path file = Path.of("perftour.jfr");
        try (Recording rec = new Recording()) {
            rec.enable("jdk.ObjectAllocationSample").withStackTrace();
            rec.enable("jdk.GCPhasePause");
            rec.enable("jdk.ExecutionSample").withPeriod(Duration.ofMillis(10));
            rec.start();
            churn();
            rec.stop();
            rec.dump(file);
        }
        System.out.println("recorded " + file.toAbsolutePath() + "  (checksum " + checksum + ")");
        report(file);
    }
}

Read the output. The first line names the file — open it later in JDK Mission Control, or with the jfr tool.

GC pauses: 14, total 21 ms tells you fourteen young collections happened during 1.5 seconds of churn, each a millisecond or two. That is the signature of allocation pressure with a small live set.

Now the surprise, and it is worth sitting with. The allocator list has java.lang.StringConcatHelper.newArray or java.lang.String.<init> at the top — not PerfTour.churn.

That is because the sampler attributes bytes to the frame that executed the allocation. The string concatenation in churn was expanded by invokedynamic into JDK code. Open the full stack in Mission Control and churn is two frames down.

That attribution surprise is the same one that makes "40 percent of CPU in HashMap.get" a useless finding until you look at the callers. It is exactly why flame graphs are read from the bottom up.

The CPU list shows the same StringConcatHelper and ArrayList.add frames. The numbers are samples at 10 ms, so 150 samples is the whole 1.5 seconds.

One more view is worth running. jfr view allocation-by-class perftour.jfr puts byte[] and String at the top by bytes — the class view of the same events, rather than the method view.

So you now have the two questions every allocation investigation asks, both answered from one 1.5-second recording that cost about one percent to collect.

🧠 Brain power

Before reading on: a colleague writes a JMH benchmark for a parse(String) method, passes the literal "{\"id\":1}" as the argument, does not return the result, and reports 2 nanoseconds per operation. What has actually been measured, and what are the two changes that would make the number meaningful?

Reveal the answer

Almost nothing has been measured. Three separate things conspired.

  • Because the result is discarded, C2 is free to delete the parse entirely, once it proves the call has no side effects.
  • Because the input is a compile-time constant, whatever remains can be folded at compile time.
  • The 2 ns you measured is the cost of a loop iteration and a counter.

Two changes fix the measurement. Move the input into a @State object field, so the compiler cannot treat it as a constant. And return the parsed object from the benchmark method, or pass it to a Blackhole, so the work must actually happen.

After that the number will be in the hundreds of nanoseconds or more. And it will still answer only the narrow question: "how fast is this parse, for this one document shape, at a monomorphic call site".

The senior answer adds a third fix. Benchmark a set of production-shaped inputs, and confirm the winner with a JFR recording from a canary — not with the harness alone.

Quick reference — performance and observability

JFR
Always-on event recorder, ~1% overhead. -XX:StartFlightRecording=... at launch, or jcmd <pid> JFR.start on a live process. Read with jfr summary / jfr view.
The leak detector
jdk.OldObjectSample with path-to-gc-roots=true. Cheapest one available.
safepoint
A point where every thread can stop so the JVM can act. Compiled code polls at method returns and loop back-edges.
time to safepoint
The wait for the slowest thread to reach its poll. Not included in the GC log's pause number. When users see 300 ms and the log says 5 ms, run -Xlog:safepoint and read "Reaching safepoint" versus "At safepoint".
safepoint bias
Tools that sample at safepoints (jstack, older profilers) blame the method holding the nearest poll. JFR and async-profiler do not have it.
flame graph
Bar width = share of samples with that frame on the stack. Read bottom-up, and look for wide plateaus near the top. -e cpu for CPU, -e wall for "why is this slow", -e alloc, -e lock.
The four benchmark lies
Dead-code elimination (→ Blackhole), constant folding (→ @State), warm-up and OSR (→ forked JVMs), wrong mode (→ Mode.SampleTime for the tail).
Startup: which one
Native image for functions, CLI tools and scale-to-zero. AOT cache for everything long-running — roughly half the startup time, no code change, no closed world.
Deserialization
Never ObjectInputStream on untrusted bytes without ObjectInputFilter (JEP 290). A gadget chain executes code. Better: a format that cannot express code.

08 · DrillClass Loading, Bytecode & the JIT — Q1–Q40

Senior rounds open on the compilation pipeline because it reveals whether you know what the JVM does with your code or only what your code says. These forty questions cover the class file and linking, the loader hierarchy and the identity rule, tiered compilation and inlining, escape analysis, deoptimisation, the code cache, and the incidents each of them causes. Scenarios are answered in diagnosis order. Say the answer aloud before revealing; if you cannot say why, you do not yet know it.

Drill · Bytecode, the class file & linking

This group tests whether you can read what javac wrote, explain what the JVM does with it before the first line of your code runs, and name the exact error each stage throws when it fails.

Q1. "What does javac actually produce, how is that different from what the JIT produces, and can you read me a few lines of javap -c -v output?"

Reveal answer

The real test Whether you know that a class file is a program for an abstract stack machine and can tell the four classic invoke instructions apart, rather than saying "bytecode" and stopping.

Strong answer javac produces a class file: a portable description of one class, made of a constant pool, which is a numbered table of names, type descriptors and literal values, plus the fields, the methods and the bytecode of each method body.

The bytecode is a program for a stack machine, meaning instructions take their operands from an operand stack and push results back, with no registers.

That format was chosen because it is compact, because it is independent of any real CPU, and because the verifier can check it cheaply.

The JIT, the just-in-time compiler inside HotSpot, produces something completely different: native machine code for the CPU you are on, specialised using what the running program has actually done, and kept in the code cache, not on disk.

So javac does almost no optimisation, and the JIT does almost all of it; that is why "the compiler" means two different things in Java.

Reading javap -c -v Foo.class: the top lists constant pool entries like #7 = Methodref #8.#9, a symbolic reference made of a class name and a name-and-type.

In the method body, ldc #12 pushes a constant such as a string from the pool.

The four classic invoke instructions differ like this:

  • invokevirtual #7: calls an instance method through the class's virtual table, so subclasses can override it.
  • invokeinterface: does the same for a method declared on an interface. It is slightly slower because the receiver's class can be anywhere in the hierarchy.
  • invokespecial: the direct call used for constructors, which appear as <init>, and for super.method().
  • invokestatic: needs no receiver at all.

One surprise: since JDK 11 private methods are also called with invokevirtual or invokeinterface because of nestmates, which breaks the older rule people learned.

Picture it one small method, the bytecode javac wrote for it, the operand stack at work, and what the JIT leaves behind.

The setup: a method that sums an array with an enhanced for.

the source, and the bytecode javac producedruns offline
public int sum(int[] xs) {
    int total = 0;
    for (int x : xs) total += x;
    return total;
}

Make the invisible visible: the bytecode, one instruction per line, with the local-variable slot each value lives in.

javap -c Adder.class — read it left to rightruns offline
public int sum(int[]);
  Code:
     0: iconst_0          // push 0
     1: istore_2          // total = 0                  (slot 2)
     2: aload_1           // push xs                    (slot 1)
     3: astore_3          // copy of the array for the loop
     4: aload_3
     5: arraylength
     6: istore        4   // length -> slot 4
     8: iconst_0
     9: istore        5   // index i = 0                (slot 5)
    11: iload         5
    13: iload         4
    15: if_icmpge     35  // if i >= length, jump out
    18: aload_3
    19: iload         5
    21: iaload            // x = xs[i]
    22: istore        6
    24: iload_2
    25: iload         6
    27: iadd              // total + x
    28: istore_2
    29: iinc          5, 1  // i++
    32: goto          11
    35: iload_2
    36: ireturn

The trace: the operand stack while total += x runs (offsets 24 to 28 above).

operand stack, one line per instructionruns offline
24: iload_2        stack: [ total ]
25: iload 6        stack: [ total, x ]
27: iadd           stack: [ total+x ]          ✓ two values popped, one pushed
28: istore_2       stack: [ ]                  total = total+x, stack empty again

Make the invisible visible: the constant pool behind a call such as invokevirtual #7, as javap -v prints it.

javap -v (constant pool excerpt)runs offline
# illustrative output
Constant pool:
   #7 = Methodref          #8.#9          // java/io/PrintStream.println:(Ljava/lang/String;)V
   #8 = Class              #10            // java/io/PrintStream
   #9 = NameAndType        #11:#12        // println:(Ljava/lang/String;)V

What you see: what the JIT produced for the same method after it got hot, as -XX:+PrintCompilation reports it. The native code lives in the code cache, not in any file.

PrintCompilationruns offline
# illustrative output  (timestamp ms, compile id, tier, method, bytecode size)
    312  105       3       Adder::sum (37 bytes)     <- tier 3: C1 with profiling
    355  118       4       Adder::sum (37 bytes)     <- tier 4: C2, optimised using the profile

Read what javac did and did not do. It desugared the enhanced for into an index loop and allocated local-variable slots — but it did not unroll, did not vectorise, and did not remove a single bounds check. It is a faithful, unoptimised translation; every optimisation you care about happens later, in the JIT, using profile data javac never had.

Land it The class file is a contract written for a machine that does not exist, and the JIT is the thing that turns it into code for the machine that does.

Likely follow-ups
"Why a stack machine and not a register machine like Android's Dalvik?"

A stack encoding is smaller, because most instructions carry no operand addresses; an iadd is one byte.

It is also easier to generate from a compiler with no register allocator and easier to verify, because the verifier can simulate the stack depth and types at every instruction using the StackMapTable attribute.

The cost is more instructions for the same work, but that does not matter, because HotSpot never executes bytecode as-is for long. The template interpreter maps each bytecode to a native snippet, and the JIT turns hot methods into a register-based intermediate form anyway.

Dalvik chose registers because it interpreted for much longer on weak phones. For the JVM, the class file is a distribution format, not the execution format, so compactness and verifiability win.

"What does the constant pool hold and why does it matter to a running program?"

It holds every symbolic name the class refers to: class names, field and method references as name plus descriptor, string and numeric literals, and since JDK 7 the bootstrap method entries used by invokedynamic. It matters because linking is done against these entries.

When the JVM first executes invokevirtual #7, it resolves entry 7 to a real method in a loaded class and caches the result in the constant pool cache, so the second execution skips the lookup.

resolution traceruns offline
1st execution of invokevirtual #7:  entry #7 unresolved -> find class, find method -> cache the result   ✓ pays the lookup
2nd execution of invokevirtual #7:  entry #7 resolved   -> use the cached target                          ✓ no lookup
method missing from the loaded class -> NoSuchMethodError, thrown at the FIRST execution, not at load   ✗ late failure

That is why a missing method only fails when the instruction is first reached, not at class load time.

It is also why javap -v is the fastest way to answer "what does this jar actually call", for example when checking whether a library was compiled against an old API.

"How would you check what the JIT produced for a hot method?"

First I would confirm it was compiled at all with -XX:+PrintCompilation, which prints one line per compile with the tier, or with the JFR event jdk.Compilation.

To see the machine code I need the hsdis disassembler plugin on the library path and then -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly, usually narrowed with -XX:CompileCommand=print,com.acme.Foo::bar, because printing everything is unreadable.

For inlining decisions, which matter more in practice, -XX:+PrintInlining tells me why a call was or was not inlined, for example "callee is too large" against the 325-bytecode FreqInlineSize limit.

PrintInliningruns offline
# illustrative output
@ 8   com.acme.Foo::bar (24 bytes)   inline (hot)
@ 15  com.acme.Big::run (410 bytes)   hot method too big

For a benchmark I would use JMH with the perfasm profiler, which lines up hot instructions with the source.

Q2. "How do lambdas and string concatenation use invokedynamic, and why is that better than what javac used to generate?"

Reveal answer

Strong answer invokedynamic is a call instruction whose target is not written into the class file. The first time it executes, the JVM calls a bootstrap method named in the constant pool, and that method returns a java.lang.invoke.CallSite holding a method handle.

The JVM links the instruction to that handle permanently, so later executions are as fast as a normal call and can be inlined.

For lambdas, javac compiles the body to a private synthetic method in your class. It then emits an invokedynamic whose bootstrap is LambdaMetafactory.metafactory.

At runtime that factory spins a small hidden class implementing the functional interface and returns a handle to its constructor, or to a cached singleton if the lambda captures nothing.

For string concatenation, since JDK 9 under JEP 280, "id=" + id + ", name=" + name compiles to one invokedynamic with bootstrap StringConcatFactory.makeConcatWithConstants and a recipe string that marks where the arguments go.

The runtime's default strategy computes the exact final length, allocates one byte array and copies into it, with no intermediate StringBuilder.

Why this beats the old approach:

  • Lambdas: an anonymous inner class meant one extra class file per lambda in the jar, loaded and verified at startup whether used or not.
  • Concatenation: a StringBuilder chain baked one particular strategy into every class file forever.

With invokedynamic the class file only records intent, and the JDK team can improve the runtime strategy in a new release without anyone recompiling.

It also keeps bytecode smaller and gives the JIT a single, well-understood shape to optimise.

Picture it the two source lines, what javac turns them into, and what happens on the first and later executions.

The setup: a lambda and a string concatenation.

what invokedynamic replaced, and why it mattersruns offline
// SOURCE
Runnable r = () -> System.out.println("hi");
String s = "user=" + name + " id=" + id;

Make the invisible visible: the code javac effectively produces, written as Java, plus the bytecode instruction that replaces the old class.

what the compiler generatesruns offline
// the lambda body becomes a private synthetic method in YOUR class
private static void lambda$main$0() { System.out.println("hi"); }

// the call site is one invokedynamic; its bootstrap is LambdaMetafactory.metafactory
Runnable r = invokedynamic run()  -> metafactory(..., lambda$main$0)

// the concatenation recipe: \u0001 marks where each argument goes
String s = invokedynamic makeConcatWithConstants(name, id)   // recipe "user=\u0001 id=\u0001"
the bytecode, before and afterruns offline
// PRE-JAVA-8 LAMBDAS: javac emitted an anonymous inner CLASS per lambda.
//   Adder$1.class on disk, loaded and verified at startup, one per call site.

// TODAY: one instruction, and no class file.
  invokedynamic #2, 0   // InvokeDynamic #0:run:()Ljava/lang/Runnable;
//
// The first execution calls a BOOTSTRAP METHOD — LambdaMetafactory.metafactory
// — which builds the implementing class at RUNTIME, then permanently links the
// call site to it. Every later execution is a direct call with no indirection.

// STRING CONCATENATION, pre-JDK-9: javac emitted a fixed StringBuilder chain.
   new StringBuilder; dup; invokespecial; ldc "user="; invokevirtual append; ...

// TODAY:
  invokedynamic #7, 0   // makeConcatWithConstants(...)
//
// StringConcatFactory picks a strategy at runtime, and can size the buffer
// exactly once instead of growing it.

The trace: the life of one lambda call site.

call site statesruns offline
call 1:      invokedynamic #2 is unlinked -> run bootstrap -> metafactory spins a hidden class -> site linked   ✗ slow, once
call 2..n:   site is linked              -> call the target directly (the JIT can inline it)                  ✓ fast

What you see: the generated class in the class-loading log. It is a hidden class named after the enclosing class.

-Xlog:class+loadruns offline
# illustrative output
[0.044s][info][class,load] Adder$$Lambda/0x000071c4c8003200 source: __JVM_LookupDefineClass__

The point of invokedynamic is that the linkage decision is deferred to runtime. That let the JDK change how lambdas and concatenation are implemented — repeatedly, and with real performance gains — without recompiling a single line of application code, because the bytecode only names a bootstrap method rather than a strategy.

Land it invokedynamic moves the "how" of a language feature from compile time into the runtime library, which is the only place it can be improved after your jar is built.

Likely follow-ups
"Does that mean the first call of every lambda is slow?"

Yes, the first execution of each invokedynamic site pays for bootstrapping: the metafactory generates and defines a class, which takes tens of microseconds to a few milliseconds.

In a service with thousands of lambda sites that adds up to visible startup cost, which is why frameworks and JDK startup work went into it.

Mitigations: class data sharing archives, and since JDK 24 the Leyden AOT cache with -XX:AOTCache, can store the already-linked lambda classes so the sites resolve without spinning classes again.

After linking there is no ongoing cost; a linked site is a constant method handle the JIT inlines like any other call. If startup matters, I would measure with -Xlog:class+load and count the Lambda hidden classes rather than guessing.

"Can I see the generated lambda class or turn the new concatenation off?"

The lambda proxy classes can be dumped to disk with a system property; the name changed across releases, so on the JDK in use I would check the LambdaMetafactory source, but in recent JDKs it is -Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles=true, and older ones used -Djdk.internal.lambda.dumpProxyClasses=<dir>. The dumped class shows a tiny class with one method that calls your synthetic lambda$main$0. For concatenation, the compiler flag -XDstringConcat=inline makes javac emit the old StringBuilder chain, which is useful when targeting tools that cannot handle invokedynamic, and --release 8 does the same automatically because the factory did not exist then.

consoleruns offline
java -Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles=true Main     # recent JDKs: writes the proxy classes to disk
javac -XDstringConcat=inline Main.java                                  # old StringBuilder chain instead of invokedynamic
javac --release 8 Main.java                                             # same effect, because the factory did not exist in 8
"Why does a lambda that captures nothing behave like a singleton, and why should I care?"

When a lambda uses no local variables and no this, the metafactory returns a call site bound to a single pre-built instance, because every evaluation would produce an identical object. So Runnable r = () -> {} in a loop allocates nothing after the first time.

capturing versus non-capturingruns offline
Runnable a = () -> {};                    // captures nothing: one shared instance, no allocation per evaluation
Runnable b = () -> System.out.println(n); // ❌ captures n: a new instance on every evaluation
// Result: whether a == a2 for two evaluations is unspecified; never rely on lambda identity.

A capturing lambda must allocate a new instance each time, holding the captured values in fields. I care for two reasons.

First, performance: turning a capturing lambda into a non-capturing one, for example by passing the value as a method parameter, removes an allocation on a hot path.

Second, identity: code that uses lambdas as map keys or listener tokens must not rely on either behaviour, because the specification deliberately leaves it unspecified.

"What else in the JDK rides on invokedynamic today?"

Records get their equals, hashCode and toString through java.lang.runtime.ObjectMethods as a bootstrap, so the class file holds no hand-written implementation. Pattern matching for switch uses java.lang.runtime.SwitchBootstraps.typeSwitch and enumSwitch to build the dispatch. Method references use the same lambda metafactory. And the whole java.lang.invoke machinery, method handles and VarHandle, is what the JVM's own Method.invoke has used since JDK 18. So the instruction is now the standard way for the language to add features without adding JVM instructions.

Q3 · Scenario. "A Kubernetes pod crashes at startup with UnsupportedClassVersionError: class file version 65.0, this version of the Java Runtime only recognizes class file versions up to 61.0. It runs fine on the developer's laptop. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom decoded: the class file's major version is 65, which means it was compiled for JDK 21, and the runtime only accepts up to 61, which is JDK 17. The table worth knowing is 52 for Java 8, 55 for 11, 61 for 17, 65 for 21 and 69 for 25. So a JDK 21 compiler produced the class and a JDK 17 runtime is trying to load it. The laptop has 21 installed, so it works there.
  2. Evidence: the error names the class, so I check who compiled it. javap -v -cp app.jar com.acme.Main | grep major shows the application's own version. java -version inside the container, or the base image tag in the Dockerfile, shows the runtime. If the class is from a dependency, unzip -p lib.jar META-INF/MANIFEST.MF often states the build JDK.
  3. Causes, ranked: a multi-stage Dockerfile that builds with a maven:3-eclipse-temurin-21 image and runs on eclipse-temurin:17-jre; the build using -source/-target 21 or maven.compiler.release=21 after someone bumped it without touching the image; a newly upgraded library whose latest release requires 21; a CI runner with a different default JAVA_HOME than the developer.
  4. Fix: decide which JDK is the target and make both sides agree. Either move the runtime image to 21, or compile with --release 17, which also refuses any API that did not exist in 17, unlike -target, which happily compiles calls to 21-only methods and then fails at runtime with NoSuchMethodError.
  5. Prevention: one variable for the Java version shared by the build and the base image, an enforcer rule requireJavaVersion, and a smoke test in CI that starts the actual image, because the laptop never runs the image.

Picture it the two JDKs in the pipeline, the class file number each one speaks, and the failure and fix line for line.

The setup: a multi-stage Dockerfile that builds on one JDK and runs on another.

Dockerfileruns offline
# compiles with JDK 21 -> class files are version 65
FROM maven:3-eclipse-temurin-21 AS build
RUN mvn -q package

# ❌ TRAP: runs on JDK 17, which reads up to 61
FROM eclipse-temurin:17-jre
COPY --from=build /app/target/app.jar /app.jar
CMD ["java", "-jar", "/app.jar"]

Make the invisible visible: the first eight bytes of every class file carry the version, and each JDK has a ceiling.

class file header and version tableruns offline
CA FE BA BE  00 00  00 41        magic, minor = 0, major = 0x41 = 65  -> JDK 21
major: 52 = Java 8 | 55 = 11 | 61 = 17 | 65 = 21 | 69 = 25
JDK 17 runtime accepts major <= 61

The trace: what happens on each machine.

where it works and where it failsruns offline
laptop (JDK 21):   loads app.jar, major 65 <= 65       ✓
CI test stage:     runs on the JDK 21 build image      ✓ (never starts the runtime image)
pod (JDK 17):      loads app.jar, major 65 > 61        ✗ UnsupportedClassVersionError

What you see: the error at startup, quoting both numbers.

consoleruns offline
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/acme/Main has been compiled by a more recent version of the Java Runtime (class file version 65.0), this version of the Java Runtime only recognizes class file versions up to 61.0

Why: the compiler wrote a version the older runtime does not know, and the runtime refuses rather than guess.

The fix: make the runtime image match, or compile for the runtime with --release 17.

Dockerfile and pom.xmlruns offline
# ✅ FIX A: run on the JDK that built it
FROM eclipse-temurin:21-jre

# ✅ FIX B: or keep 17 and compile with <maven.compiler.release>17</maven.compiler.release>

What you see now: the pod starts, and docker run image java -version prints the JDK you chose.

Land it The error is a version mismatch between two JDKs you own, and --release is the flag that makes the compiler enforce the runtime's contract instead of trusting you.

Likely follow-ups
"You fixed the Dockerfile to run on 21 and now a different class fails with the same error but 69.0. What next?"

Now a dependency is compiled for JDK 25. The message names the class, so I find its jar with mvn dependency:tree or by searching the lib directory with unzip -l. Then I check whether the library really requires 25 or shipped a multi-release jar.

A multi-release jar has Multi-Release: true in its manifest and puts newer classes under META-INF/versions/25; a 21 runtime ignores that directory, so it would not fail.

A plain jar with version 69 at the root means the library dropped support for 21, and my choice is to pin the previous release of that library or move the whole service to 25.

I would also check any Java agents in the JAVA_TOOL_OPTIONS, because an agent jar loads before the application and fails the same way.

"What is the difference between -source, -target and --release?"

-source sets which language features the parser accepts. -target sets the class file version written.

Neither restricts which library classes you can call, so with a JDK 21 compiler and -target 17 you can compile a call to List.reversed(), a 21 method, and it fails at runtime on 17.

The same call, list.reversed(), compiled by a JDK 21 javac for a 17 runtime.
Compiler flagsCompile resultRun on JDK 17
-source 17 -target 17Compiles (a warning about the system modules path)Fails: NoSuchMethodError
--release 17Compile error: cannot find symbol reversed()Never reaches runtime

--release 17 sets both and additionally compiles against a stored signature of the 17 platform API, kept in the JDK's ct.sym file, so that call is a compile error. In Maven that is maven.compiler.release; in Gradle java.toolchain plus options.release.

As of Aug 2026 the JDK 27 compiler still supports --release back to 8, so there is no reason to use the older pair.

"Why did it fail in the pod but not in the CI test stage?"

Because the CI test stage ran mvn test on the build image, which has JDK 21, and never started the runtime image. Tests exercise the code, not the deployment artefact.

The fix in the pipeline is a stage that runs docker run image java -version and a health check against the built container, so the runtime that will serve traffic is the runtime that gets tested.

The same gap hides other classes of bug: a missing native library, a different default locale or time zone, and a JAVA_TOOL_OPTIONS value set only in the image.

Q4. "Walk me through linking and initialisation of a class in order, and tell me exactly what triggers <clinit> and what does not."

Reveal answer

The real test Whether you know the three linking steps by name and can list the initialisation triggers from the language specification, because static-initialisation bugs are diagnosed with that list.

Strong answer After loading, which turns bytes into an internal representation, the JVM links the class in three steps.

Verification checks that the bytecode is safe: every jump lands inside the method, the operand stack never underflows or overflows, each instruction receives operands of the right type, according to the StackMapTable the compiler wrote, and a final method or class is not overridden.

Application classes are verified by default; classes from the boot loader are not, controlled by -XX:BytecodeVerificationRemote and BytecodeVerificationLocal. The old -Xverify:none and -noverify have been deprecated since JDK 13 and only print a warning, so I would not put them in a startup script.

Preparation allocates the static fields and sets them to their default values, zero, false or null; constants with a ConstantValue attribute get their value from the constant pool before any user code runs.

Resolution replaces symbolic references in the constant pool with direct references, and HotSpot does it lazily, one reference at a time when the instruction first executes, which is why a missing class only fails when you reach it.

Initialisation then runs <clinit>, the method javac builds from static field initialisers and static blocks, under the class's initialisation lock, after initialising the superclass.

The triggers are exactly those in JLS 12.4.1:

  • Creating an instance.
  • Calling a static method.
  • Assigning a static field.
  • Reading a static field that is not a compile-time constant.
  • Initialising a subclass.
  • Reflective access such as Class.forName(name).
  • Being the class holding main.

An interface is initialised only when its own non-constant field is used, or when an implementing class initialises and the interface declares default methods.

Not triggers:

  • Foo.class.
  • Creating an array, new Foo[10].
  • Reading a constant such as static final int MAX = 5, which javac inlined at the call site.
  • loader.loadClass("Foo").

Picture it a class with a noisy static block, touched in six ways, and which touches actually run it.

The setup: a class that prints when it initialises, and six lines that mention it.

Config.java and Main.javaruns offline
class Config {
    static final int MAX = 5;                        // compile-time constant: inlined by javac
    static final int TIMEOUT = compute();            // not a constant
    static { System.out.println("Config init"); }
    static int compute() { return 30; }
}

public class Main {
    public static void main(String[] args) throws Exception {
        Class<?> c = Config.class;                   // 1
        Config[] arr = new Config[10];               // 2
        int m = Config.MAX;                          // 3
        ClassLoader.getSystemClassLoader().loadClass("Config");   // 4
        System.out.println("-- no trigger yet --");
        int t = Config.TIMEOUT;                      // 5  ❌ first real trigger
    }
}

Make the invisible visible: the phases a class goes through, and which of them each line reaches.

class lifecycleruns offline
Loading ──► Linking ──────────────────────────────────► Initialization
            ├─ Verification   (is the bytecode safe?)     runs <clinit>:
            ├─ Preparation    (statics get default 0/null) static initialisers + static blocks
            └─ Resolution     (lazy: one reference at a time)

The trace: line by line, did Config's static block run?

trigger traceruns offline
1  Config.class                    ✓ no init (may load)
2  new Config[10]                  ✓ no init (an array of Config is not a Config)
3  Config.MAX                      ✓ no init (the literal 5 was copied into Main)
4  loadClass("Config")             ✓ no init (loading only)
5  Config.TIMEOUT                  ✗ init runs: this is the first trigger

What you see: the print shows up only at line 5.

consoleruns offline
-- no trigger yet --
Config init

Why: initialisation is triggered by use of the class's static state or behaviour, not by mentioning its name.

Land it Loading and linking are lazy and mostly invisible, so the moment a class's static code runs is decided by the first trigger in that list, not by where the class sits in your code.

Likely follow-ups
"How would you see the actual initialisation order in a running service?"

With unified logging: -Xlog:class+init=info prints a line each time a class is initialised, in order, and -Xlog:class+load=info prints the loading with the source jar, so I can see that loading happened long before initialisation.

For a one-off question, a breakpoint or a stack trace printed from a static block shows who triggered it, because the trigger is always at the top of the stack. JFR's jdk.ClassLoad event, off by default, gives the same with timestamps.

When I want to force order deliberately, for example to move all initialisation cost to startup, I call Class.forName("com.acme.Foo") for each class in the main thread before opening the listening port.

"What happens if <clinit> throws?"

The exception is wrapped in ExceptionInInitializerError and thrown to the thread that triggered initialisation, and the class is marked erroneous.

what each use seesruns offline
# illustrative output
1st use, thread A:  java.lang.ExceptionInInitializerError
                    Caused by: java.lang.NullPointerException     <- the real cause, logged once
2nd use, thread B:  java.lang.NoClassDefFoundError: Could not initialize class com.acme.Foo

Every later attempt to use that class, in any thread, fails with NoClassDefFoundError: Could not initialize class com.acme.Foo, and since JDK 17 that error carries the original cause in its message, which older JDKs did not.

The class is never retried and cannot be repaired without a new class loader.

That is why the first error in the logs matters and why catching Throwable around a first use hides the real problem: the second use in another request produces an error that looks like a missing class.

"Why is the constant-inlining rule dangerous with separate compilation?"

Because javac copies the value of a static final primitive or String constant into every class that reads it. If a library defines public static final int TIMEOUT = 30 and I compile against it, my class file contains 30, not a reference to the field.

javap -c of my classruns offline
// my source:  int t = Library.TIMEOUT;
   bipush 30            // ❌ TRAP: the value 30 is baked in; there is no getstatic Library.TIMEOUT
// after the library ships TIMEOUT = 60 and I do NOT recompile:
// Result: my class still uses 30, and nothing fails.

When the library ships a new jar with 60, my class still uses 30 until I recompile, and nothing fails, which is worse than an error. The JVM never resolves the reference because there is none.

The defence is to not expose tunables as constants; wrap them in a static method or a non-final field, which forces a real field access and a real initialisation trigger.

"Does the verifier ever fail on code that javac produced?"

Rarely, and when it does the message is a VerifyError that names the method and the instruction offset.

The usual causes are bytecode-rewriting tools, not javac: an old agent, a coverage tool or a mocking library producing a StackMapTable that no longer matches after it inserted code, or two different tools transforming the same class.

The other cause is a corrupt or truncated class file in a jar. I would reproduce with the agent removed, and if the class is from a build tool, I would dump the transformed bytes and run javap -v on them to see the mismatch.

Q5 · Scenario. "After upgrading a library, the service compiles and passes tests, but in production a request throws NoSuchMethodError and another path throws IncompatibleClassChangeError. How can something that compiled fail like this?"

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom decoded: both errors are linkage errors, meaning a class was compiled against one version of another class and is running against a different one. Java compiles each class separately and records symbolic references, name plus descriptor, which the JVM resolves lazily at first use.

    Compilation only proves that the classes on the compile classpath fit together. It says nothing about the classes on the runtime classpath, and nothing about classes inside dependencies that were compiled years ago against the old version.

  2. Evidence: the error message names the missing method with its full descriptor, for example com.acme.Client.send(Ljava/lang/String;)V. I find which class holds that call from the stack trace, then check where both classes come from at runtime with -Xlog:class+load=info, which prints the source jar of each class, and compare with mvn dependency:tree -Dverbose, which shows conflicts.
  3. Causes, ranked:
    • Pinned transitive dependency: a transitive dependency of the upgraded library was pinned to an older version elsewhere, so Maven's nearest-wins rule kept the old one.
    • Caller compiled against the old API: another library on the classpath calls a method the new version removed or changed. A changed return type counts, because it is part of the runtime descriptor but not of the source signature.
    • Kind of member changed: a class turned into an interface, or a method changed between static and instance. That is what IncompatibleClassChangeError means.
    • Two copies of the class: first-on-classpath order differs between the test run and the container.
  4. Fix: align every dependency on one version with dependencyManagement, remove the duplicate jar, and if a third-party library is genuinely compiled against the old API, either upgrade it or hold the old version until it is.
  5. Prevention: the enforcer plugin's dependencyConvergence rule, a duplicate-class check, and a binary-compatibility report such as japicmp on the library upgrade before merging.

Picture it one library call, compiled against one version and linked against another, with the evidence that exposes the mismatch.

The setup: a library whose method changed return type in the upgrade, and a second library that still calls the old form.

Client.java across two versionsruns offline
// com.acme:client 1.4                          // com.acme:client 2.0.0 (the upgrade)
public void    send(String msg) { ... }         public boolean send(String msg) { ... }   // ❌ TRAP: return type changed

// org.old:plugin 3.1, compiled against client 1.4 and never rebuilt:
client.send("hi");                               // recorded as send:(Ljava/lang/String;)V

Make the invisible visible: the name is the same, but the descriptor the call recorded is not the descriptor the class now has.

descriptors, compile time versus run timeruns offline
call site records:      Methodref com/acme/Client.send:(Ljava/lang/String;)V     ... V = returns void
class on the classpath: send:(Ljava/lang/String;)Z                                ... Z = returns boolean
lookup at first call:   no method with that name AND descriptor                   ✗

The trace: what each stage proved.

where it works and where it failsruns offline
javac of my app             sees client 2.0.0, compiles                      ✓
mvn test                    passes (this path never calls plugin.send)       ✓
org.old:plugin is not rebuilt, still records the old descriptor
production, first request that reaches plugin -> send                        ✗ NoSuchMethodError

What you see: the error at the call, and the dependency tree that explains it.

consoleruns offline
# illustrative output
java.lang.NoSuchMethodError: 'void com.acme.Client.send(java.lang.String)'
    at org.old.Plugin.notify(Plugin.java:57)

$ mvn dependency:tree -Dverbose -Dincludes=com.acme:client
[INFO] +- com.acme:client:jar:2.0.0:compile
[INFO] \- org.old:plugin:jar:3.1:compile
[INFO]    \- (com.acme:client:jar:1.4:compile - omitted for conflict with 2.0.0)

Why: the JVM matches name plus descriptor at the first call, and nothing earlier checks that the loaded class still has the member the caller recorded.

The fix: align everything on one version, and upgrade or replace the library that is built against the old API.

consoleruns offline
# ✅ FIX: manage one client version in dependencyManagement, then upgrade org.old:plugin to a build compiled against 2.0.0
$ mvn dependency:tree -Dverbose -Dincludes=com.acme:client
[INFO] +- com.acme:client:jar:2.0.0:compile
[INFO] \- org.old:plugin:jar:3.2:compile      <- no conflict line any more

What you see now: the same request path succeeds, and -Xlog:class+load=info shows com.acme.Client loading once, from the 2.0.0 jar.

Land it A green compile is a statement about one classpath at one moment, and the JVM will happily link against a different classpath later, one symbolic reference at a time.

Likely follow-ups
"You aligned the versions and the error persists. What next?"

Then the old class is still reaching the JVM from somewhere I did not look.

I would start the service with -Xlog:class+load=info and grep the failing class name; the "source:" part of the line shows the jar, and it may be a shaded copy inside a fat jar, an agent jar, a container shared lib directory, or a WEB-INF/lib that was not rebuilt.

At runtime, Foo.class.getProtectionDomain().getCodeSource().getLocation() from a debug endpoint answers the same question. If the jar is correct, I would check for a relocated package name, because shade plugins rename packages and the stack trace shows the renamed one.

Finally I would confirm the image actually contains the new build with the jar's checksum, because stale images are a common false lead.

"Which library changes are binary compatible and which are not?"

Chapter 13 of the Java Language Specification lists them. Safe: adding methods, fields or classes, widening access, moving a method up to a superclass, adding a default method to an interface.

Breaking: removing anything public, changing a parameter or return type, changing static to instance or the reverse, turning a class into an interface, making a method final or abstract, and narrowing access.

A subtle one is changing a constant's value, which does not fail but leaves stale copies in callers.

Tools that check this automatically against the previous release are japicmp and revapi; I would run one in the library's own build so a breaking change fails there, not in fifty consumers.

"Why did the tests not catch it?"

Because tests ran on the test classpath, which Maven and Gradle build from the same dependency graph as compilation, so it was consistent with itself.

Production had a different graph, most often because the deployable is assembled by a different process: a fat jar with merged dependencies, a container base layer with its own libraries, or a server with shared libraries.

The other reason is laziness of resolution: the failing method was only linked when that code path first ran, and no test executed it.

Both point to the same fix: run integration tests against the real deployable artefact, and use a duplicate-class check so two versions cannot coexist at all.

"How is AbstractMethodError related?"

It is the same family. It appears when an interface or abstract class gained an abstract method in the new version and an older implementation on the classpath does not implement it.

Compilation of the implementation against the old interface succeeded, the JVM linked the class without complaint because class loading does not check that every abstract method is implemented, and the error only fires when the missing method is invoked on that instance.

AbstractMethodErrorruns offline
// library v1: interface Handler { void handle(); }            old jar: class MyHandler implements Handler
// library v2: interface Handler { void handle(); void close(); }   // new ABSTRACT method
handler.handle();   // ✓ works
handler.close();    // ❌ AbstractMethodError: the old MyHandler has no close()
// ✅ FIX in the library: make close() a default method instead

Since JDK 8 library authors avoid it by adding default methods instead of abstract ones, which is precisely why default methods were introduced.

Q6. "Tell me the difference between ClassNotFoundException, NoClassDefFoundError, ExceptionInInitializerError and UnsupportedClassVersionError, mechanically, and the first thing you check for each."

Reveal answer

The real test Whether you know which stage of the class lifecycle each one comes from, because that decides where to look first.

Strong answer ClassNotFoundException is a checked exception thrown by an explicit lookup by name: Class.forName, ClassLoader.loadClass or ServiceLoader. It means a specific loader searched its path and its parents and found no such class.

The first thing I check is which loader did the searching and what that loader can see, because the class may exist on the classpath of a different loader.

NoClassDefFoundError is an error thrown by the JVM itself during resolution, when bytecode already loaded refers to a class that cannot be provided now. It has two faces.

If its cause is a ClassNotFoundException, the class is genuinely missing at runtime although it existed at compile time, so I check the runtime classpath, typically a provided-scope or optional dependency.

If the message reads "Could not initialize class X", the class was found but its initialisation failed earlier, and this error is the JVM refusing to retry; the first thing I do is search the logs backwards for the original ExceptionInInitializerError, which since JDK 17 is also quoted in the message.

ExceptionInInitializerError is thrown once, to the thread that first triggered <clinit>, and wraps whatever the static initialiser threw, so I look at getCause(): a missing configuration value, a null from a static lookup, a failed native library load.

UnsupportedClassVersionError is a ClassFormatError raised during loading when the class file's major version is newer than the runtime accepts; the message quotes both numbers, and the first check is the compiler version versus the runtime version, as in the version table 61 for JDK 17, 65 for 21, 69 for 25.

Picture it which stage each error comes from, then the double failure of one class, line by line.

The setup: the code below throws all four failures in different places.

the four failures, and what each one tells youruns offline
// ClassNotFoundException — CHECKED. Someone asked for a class BY NAME and the
// loader could not find it. Reflection, a service loader, a JDBC driver string.
Class.forName("com.acme.Missing");     // -> ClassNotFoundException

// NoClassDefFoundError — an ERROR. The class was present at COMPILE time and is
// missing (or failed to initialise) now. This is a packaging/classpath problem.
public void use() { new Helper(); }    // Helper.class was on javac's path,
                                       // not on the runtime path -> NoClassDefFoundError

// ExceptionInInitializerError — a static initialiser THREW.
class Config {
    static final String URL = System.getenv("URL").trim();  // ❌ TRAP: NPE if URL unset
}                                       // -> ExceptionInInitializerError, caused by NPE

// ...and the second use is the confusing one: the class is now marked
// ERRONEOUS forever, and every LATER touch throws a different exception:
Config.URL;   // first access  -> ExceptionInInitializerError
Config.URL;   // second access -> NoClassDefFoundError: Could not initialize class Config

// NoSuchMethodError — the class IS there, but not the member you compiled
// against. A binary-incompatible library upgrade. Compiles fine; fails at the call.

Make the invisible visible: each error next to the stage that raises it.

Error, stage, and the first thing to check.
ErrorStage that raises itWho throws itFirst check
ClassNotFoundExceptionA lookup by nameYour code: Class.forName, loadClass, ServiceLoaderWhich loader searched, and what it can see
NoClassDefFoundErrorResolution of a class already referencedThe JVMRuntime classpath, or the earlier initialisation failure
ExceptionInInitializerErrorInitialisation (<clinit>)The JVM, oncegetCause()
UnsupportedClassVersionErrorLoading (parsing the class file)The JVMCompiler version against runtime version

The trace: one class, three touches.

what each touch of Config seesruns offline
touch 1 (thread main):    run <clinit> -> NullPointerException inside it    ✗ ExceptionInInitializerError, class marked erroneous
touch 2 (thread worker):  class is erroneous, no retry                       ✗ NoClassDefFoundError: Could not initialize class Config
touch 3 (any thread):     same as touch 2                                    ✗ NoClassDefFoundError, forever

What you see: the log shows the real cause once and the secondary error after it.

consoleruns offline
# illustrative output
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException: Cannot invoke "String.trim()" because the return value of "java.lang.System.getenv(String)" is null
    at Config.<clinit>(Config.java:2)
...
Exception in thread "worker-2" java.lang.NoClassDefFoundError: Could not initialize class Config

The fix: find the first occurrence in the log, and stop initialisers from throwing on missing configuration.

console and Config.javaruns offline
$ grep -n -m1 ExceptionInInitializerError app.log          # ✅ FIX 1: the first failure is the real one

// ✅ FIX 2: fail with a clear message, at a known place, outside <clinit>
static String url() {
    String v = System.getenv("URL");
    if (v == null) throw new IllegalStateException("env var URL is required");
    return v.trim();
}

What you see now: every caller gets the same readable IllegalStateException: env var URL is required, and the class never becomes erroneous.

Read the double failure on Config. It is why a startup log often shows a NoClassDefFoundError with no obvious cause — the real exception happened once, earlier, on the first touch, and every subsequent thread sees only the secondary error. Always search the log for the first occurrence.

Land it One is a failed search, one is a failed link, one is a failed static initialiser, and one is a failed parse, and reading the message tells you which stage before you open a single file.

Likely follow-ups
"Why does the same missing class produce an exception in one place and an error in another?"

Because of who is asking. When my code asks by name, the class library is doing a lookup that can reasonably fail, so it reports a checked exception I am expected to handle, for example an optional plugin that is not installed.

When the JVM resolves a constant pool entry while executing an instruction, there is no reasonable recovery inside the method, so it throws an error.

Frameworks turn one into the other all the time: Spring's @ConditionalOnClass deliberately calls Class.forName to probe, catching the exception, whereas a plain new Foo() in a bean would hit the error.

The rule of thumb is that a probe should use forName with initialisation off, so probing never runs static code.

"How would you find which jar should have contained the missing class?"

Locally, mvn dependency:tree and then search the jars: a shell loop over the lib directory with unzip -l and grep for the class path, or an IDE's "find class in dependencies".

In a running system, -Xlog:class+load=info shows every class that did load with its source, so the absence of the neighbours of the missing class from the same package tells me the whole jar is absent.

Then I compare the runtime classpath with the build: jcmd <pid> VM.system_properties prints java.class.path, and jcmd <pid> VM.classloaders shows the loader tree.

Most of the time the answer is a dependency scoped as provided or optional, or a fat jar built with the shade plugin's minimize option, which dropped a class only reached by reflection.

find the jar by handruns offline
for j in lib/*.jar; do
  unzip -Z1 "$j" | grep -q '^com/acme/Foo.class$' && echo "$j"     # prints the jar that has the class
done
"What about NoClassDefFoundError for a class that is clearly in the jar?"

Then it is almost always the "Could not initialize class" case, or a case-sensitivity or package mismatch. For the first, the class is there, but a previous attempt to initialise it threw, often on a different thread minutes earlier, and this thread gets the cached failure.

The search term is the class name together with ExceptionInInitializerError in the earlier logs. If nothing was logged because the first failure was swallowed, I add -Xlog:class+init=info or set a breakpoint in the static initialiser.

The mismatch case appears when the file path inside the jar does not match the package declaration, which a hand-built jar or a broken shade relocation can cause; jar tf shows it immediately.

Q7 · Design. "We have a large service with 400 transitive dependencies and we keep getting runtime linkage errors after upgrades. Design our dependency-conflict strategy."

Reveal answer

Strong answer Requirements and assumptions: builds must be reproducible, exactly one version of every artefact and one copy of every class must reach the runtime classpath, an upgrade must fail in the build rather than in production, and the team must be able to see why any given jar is present.

Design, in layers:

  1. One source of versions. A bill of materials, a BOM, is a parent artefact that fixes the version of every library we use, imported into dependencyManagement. No module chooses a version on its own, so Maven's nearest-wins rule has nothing left to decide.
  2. Build gates. The enforcer plugin with dependencyConvergence fails the build if two paths require different versions. banDuplicateClasses from the extra enforcer rules fails it if two jars contain the same class name. In Gradle the equivalents are failOnVersionConflict() and a duplicate-class task.
  3. Visibility. mvn dependency:tree -Dverbose goes in the pipeline output. jdeps reports split packages and use of JDK internals, because both become hard errors the day we adopt modules.
  4. Shading, sparingly. Shading means copying a dependency into our jar under a renamed package with the shade plugin's relocation feature. Use it only in the final deployable, and only for a library whose version we cannot align with a neighbour. Never use it in a library we publish, because a shaded library forces its private copy onto every consumer.
  5. JPMS where feasible. A modular build detects split packages at startup instead of at first use. With 400 dependencies many are automatic modules, so I would introduce it per service, not globally.

Trade-offs: convergence rules are noisy at first and someone owns the BOM full time for a quarter.

What I would not do: exclude transitive dependencies one by one to make the build pass, rely on classpath ordering, or shade to hide a conflict I have not understood.

Picture it the conflict, the layers that stop it, and the build failure that replaces the production failure.

The setup: two paths in the dependency graph that want different versions of the same library.

dependency graphruns offline
app
 ├─ service-a 1.2  ──► guava 33.0.0-jre
 └─ service-b 3.4  ──► guava 31.1-jre         ❌ TRAP: two versions requested, only one reaches the classpath

Make the invisible visible: the layers, as a pipeline a change must pass before it can reach production.

strategy as layersruns offline
BOM (one version per library)  ──►  enforcer: dependencyConvergence + banDuplicateClasses
        ──►  dependency:tree and jdeps in the pipeline  ──►  smoke test on the real deployable
        (shade only inside the final jar, only when a conflict cannot be aligned)

The trace: one upgrade moving through the layers.

upgrade traceruns offline
bump guava in the BOM                           ✓ one place to change
service-b still asks for 31.1                    ✗ dependencyConvergence fails the build   <- caught here, not in production
align service-b, build is green                  ✓
smoke test starts the real image                 ✓

What you see: the gate failing in the build log.

consoleruns offline
# illustrative output
[WARNING] Rule 0: DependencyConvergence failed with message:
Dependency convergence error for com.google.guava:guava:33.0.0-jre paths to dependency are:
  app -> service-a:1.2 -> guava:33.0.0-jre
and
  app -> service-b:3.4 -> guava:31.1-jre

The fix: pin the version once in the BOM, then fix the module that disagrees.

pom.xml (BOM import)runs offline
<dependencyManagement><dependencies>
  <dependency><groupId>com.acme</groupId><artifactId>platform-bom</artifactId>
              <version>2026.1</version><type>pom</type><scope>import</scope></dependency>   <!-- ✅ FIX: one source of versions -->
</dependencies></dependencyManagement>

What you see now: the enforcer passes, and the resolved tree shows one guava version.

Land it Move every version decision into one file and make the build fail whenever two copies of anything could reach the JVM, because the JVM will never fail early for you.

Likely follow-ups
"The requirement changes: 200 services must share a company platform library that itself drags in Jackson and Netty. What changes?"

The platform team publishes the BOM and every service imports it; the platform library declares its own dependencies with versions taken from that same BOM, so a service and the platform can never disagree.

The platform does not shade Jackson, because services need to register their own modules with the shared ObjectMapper.

Upgrades run as a BOM version bump per service, with a binary-compatibility report from japicmp published with each platform release so a service knows whether the bump is safe.

For the one case where a service genuinely needs a different Netty, the answer is a documented exception with a shaded copy in that service, not a fork of the platform.

"What would you cut under time pressure?"

I would keep two things: the BOM, because it removes most conflicts at their source, and the duplicate-class check, because a duplicate class is the one failure that stays invisible until production.

I would drop dependencyConvergence for the first weeks, since it fails on every existing disagreement and blocks the team, and instead run it in report mode. I would defer JPMS and jdeps entirely.

I would not cut the smoke test that starts the real deployable, because it is the only thing that catches problems introduced by the packaging step rather than by the dependency graph.

"How do you detect duplicate classes across jars by hand?"

List every class in every jar and count names that appear more than once. A shell one-liner does it: for each jar run unzip -Z1, filter to .class, sort the union and pipe through uniq -d.

duplicate classes by handruns offline
for j in lib/*.jar; do unzip -Z1 "$j" | grep '\.class$'; done | sort | uniq -d
# illustrative output
com/google/common/base/Strings.class       <- present in two jars: a real conflict
module-info.class                          <- usually harmless

That prints class paths present in two or more jars; most hits are harmless module-info.class entries, and the rest are the real conflicts, typically an old javax API duplicated by a jakarta or JDK copy, or a library that bundled its dependencies without relocating them.

In the build, the duplicate-finder-maven-plugin and the enforcer's banDuplicateClasses rule do the same and fail the build, with an ignore list for the known-harmless cases.

"When is shading the right answer?"

When the deployable is the end of the line and one library needs a version of a dependency that the rest of the application cannot use, for example a cloud SDK pinned to an old HTTP client.

Then relocate that dependency under a private package inside the deployable so both versions coexist with different names and the JVM sees no conflict. It is also reasonable for a Java agent, which must not pollute the application's classpath.

It is wrong for a library published to others, unless everything is relocated, and it is wrong as a way to avoid understanding a conflict, because relocated classes cannot exchange objects with the un-relocated version, which shows up later as a ClassCastException between two classes with the same simple name.

Q8. "Explain how two classes can deadlock each other during static initialisation, what lock is involved, and how it looks in a thread dump."

Reveal answer

Strong answer The JVM guarantees that each class is initialised exactly once, and it does so with a per-class initialisation lock.

The procedure in section 5.5 of the JVM specification is:

  1. Acquire the class's lock.
  2. If the class is not yet initialised, mark it as "in progress by this thread" and release the lock.
  3. Run <clinit>.
  4. Mark the class done and notify waiters.

If another thread finds the class in progress by someone else, it waits on the lock until it is done.

If the same thread re-enters, because <clinit> referred back to the class, it continues immediately and sees whatever static fields have been set so far. That is the source of the famous null static seen from a constructor called in a static block.

Now the deadlock.

Class A's static initialiser reads a static field of B, and B's static initialiser reads a static field of A. Thread one touches A first, marks it in progress, and inside <clinit> reaches B.

At the same moment thread two touches B first, marks it in progress, and reaches A. Thread one now waits for B, which thread two owns, and thread two waits for A, which thread one owns.

Neither will ever finish, and the JVM does not detect it, because these locks are not monitors that the deadlock detector understands.

In a thread dump from jcmd <pid> Thread.print, both threads have <clinit> frames, the top frame is the line that touched the other class, and on recent JDKs a line under the frame says "waiting on the Class initialization monitor for com.acme.A".

Older dumps just show the thread apparently running, with no lock listed, which is why this bug is so often misread as a hang in user code.

Picture it two threads entering two classes in opposite order, the state of each class, and the thread dump that results.

The setup: the two classes below, entered by two threads at the same moment.

two classes deadlocking in their static initialisersruns offline
// Each class's <clinit> runs under an initialisation lock on that CLASS OBJECT.
// The lock is held for the whole initialiser, and initialisation is one-shot.

class A {
    static final B DEP = new B();     // thread 1 holds A's lock, wants B's
    static final String NAME = "A";
}

class B {
    static final String FROM_A = A.NAME;   // thread 2 holds B's lock, wants A's
}

// Thread 1: touches A -> takes A's init lock -> runs <clinit> -> touches B -> blocks
// Thread 2: touches B -> takes B's init lock -> runs <clinit> -> touches A -> blocks
// Classic deadlock, and jstack shows it as threads "in <clinit>" with no
// Java-level lock visible, because the init lock is not a monitor you can see.

// SINGLE-THREADED it does NOT deadlock — the JVM allows a thread to re-enter
// a class it is already initialising, and you get a partially initialised
// class instead: A.NAME reads as null. Which is arguably worse, because it is silent.

// FIXES
// 1. Remove the cycle. Extract the shared constant into a third class.
// 2. Make initialisation lazy and explicit, not static.
// 3. Do not do real work in static initialisers at all — that is the rule.

Make the invisible visible: the initialisation state each class is in when the threads stop making progress.

class initialisation stateruns offline
class A:  state = IN PROGRESS by Thread 1     (its <clinit> is waiting for B)
class B:  state = IN PROGRESS by Thread 2     (its <clinit> is waiting for A)

The trace: the interleaving, one row per step.

thread interleavingruns offline
step | Thread 1                                  | Thread 2
-----+-------------------------------------------+------------------------------------------
 1   | touch A: take A's init lock               |                                           ✓
 2   |                                           | touch B: take B's init lock               ✓
 3   | A.<clinit> needs B: wait for B            |
 4   |                                           | B.<clinit> needs A: wait for A
 5   | waits for B, owned by Thread 2            | waits for A, owned by Thread 1            ✗ deadlock

What you see: both threads stuck in <clinit>, with no Java lock listed in the older dump format.

jcmd Thread.printruns offline
# illustrative output
"T1" #21 prio=5 tid=0x... nid=0x... runnable
   java.lang.Thread.State: RUNNABLE
	at B.<clinit>(B.java:2)             <- the top frame touched the other class
	at A.<clinit>(A.java:2)
"T2" #22 prio=5 tid=0x... nid=0x... runnable
	at A.<clinit>(A.java:1)
	at B.<clinit>(B.java:2)

Why: each thread owns one class's initialisation lock and needs the other, and the JVM does not report this lock as a monitor.

The fix: remove the cycle by making one side lazy, using the holder idiom.

holder idiomruns offline
class A {
    static B dep() { return Holder.DEP; }                 // ✅ FIX: B is created when dep() is first called
    private static class Holder { static final B DEP = new B(); }
}

What you see now: neither <clinit> waits on the other, so a thread dump shows no stuck initialisers.

The single-threaded case is the one that ships. No deadlock, no error, just a null in a static final field that the compiler promised could never be null — and it only reproduces when the classes are touched in one particular order.

Land it Class initialisation is a lock you never wrote, so a cycle between two static initialisers is a deadlock that no tool will flag for you; the fix is to break the cycle, not to add synchronisation.

Likely follow-ups
"How do you fix it once found?"

Break the cycle in the code or fix the order at startup.

The code fix is to make one side lazy: move the cross-reference out of the static initialiser into a method, or use the holder idiom, a nested class Holder whose only job is to hold the static field, so the field is created when first read, outside the outer class's <clinit>.

Enums that reference each other's constants are a classic instance and need the same treatment. The startup fix is to initialise both classes in one thread, in a fixed order, before any worker thread exists, with Class.forName calls in main.

I prefer the code fix, because the startup fix silently stops working when someone adds a new entry point.

"Why does the same-thread case not deadlock, and what goes wrong instead?"

The specification says that if the initialising thread itself re-enters, initialisation "completes normally" for that access, because waiting on yourself would always hang. So the code proceeds against a half-built class.

Typical damage: a static Map declared after a static block that calls a method which writes to that map; the map is still null, so a NullPointerException comes out of code that looks obviously safe.

Or a subclass instance created in the superclass's static block, which reads the subclass's statics as defaults. The signature is an exception from a static initialiser whose stack trace passes through <clinit> twice. Ordering the static declarations, or moving the work into a method, fixes it.

"Does this interact with virtual threads?"

Yes, in one specific way. A virtual thread that blocks waiting for another thread's class initialisation cannot be unmounted from its carrier thread; this is one of the remaining pinning cases even after JEP 491 in JDK 24 removed pinning for synchronized.

If a static initialiser does slow work, such as a network call, and hundreds of virtual threads hit that class at once during a burst, they pin the carrier threads, the scheduler with parallelism equal to the CPU count is starved, and the whole service stalls.

The JFR event jdk.VirtualThreadPinned records the reason. The fix is the same as always: no slow or blocking work in static initialisers, and initialise eagerly at startup.

cause of the stallruns offline
200 virtual threads touch Slow.class at once
  1 thread runs Slow.<clinit> (network call, 2 s)       ✓ owner
  199 wait for the init lock, carriers cannot be released ✗ pinned; the scheduler runs out of carriers

Q9 · Scenario. "A service hangs on startup. A thread dump shows several threads sitting in <clinit> frames. Take me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom decoded: threads are inside static initialisers, so either one initialiser is doing slow or blocking work and the others are waiting on its class initialisation lock, or two initialisers are waiting on each other.
  2. Evidence: two dumps with jcmd <pid> Thread.print thirty seconds apart. I look for the one thread whose <clinit> frame is not waiting on a class initialisation monitor but is inside something else, a socket read, a SecureRandom seed, a Thread.join, a native frame; that is the owner. The others show "waiting on the Class initialization monitor for" that class. If instead two owners each wait for the other's class, it is the cycle deadlock. -Xlog:class+init=info on a restart shows which class never finished initialising.
  3. Causes, ranked:
    • Blocking I/O in a static block: it opens a connection or resolves a hostname, which blocks when a dependency or DNS is down.
    • Self-join: a static initialiser starts a thread and joins it, while that thread calls a static method of the same class and so waits for an initialisation that cannot finish until it returns.
    • Entropy: a SecureRandom seeded from /dev/random on a virtual machine with no entropy, set through securerandom.source.
    • Cycle: a cross-class initialisation cycle across two threads.
    • Native load: a native library load in a static block hanging inside JNI.
  4. Fix: for slow work, move it out of static initialisation into an explicit start method called at a known point; for the self-join, never wait on another thread from a static block; for the entropy case, use file:/dev/urandom; for the cycle, break it as in Q8.
  5. Prevention: a review rule that static initialisers only build constants, an integration test that starts the service with the network unreachable to see what blocks, and eager initialisation of known-heavy classes on the main thread so a hang is visible before workers exist.

Picture it the dump of a hung startup, with the one owner and its victims marked, and the same code before and after moving the blocking call.

The setup: a static block that calls a dependency which is down.

Directory.javaruns offline
class Directory {
    static final Map<String, String> USERS = fetchAll();   // ❌ TRAP: network call inside <clinit>

    static Map<String, String> fetchAll() { return client.get("https://dir.internal/users"); }   // blocks while the service is down
}

Make the invisible visible: which thread owns the class, and who waits for it.

who owns the initialisation lockruns offline
Directory:  state = IN PROGRESS by "main"         <- the owner, stuck in a socket read
"worker-1", "worker-2", ... wait for Directory    <- victims; they are not the problem

What you see: the owner is inside something else; the victims show a class-initialisation wait.

jcmd Thread.print (two dumps, 30 s apart, same stacks)runs offline
# illustrative output
"main" #1 prio=5 runnable
	at java.base/sun.nio.ch.SocketDispatcher.read0(Native Method)
	at com.acme.Http.get(Http.java:44)
	at com.acme.Directory.fetchAll(Directory.java:9)
	at com.acme.Directory.<clinit>(Directory.java:5)     <- owner: <clinit> that is NOT waiting for a class
"worker-1" #31 prio=5 runnable
	at com.acme.Handler.handle(Handler.java:12)          <- victim: waits for Directory's initialisation

Why: the initialisation lock is held until <clinit> returns, so one blocked initialiser blocks every thread that needs the class.

The fix: move the slow work to an explicit start method called at a known point.

Directory.java (fixed)runs offline
class Directory {
    private static volatile Map<String, String> users;
    static void start() { users = client.get("https://dir.internal/users"); }   // ✅ FIX: explicit, loggable, can time out
    static Map<String, String> users() { return users; }
}
// main(): Directory.start();  before opening the listening socket

What you see now: if the dependency is down, start() fails or times out on the main thread with a clear stack trace, and no worker is stuck on a class lock.

Land it Find the one thread that owns an initialisation lock and is not waiting for one; everyone else is a victim, and fixing the owner fixes the hang.

Likely follow-ups
"You moved the blocking call out of the static block and it still hangs. What next?"

Then there is a second owner I did not see.

I would take the dump again and this time list every <clinit> frame across all threads, including daemon threads and threads with framework names, because the owner is frequently a scheduler or metrics thread, not a request thread.

I would also check native frames with jcmd <pid> Thread.print -l and, if the owner is inside a native call, use jstack -m or a gdb backtrace to see the native library.

If the owner is a virtual thread it may not appear in a classic dump at all, so I would use jcmd <pid> Thread.dump_to_file -format=json, which includes virtual threads.

Finally, I would confirm it is not the JVM's own class loading waiting on a network filesystem where the jars live.

"How would you tell a slow initialiser from a deadlocked one without a thread dump?"

With logging. -Xlog:class+init=info prints a line at the start of each class's initialisation; a slow one is the last line printed and no error follows, and a deadlock shows two classes started and neither finished.

what the class+init log shows (shape, not exact text)runs offline
slow initialiser:  ... started Directory                                          <- last line, no error, still running
deadlock:          ... started A, started B                                       <- neither A nor B ever "finished"

JFR helps too: record with jcmd <pid> JFR.start, and the jdk.ExecutionSample events show where the owner thread spends its time, a socket read versus a wait.

CPU usage is a rough tell: a slow initialiser doing I/O and a deadlock both sit at zero CPU, but a slow one eventually finishes when the dependency comes back, while a deadlock never does.

In practice I would still take the dump, because it takes one command and is definitive.

"What is the safest place for one-time expensive setup if not a static block?"

An explicit lifecycle. In a framework application, a bean's initialisation method or an application-ready listener, which runs on the main thread in a defined order, can time out, can be logged, and can be retried.

Without a framework, a start() method on the component called from main before the listening socket opens. For lazily created heavy objects, the holder idiom gives thread-safe laziness but still runs under the class initialisation lock, so it only suits work that cannot block.

If I need laziness with blocking work, I use a CompletableFuture stored in a static field, started at boot, and join() it at first use, so waiting threads wait on a future with a timeout rather than on a class lock without one.

Q10. "What is a hidden class, how does it differ from what Unsafe.defineAnonymousClass used to do, and who uses them?"

Reveal answer

Strong answer A hidden class is a class defined at runtime that cannot be found by name. It was introduced by JEP 371 in JDK 15 through MethodHandles.Lookup.defineHiddenClass(bytes, initialize, options). Three properties make it different from a normal class defined with defineClass:

  1. Not findable. Class.forName and loader.loadClass never return it, and no other class's constant pool can refer to it. It can only be used through the Class object or a method handle the definer holds. Its name carries a suffix such as Foo/0x0000021e to make that explicit.
  2. Unloadable on its own. Unless defined with the STRONG option, the class is unloaded as soon as nothing references it, even while the loader lives on. A normal class never does that.
  3. Nestmate access. With the NESTMATE option it joins the nest of the lookup class, so it can access that class's private members without reflection tricks.

The predecessor, Unsafe.defineAnonymousClass, gave the JDK's own lambda implementation the same abilities with no specification. It also had constant pool patching that nobody else could rely on. It was deprecated in JDK 15 and removed in JDK 17.

Users today:

  • Lambdas: LambdaMetafactory defines every lambda proxy as a hidden nestmate class, which is why a stack trace shows Foo$$Lambda/0x....
  • Method handles: the implementation defines its lambda forms this way.
  • Proxy, mocking and persistence libraries: ByteBuddy, Mockito and frameworks generating accessors use it to reach private members and to let generated classes be collected.

For a generated class that must be findable by name, for example something referenced from other generated code, the sibling method Lookup.defineClass from JDK 9 defines an ordinary class in the lookup's runtime package instead.

Picture it a hidden class being defined, refusing to be found by name, and being collected while a normal class stays.

The setup: defining a hidden class next to the current class, then trying to find it by name.

HiddenDemo.javaruns offline
byte[] bytes = Files.readAllBytes(Path.of("Greeter.class"));       // must be in the lookup class's package
MethodHandles.Lookup lookup = MethodHandles.lookup();
Class<?> hidden = lookup.defineHiddenClass(bytes, true, MethodHandles.Lookup.ClassOption.NESTMATE).lookupClass();
System.out.println(hidden.getName());
System.out.println(hidden.isHidden());
Class.forName(hidden.getName());      // ❌ TRAP: a hidden class has no findable name

Make the invisible visible: who keeps each kind of class alive.

memory pictureruns offline
app class loader (lives until the JVM exits)
  ├─ com.acme.Orders            normal class: strongly held by the loader, lives as long as the loader
  └─ (no entry for the hidden class: the loader does not know it)

Class object ◄── your reference            hidden class Orders$$Lambda/0x...: collected when the last reference goes

What you see: the suffixed name, true, and the exception from the name lookup.

consoleruns offline
# illustrative output
com.acme.Greeter/0x000001a2b3
true
Exception in thread "main" java.lang.ClassNotFoundException: com.acme.Greeter/0x000001a2b3

Why: the hidden class is deliberately not registered with its loader, so a name lookup has nothing to return.

The fix: use the Class object or a method handle you kept, or use Lookup.defineClass when other code must find it by name.

HiddenDemo.java (fixed)runs offline
MethodHandle ctor = lookup.findConstructor(hidden, MethodType.methodType(void.class));   // ✅ FIX: keep a handle
Object g = ctor.invoke();
// or: Class<?> named = lookup.defineClass(bytes);   // ordinary class, findable by name

What you see now: the instance is created through the handle, and a stack trace through a lambda shows the hidden-class name, for example Orders$$Lambda/0x...apply(Unknown Source).

Land it Choose a hidden class when generated code should be private to its creator and garbage-collectable on its own; choose defineClass when other code must be able to name it.

Likely follow-ups
"Why does unloading matter for a framework that generates classes?"

Because normal classes live as long as their loader, and in a long-running service the application loader lives forever.

A framework that generates a class per request shape, per expression or per mock would fill metaspace with classes that can never be collected, and eventually fail with OutOfMemoryError: Metaspace or "Compressed class space".

A weak hidden class is collected when the last reference to it goes, so churn is bounded by live usage. I would verify it with -Xlog:class+unload and by watching jcmd <pid> VM.metaspace under load.

The trade-off is that a class you wanted to keep, such as a cached accessor, must be held by a strong reference somewhere, or defined with the STRONG option.

"How does the nestmate option change access checks?"

Nestmates, from JEP 181 in JDK 11, are the classes that share private access, originally an outer class and its nested classes, recorded in the NestHost and NestMembers attributes. The JVM checks private access by asking whether two classes are in the same nest.

A hidden class defined with NESTMATE is added to the lookup class's nest dynamically, so its bytecode can call the host's private methods directly with invokevirtual, with no accessor methods and no setAccessible.

That is what lets a lambda body be a private method of the enclosing class and still be called from the generated proxy at full speed. It requires a lookup with private access to the host, which is how the host consents to it.

"Can I see hidden classes in tooling, and do they show up in class counts?"

Yes. Class.isHidden() reports it, and the names with a slash and hexadecimal suffix are the tell in stack traces, JFR views and heap dumps. jcmd <pid> VM.classloader_stats counts them per loader, and -Xlog:class+load shows them loading with source "__JVM_LookupDefineClass__".

They count towards metaspace like any class, and there are usually a lot of them: a mid-sized service has several thousand lambda proxies after warm-up.

In a heap dump opened in Eclipse MAT they appear as class objects whose loader is the app loader; a huge number of distinct hidden classes with similar names is the signature of a framework generating per-call code, which is a bug to raise with that framework.

"Why not use Instrumentation.redefineClasses for the same purposes?"

Different job. Redefinition swaps the bytecode of an existing class in place, and it is restricted to changing method bodies; it cannot add methods or fields or change the hierarchy, and every live instance keeps its shape.

It exists for agents and debuggers doing hot code replace. Hidden classes create new classes, with any shape, that coexist with old ones and can be collected. A framework that needs a new type per generated accessor wants the second.

Redefinition also needs an agent attached and triggers deoptimisation of every compiled method that inlined the old code, which is a cost I would not pay on a hot path in a service.

Drill · Class loaders, delegation & isolation

This group tests whether you understand that a class's identity includes the loader that defined it, and whether you can use that fact to build isolation on purpose and to diagnose it when it happens by accident.

Q11. "Describe the class loader hierarchy since JDK 9, how delegation works, and the difference between loadClass, findClass and defineClass."

Reveal answer

The real test Whether you can name the three built-in loaders and explain who defines a class versus who was merely asked for it.

Strong answer There are three built-in loaders:

  • Bootstrap: part of the JVM, written in native code, appears as null from Java, and loads the core modules such as java.base from the runtime image.
  • Platform: ClassLoader.getPlatformClassLoader() replaced the old extension loader in JDK 9 and defines the remaining platform modules, for example java.sql and java.net.http.
  • Application: ClassLoader.getSystemClassLoader() defines the classpath and any application modules.

Since JDK 9 these are not URLClassLoader instances, so old code that cast the system loader to add jars at runtime breaks.

Delegation is parent-first. loadClass(name) does three things in order:

  1. Calls findLoadedClass to see if this loader already defined it.
  2. Asks the parent.
  3. Only if the parent throws ClassNotFoundException, calls its own findClass.

Custom loaders override findClass to locate the bytes and then call defineClass, which hands the bytes to the JVM, creates the Class object and records this loader as the defining loader.

That distinction matters: the defining loader is the one whose defineClass created the class; an initiating loader is any loader that was asked and returned it, possibly by delegating. Class identity and access rules use the defining loader only.

For named modules the built-in loaders skip the parent walk and map the package name directly to the module's loader, which is why a class in java.sql is found without asking the bootstrap loader first.

Finally, a runtime package is the pair of package name and defining loader, so two classes in com.acme.util defined by different loaders are in different packages and cannot see each other's package-private members; the attempt fails with IllegalAccessError.

Picture it the loader tree, one delegation walk, and what happens when the same class is defined by two different loaders.

The setup: a program that asks three loaders about three classes.

LoaderDemo.javaruns offline
System.out.println(String.class.getClassLoader());             // java.base
System.out.println(java.sql.Connection.class.getClassLoader()); // java.sql
System.out.println(LoaderDemo.class.getClassLoader());          // your code

Make the invisible visible: the hierarchy, as jcmd <pid> VM.classloaders prints it, with each loader's job.

loader treeruns offline
# illustrative output
<bootstrap>                          java.base, java.logging ...  (shown as null in Java)
  └─ 'platform'                      java.sql, java.net.http ...
       └─ 'app'                      the classpath: com.acme.*
            └─ (custom loaders)      plugins, app servers

The trace: what loadClass("com.acme.Main") does, step by step.

delegation traceruns offline
app.loadClass("com.acme.Main")
  1. findLoadedClass            -> not yet defined here
  2. ask parent: platform       -> platform asks bootstrap -> bootstrap: not found   ✗ ClassNotFoundException (swallowed)
  3. platform: not found        ✗ ClassNotFoundException (swallowed)
  4. app.findClass              -> found on the classpath; defineClass(...)         ✓ app is now the DEFINING loader

Make the invisible visible: the same logic, as the code in ClassLoader.loadClass (simplified).

loadClass, simplifiedruns offline
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
    synchronized (getClassLoadingLock(name)) {
        Class<?> c = findLoadedClass(name);                 // 1. already defined by me?
        if (c == null) {
            try { c = parent.loadClass(name, false); }       // 2. parent first
            catch (ClassNotFoundException e) { }
            if (c == null) c = findClass(name);              // 3. my own findClass, which ends in defineClass
        }
        return c;
    }
}

What you see: two loaders defining the same bytes give two different classes, and the cast between them fails.

consoleruns offline
# illustrative output
java.lang.ClassCastException: class com.acme.Plugin cannot be cast to class com.acme.Plugin
  (com.acme.Plugin is in unnamed module of loader com.acme.PluginLoader @1b2c3d4;
   com.acme.Plugin is in unnamed module of loader 'app')

Why: a class's identity is its name plus its defining loader, so the same name in two loaders is two unrelated classes.

Land it Delegation decides who gets to define a class, and the defining loader becomes part of the class's name from then on.

Likely follow-ups
"When would you override loadClass instead of findClass?"

Only when I need to change the delegation order itself, which is the child-first case for plugins and application servers.

Overriding findClass keeps parent-first behaviour and only changes where bytes come from, which is the safe default.

If I do override loadClass, I must keep three things:

  1. Check findLoadedClass first, so a class is never defined twice by the same loader, which would throw LinkageError: duplicate class definition.
  2. Always delegate java.* to the parent, because defining a java.* class is refused with SecurityException.
  3. Synchronise on getClassLoadingLock(name) after calling registerAsParallelCapable() in a static block, so concurrent loads of different classes do not serialise on the loader.
child-first loadClass keeping the three rulesruns offline
static { registerAsParallelCapable(); }

@Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
    synchronized (getClassLoadingLock(name)) {                     // rule 3
        Class<?> c = findLoadedClass(name);                       // rule 1
        if (c == null) {
            if (name.startsWith("java.")) return super.loadClass(name, resolve);   // rule 2
            try { c = findClass(name); }                            // child first: my jars before the parent's
            catch (ClassNotFoundException e) { return super.loadClass(name, resolve); }
        }
        return c;
    }
}
"How would you see which loader defined a class in a running JVM?"

From code, Foo.class.getClassLoader(), remembering that null means bootstrap, and getModule() for the module. From outside, -Xlog:class+load=info prints the loader and source jar for each class as it loads.

On a live process, jcmd <pid> VM.classloaders show-classes prints the loader tree with the classes each defined, and jcmd <pid> VM.classloader_stats gives the count and metaspace usage per loader.

In a heap dump, a Class object's classLoader field answers it in Eclipse MAT. Since JDK 11 a ClassCastException message already includes the loader name, which is the quickest confirmation when the question is "why are there two of these".

"What does the parallel-capable registration actually change?"

Before JDK 7, loadClass was synchronised on the loader object. One thread loading a slow class blocked every other thread loading anything through that loader.

A parent-first chain with a child-first server loader could also deadlock: thread one holds the child lock and waits for the parent, while thread two holds the parent lock and, through a callback, waits for the child.

A loader that calls ClassLoader.registerAsParallelCapable() gets a lock per class name instead, from getClassLoadingLock(name). Different classes load concurrently and the deadlock pattern disappears.

The built-in loaders are parallel capable, and any custom loader should be, provided its findClass is thread safe.

lock granularityruns offline
not parallel capable:  Thread 1 loads Big  -> holds THE loader lock      ✗ Thread 2 loading Small waits
parallel capable:      Thread 1 loads Big  -> holds lock "Big"           ✓ Thread 2 loads Small under lock "Small" at once

Q12. "Why can a JVM throw ClassCastException: com.acme.Plugin cannot be cast to com.acme.Plugin, and what is a loader constraint violation?"

Reveal answer

Strong answer Because the name is only half of a class's identity. Inside the JVM a class is identified by its binary name together with its defining loader.

If loader A and loader B each read the same Plugin.class bytes and each call defineClass, there are now two distinct Class objects, two separate sets of static fields, and two types that the JVM treats as unrelated.

A cast checks the runtime type against the target type by identity, so an instance of A's Plugin cast to B's Plugin fails with that confusing message.

Since JDK 11 the message helps: it reads "com.acme.Plugin is in unnamed module of loader 'app'; com.acme.Plugin is in unnamed module of loader com.acme.PluginLoader @1a2b3c", which names both loaders.

The same duplication shows up in other ways:

  • instanceof: it returns false.
  • equals: an equals that checks getClass() returns false.
  • Singletons: a static singleton exists twice.

A loader constraint violation is the JVM catching this earlier, at link time.

When a class defined by loader A calls a method on a class defined by loader B, and that method's signature mentions type P, the JVM records a constraint that P must resolve to the same class from both loaders.

If it later finds two different P classes, it throws LinkageError: loader constraint violation, with a message stating which method and which type disagreed.

The classic case is a web application bundling its own copy of the servlet API or of a logging facade that the container also has: the container calls service(HttpServletRequest) on the application's servlet, and the application's loader has a different HttpServletRequest.

The fix is always the same: any type that crosses a loader boundary must be defined once, by a loader both sides share, normally the parent.

Picture it two loaders each defining com.acme.Plugin give two different types that share a name.

The setup: a host casts an object made by a plugin loader whose parent is null, while the plugin jar also contains the API class.

PluginHost.javaruns offline
URL[] urls = { pluginJar.toUri().toURL() };
// ❌ TRAP: parent = null, so nothing is delegated; the jar's own copy of com.acme.Plugin is defined here
ClassLoader pl = new URLClassLoader(urls, null);
Object o = pl.loadClass("com.acme.PluginImpl").getDeclaredConstructor().newInstance();
Plugin p = (Plugin) o;      // Plugin here = the app loader's copy

Make the invisible visible: the JVM keys a class by name plus defining loader, so these are two classes.

memory pictureruns offline
 metaspace                                   heap
 ---------                                   ----
 loader "app"                                o ──class──▶ Plugin @ loader pl
   └─ defines  Plugin   (statics #1)                          ✗ not the same Class object as
 loader pl (URLClassLoader)                                   Plugin @ loader "app" (the cast target)
   └─ defines  Plugin   (statics #2)
   └─ defines  PluginImpl  (implements Plugin #2)

The trace: the cast compares class identity, so it fails even though the names match.

call traceruns offline
1. pl.loadClass("com.acme.PluginImpl")      -> defined by pl, links against Plugin #2   ✓
2. new PluginImpl()                         -> instance whose class chain ends at Plugin #2 ✓
3. (Plugin) o   where Plugin = Plugin #1    -> Plugin #2 is not a subtype of Plugin #1  ✗
4. o instanceof Plugin                      -> false                                    ✗

What you see: a cast error whose two class names are identical, with the loaders named after the dash.

consoleruns offline
# illustrative output
Exception in thread "main" java.lang.ClassCastException: class com.acme.Plugin cannot be cast to class com.acme.Plugin
  (com.acme.Plugin is in unnamed module of loader com.acme.PluginLoader @1a2b3c;
   com.acme.Plugin is in unnamed module of loader 'app')
// A loader constraint violation is the link-time cousin: java.lang.LinkageError,
// message starts "loader constraint violation" and names the method and both loaders.

Why: the JVM identifies a class by (name, defining loader), and the plugin loader never asked its parent for Plugin.

The fix: keep the API out of the plugin jar and give the plugin loader the host loader as parent.

PluginHost.java (fixed)runs offline
// ✅ FIX: the API jar is not packaged in the plugin; the parent defines Plugin once
ClassLoader pl = new URLClassLoader(urls, Plugin.class.getClassLoader());
Plugin p = (Plugin) pl.loadClass("com.acme.PluginImpl").getDeclaredConstructor().newInstance();

What you see now: one Class object for the API, so the cast and instanceof succeed.

consoleruns offline
p.getClass().getInterfaces()[0] == Plugin.class     // Result: true
p instanceof Plugin                                 // Result: true

Land it Two loaders that both define the same class have created two types with one name, and every shared interface must live in a loader both sides delegate to.

Likely follow-ups
"How does a child-first loader avoid this if it is meant to prefer its own classes?"

By excluding the shared API packages from child-first behaviour.

A child-first loader overrides loadClass to try its own jars before the parent, but it must keep a list of package prefixes that are always delegated to the parent: java. and jdk. by law, plus the host's API package such as com.acme.api, and any library whose objects cross the boundary.

Tomcat does exactly this: its web application loader is child-first for the application's jars but always delegates the servlet, JSP and Java EE API packages to the common loader.

A stricter alternative is to fail loudly, refusing to load any class in the API package from the plugin jar, so a plugin that bundles the API breaks at load time in a test rather than at the first cast in production.

child-first loader that always delegates the APIruns offline
@Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
    if (name.startsWith("java.") || name.startsWith("jdk.") || name.startsWith("com.acme.api."))
        return super.loadClass(name, resolve);          // ✅ FIX: API and JDK always come from the parent
    synchronized (getClassLoadingLock(name)) {
        Class<?> c = findLoadedClass(name);
        if (c == null) { try { c = findClass(name); } catch (ClassNotFoundException e) { c = super.loadClass(name, false); } }
        return c;                                       // child-first for everything else
    }
}
"Can you fix a duplicate-class problem without changing the loaders?"

Sometimes, by removing the duplicate bytes. If the plugin jar contains the API classes, build it with the API as a provided-scope dependency so the classes are not packaged, and then only the parent can define them.

If a shaded copy of a library is the duplicate, un-shade it or make sure no object of that library crosses the boundary. What does not work is catching the exception or reflecting across it, because the two types share no relationship the JVM recognises.

If objects genuinely must cross between two loaders that both define a type, the only bridge is serialisation to bytes or a shared interface defined higher up, and both are signs the loader design is wrong.

"Why does the JVM bother with loader constraints instead of just failing at the cast?"

Type safety. The verifier checked the calling class's bytecode assuming P means one specific type.

If the callee's P is a different class with a different layout, a method could read fields that do not exist and corrupt memory, so the JVM must refuse before execution, not after.

Constraints let it do this without eagerly loading every class: it records the promise when the method is resolved and checks it whenever either loader later defines a class with that name.

The practical effect for me is that the error surfaces at the first call across the boundary with a message naming the method, which is a much better place to catch a duplicate than a random cast deep in business code.

Q13 · Scenario. "After we reload a plugin at runtime, the host throws ClassCastException: com.acme.Plugin cannot be cast to com.acme.Plugin. It worked before the reload. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom decoded: two classes with the same name are alive, so the interface com.acme.Plugin has been defined by two loaders. The reload created a new loader, and that new loader defined its own copy of the API interface instead of delegating to the host.
  2. Evidence, in the order I gather it:
    • Message: on JDK 11 and later it names both loaders, so I read it first.
    • Host check: compare obj.getClass().getInterfaces()[0].getClassLoader() with Plugin.class.getClassLoader().
    • Class-load log: -Xlog:class+load=info on a reproduction shows com.acme.Plugin loaded twice from two different jars.
    • Loader list: jcmd <pid> VM.classloaders show-classes confirms it.
  3. Causes, ranked:
    1. Bundled API: the plugin jar contains the API classes and the plugin loader is child-first, so on reload it defined them itself, where before the reload the class had happened to resolve through the parent first.
    2. Wrong parent: the new loader was created with the platform loader or null as parent, so it cannot see the host's API and must define its own.
    3. Stale instance: the host kept an instance from the old loader in a cache and now compares it with types from the new one, which is a different symptom with the same message.
    4. Shaded copy: an API copy hidden inside a third library.
  4. Fix: build the plugin with the API in provided scope so it is not packaged, and make the plugin loader delegate com.acme.api to the parent unconditionally. Create every plugin loader with the host's API loader as parent. On reload, replace all references to old plugin objects atomically and drop the old loader entirely.
  5. Prevention: a build check that fails if the plugin jar contains any class under the API package, a loader test that asserts Plugin.class from the plugin loader is identical to the host's, and a reload test in CI that loads, reloads and calls through the API twice.

Picture it the loader tree before and after the reload, with the second copy of com.acme.Plugin visible.

The setup: the reload method builds a fresh loader with the platform loader as parent, and the plugin jar bundles the API.

PluginManager.javaruns offline
void reload() throws Exception {
    URL[] urls = { pluginJar.toUri().toURL() };
    // ❌ TRAP: the platform loader cannot see the host's com.acme.api, so this loader defines its own Plugin
    ClassLoader fresh = new URLClassLoader(urls, ClassLoader.getPlatformClassLoader());
    current = (Plugin) fresh.loadClass("com.acme.PluginImpl").getDeclaredConstructor().newInstance();
}

Make the invisible visible: the loaders and which one defines which copy of the API.

class-loader hierarchyruns offline
 before reload                          after reload
 -------------                          ------------
 app loader   : host + Plugin #1        app loader   : host + Plugin #1
   └─ plugin loader v1 (parent = app)   platform loader
        PluginImpl v1  ──▶ Plugin #1      └─ plugin loader v2 (parent = platform)
                                               Plugin #2  +  PluginImpl v2 ──▶ Plugin #2

The trace: the same cast works before the reload and fails after it.

call traceruns offline
load v1: PluginImpl -> asks parent (app) for Plugin -> Plugin #1       ✓ cast works
reload : new loader, parent = platform
load v2: PluginImpl -> platform cannot find Plugin -> defines Plugin #2 ✗
(Plugin) v2Object -> Plugin #2 is not Plugin #1                        ✗ ClassCastException

What you see: the class-load log shows the same name loaded twice from two sources.

-Xlog:class+load=inforuns offline
# illustrative output
[1.204s][info][class,load] com.acme.Plugin source: file:/opt/host/lib/api.jar
[9.771s][info][class,load] com.acme.Plugin source: file:/opt/plugins/pay-2.0.jar

Why: the reload changed the parent of the plugin loader and nothing stopped it from defining the API.

The fix: the host loader is the parent and the API is delegated unconditionally.

PluginManager.java (fixed)runs offline
// ✅ FIX: API in provided scope (not packaged); parent = the loader that owns the API
ClassLoader fresh = new URLClassLoader(urls, Plugin.class.getClassLoader());

What you see now: one source for the API after any number of reloads.

-Xlog:class+load=inforuns offline
# illustrative output
[1.204s][info][class,load] com.acme.Plugin source: file:/opt/host/lib/api.jar
[9.771s][info][class,load] com.acme.PluginImpl source: file:/opt/plugins/pay-2.0.jar

Land it The reload did not cause the bug, it exposed a plugin that carried its own copy of the contract, and the contract must be owned by one loader that everyone delegates to.

Likely follow-ups
"You removed the API classes from the plugin jar and it still fails. What next?"

Then a second copy still exists somewhere, or the cast is between the host's type and an old-loader instance. I would log the loader of both classes at the failing cast, including System.identityHashCode of each loader, and compare with the loader that the reload created.

If the old loader shows up, the host still holds objects from the previous plugin version, typically in a listener list, a scheduled task or a cache keyed by the plugin, and the fix is to clear them on reload.

If a third loader shows up, some library defines the class: a shaded dependency, an agent, or a serialisation framework that resolved the class through the thread context loader, which was pointing at the plugin loader during the reload.

Setting and restoring the context loader around the reload closes that path.

"Would parent-first delegation have prevented this?"

For the API class, yes, because a parent-first plugin loader would always ask the host first and never define com.acme.Plugin itself, even if the jar contained it.

The reason plugin systems still use child-first is different classes: the plugin wants its own version of a library the host also has, such as a JSON library, without being forced onto the host's version.

The right design is therefore mixed: parent-first for the API and for the JDK, child-first for everything else, with the list written in the loader and tested.

Pure parent-first is the safe default if plugins do not need private library versions, and I would start there and add child-first only for named packages when a real conflict appears.

"How do you make sure the old plugin loader actually goes away after the reload?"

Hold the loader in a WeakReference after dropping all strong references, call close() on the URLClassLoader to release the jar file handle, suggest a collection with System.gc() in a test, and assert the reference clears. In production, -Xlog:class+unload=info prints each class as it is unloaded, and jcmd <pid> VM.classloaders should show one plugin loader, not one per reload. If the old loader stays, a heap dump and the path to GC roots from it shows the holder; the usual suspects are a thread the plugin started, a ThreadLocal in a host pool thread, and a static registry in the host holding a plugin object.

reload leak testruns offline
WeakReference<ClassLoader> ref = new WeakReference<>(oldLoader);
oldLoader.close();  oldLoader = null;  plugin = null;      // drop every strong reference
System.gc();
assert ref.get() == null : "old plugin loader still reachable";   // ❌ fails if a holder remains

Q14 · Design. "We are moving a plugin host to the module system. Design the isolation using module layers, and tell me what the module system adds on top of what class loaders already give us."

Reveal answer

Strong answer Requirements: plugins are modular jars, they must not see each other's internals or the host's, two plugins may need different versions of one library, a broken plugin must fail at load time with a clear message, and the host runs on a trimmed runtime image.

Design: the host and the API module live in the boot layer. For each plugin, I create a ModuleFinder.of(pluginDir), resolve a Configuration with ModuleLayer.boot().configuration().resolve(finder, ModuleFinder.of(), Set.of("com.acme.plugin.x")), and define a layer with ModuleLayer.boot().defineModulesWithOneLoader(cfg, hostApiLoader), which gives the plugin one fresh class loader whose parent is the host's.

Then ServiceLoader.load(layer, Plugin.class) finds the plugin's implementation declared in its module-info with provides.

What the module system adds on top of class loaders:

  • Visibility (loaders): whether a name can be found at all.
  • Readability (modules): a module can only link to modules it requires.
  • Accessibility (modules): only exports packages are usable and only opens packages are reflectable.

So a plugin cannot reach the host's internal package even though the loader can see it, and two plugins in sibling layers can each carry their own version of a library because layers are separate resolution scopes, while a layer cannot redefine a module that exists in its parent.

Failures are early: a missing requires or a split package fails when the configuration resolves, with a message naming the modules. --add-opens is the escape hatch, a startup patch that opens one package to a named module or to ALL-UNNAMED.

For the runtime image, jlink needs every module to be a real modular jar, because automatic modules are not allowed, and produces an image with only the modules the host needs. Trade-off: every plugin author must write a module-info.

What I would not do: put plugins in the boot layer, or open everything to ALL-UNNAMED permanently to make an old plugin work.

Picture it the layer graph for a host and two plugins, and what each boundary blocks.

The setup: the host builds one layer per plugin directory, as in the design above.

PluginLayers.javaruns offline
ModuleFinder finder = ModuleFinder.of(pluginDir);
Configuration cfg = ModuleLayer.boot().configuration()
        .resolve(finder, ModuleFinder.of(), Set.of("com.acme.plugin.x"));
ModuleLayer layer = ModuleLayer.boot().defineModulesWithOneLoader(cfg, hostApiLoader);
ServiceLoader<Plugin> plugins = ServiceLoader.load(layer, Plugin.class);   // providers of THIS layer only

Make the invisible visible: layers are separate resolution scopes, each with its own loader.

layer graphruns offline
 boot layer:  java.base | com.acme.host | com.acme.api
                  ▲                          ▲
        ┌─────────┴────────┐        ┌────────┴─────────┐
 layer P1 (own loader)     │ layer P2 (own loader)      │
   com.acme.plugin.x       │   com.acme.plugin.y        │
   requires com.acme.api   │   requires com.acme.api    │
   lib v1 inside           │   lib v2 inside            │   P1 and P2 cannot see each other

The trace: each check happens at a different moment.

call traceruns offline
resolve(cfg)       missing requires or split package       ✗ fails here, names the modules
defineModules...   loader created, modules defined          ✓
plugin calls host internal package (not exported)           ✗ IllegalAccessError / IllegalAccessException
plugin calls com.acme.api.Plugin (exported)                 ✓

What you see: a resolution-time failure with the module named, long before any request runs.

consoleruns offline
# illustrative output
java.lang.module.FindException: Module com.acme.util not found, required by com.acme.plugin.x
// access failure at first use: IllegalAccessError, message says the package is not exported
// from module com.acme.host to module com.acme.plugin.x

Land it Loaders decide what a plugin can find, layers decide what it can link to, and the value of layers is that a bad plugin fails at resolution with a named cause instead of at first use with a cast error.

Likely follow-ups
"The requirement changes: half our plugins are old jars with no module-info. What now?"

They become automatic modules, named from the jar file name or the Automatic-Module-Name manifest attribute, exporting every package and reading every module.

They still work in a layer, so isolation of visibility and separate library versions per layer are kept, but encapsulation inside the plugin is lost and split packages between two automatic modules in one layer fail resolution.

For the runtime image, automatic modules block jlink, so I would jlink only the host's modules and load plugins from a directory outside the image.

I would ask plugin owners to add at least Automatic-Module-Name now, so the names stay stable, and a real descriptor later, generated with jdeps --generate-module-info as a starting point.

"What would you cut under time pressure?"

I would cut the runtime image and ship on a full JDK, because jlink only saves disk and start-up and forces every dependency to be modular.

I would keep one layer per plugin with defineModulesWithOneLoader, because that is where the isolation comes from and it is a few lines of code. I would keep the resolution-time failure, since that is the operational win.

I would drop per-plugin opens auditing and accept a documented --add-opens list for the two frameworks that need reflection, with a ticket to remove each one.

I would not cut the test that loads two plugins with conflicting library versions, because that is the scenario the design exists for.

"Why does --add-opens work at all if strong encapsulation is enforced by the JVM?"

Because encapsulation is data, not code. Each module holds a table of which packages are exported or opened to which modules, and the JVM consults it during access checks.

--add-opens java.base/java.lang=ALL-UNNAMED edits that table when the boot layer is created, before any application class runs, so the check passes later.

It is deliberately a launcher option rather than an API, so that the person deploying the application, not a library, makes the decision, and the module being opened cannot refuse.

consoleruns offline
# without the flag, reflecting into java.base
java.lang.reflect.InaccessibleObjectException: Unable to make field private ... accessible:
    module java.base does not "opens java.lang" to unnamed module @4e50df2e
# ✅ FIX (stop-gap): java --add-opens java.base/java.lang=ALL-UNNAMED -jar app.jar

Since JDK 16 the default is to deny illegal access, so any framework that reflects into the JDK either needs this flag or, better, an API such as MethodHandles.privateLookupIn against a package the target module has opened to it on purpose.

"How do the module system and the thread context loader interact for ServiceLoader?"

ServiceLoader.load(Service.class) without a layer uses the thread context loader and finds providers in the unnamed module through META-INF/services files and in named modules of that loader's layer and its parents through provides clauses. ServiceLoader.load(layer, Service.class) searches that layer and its parents, ignoring the context loader, which is what a plugin host wants because it wants providers from one specific plugin. The trap is a plugin that itself calls ServiceLoader.load(Service.class) for its own extensions while the context loader still points at the host, so it finds nothing; the host should set the context loader to the plugin's loader around plugin calls, or the plugin should pass its own class's loader explicitly.

Q15. "What is the difference between Class.forName(name), Class.forName(name, false, loader) and loader.loadClass(name), why did people write Class.forName for JDBC drivers, and what is the thread context class loader for?"

Reveal answer

Strong answer Class.forName(name) loads the class through the caller's defining loader and initialises it, so its static initialiser runs before the call returns. Class.forName(name, false, loader) loads through the loader I choose and does not initialise, so static code runs later at the first real trigger.

loader.loadClass(name) also does not initialise and does not even link; it only returns the Class object, and it does not accept array or primitive names, which forName does. The JDBC habit comes from the initialisation difference.

Before JDBC 4, a driver registered itself in a static block that called DriverManager.registerDriver(new Driver()), and nothing in the application referred to the driver class, so Class.forName("com.mysql.jdbc.Driver") was the only way to trigger that block.

Since JDBC 4.0 in JDK 6, DriverManager discovers drivers with ServiceLoader from META-INF/services/java.sql.Driver, so the call is unnecessary, and it is actively harmful in an application server because it registers a driver from the application's loader into a DriverManager that lives in the platform loader, which pins the application's loader on redeploy.

The thread context class loader exists because delegation only goes up. DriverManager, ServiceLoader, JNDI, JAXP factories and logging facades live in the platform or application loader, but in a container the classes they need to find live in a child loader they cannot see.

So the container sets Thread.setContextClassLoader to the application's loader on every request thread, and those frameworks use Thread.currentThread().getContextClassLoader() to look down the tree.

It is a convention, not a rule the JVM enforces, and the two classic bugs are a framework that ignores it and uses its own loader, and a thread pool created during startup whose threads carry the wrong context loader forever.

Picture it which stage each loading call reaches, and where the context loader points in a container.

The setup: a driver class with a static block, loaded three ways.

Driver.javaruns offline
public class Driver {
    static { System.out.println("Driver.<clinit> runs"); }   // JDBC 3 drivers registered themselves here
}
Class.forName("com.acme.Driver");                   // loads AND initialises
Class.forName("com.acme.Driver", false, loader);    // loads only
loader.loadClass("com.acme.Driver");                // loads only
loader.loadClass("[I");                             // ❌ TRAP: ClassNotFoundException; forName("[I") works

Make the invisible visible: what each call has done to the class when it returns.

Stages reached by each call
CallLoadedInitialised (static block ran)Array and primitive names
Class.forName(name)Yes, by the caller's loaderYesWorks
Class.forName(name, false, loader)Yes, by loaderNo, runs at first real useWorks
loader.loadClass(name)YesNoFails: ClassNotFoundException
class-loader hierarchy and context loaderruns offline
 platform loader : DriverManager, ServiceLoader, JAXP   ──looks for app classes──▶ cannot see down
        ▲  delegation only goes UP
 app/webapp loader : your classes, the JDBC driver
        ▲
 request thread  ── contextClassLoader ──▶ webapp loader   ✓ frameworks look DOWN through this

What you see: only the first call prints the static block message.

consoleruns offline
Driver.<clinit> runs            <- printed by Class.forName("com.acme.Driver")
                                <- nothing printed by the other two calls

The fix: on JDBC 4 and later, drop the call and let ServiceLoader find the driver.

Db.javaruns offline
// ✅ FIX: no Class.forName; META-INF/services/java.sql.Driver in the driver jar does the work
Connection c = DriverManager.getConnection(url, user, pass);

Land it Pick the variant by what you want to happen, load only or load and initialise, and treat the context loader as the container's way of pointing shared frameworks at application classes.

Likely follow-ups
"When would you still want Class.forName with initialisation on?"

To force a known-heavy initialisation at a chosen time.

If a class builds a large lookup table, loads a native library or warms a cache in its static initialiser, I would rather pay for that on the main thread during startup, where it is measured and logged and where a failure prevents the service from reporting ready, than on the first request.

A loop of Class.forName calls over a list of such classes, before the listening socket opens, does that. The other legitimate use is a registration pattern in code I do not control, where a class's static block registers something, and no other reference to it exists.

For plain probing, whether a class exists, I always pass false, so the probe never runs arbitrary static code.

"How does the context loader leak, and how do you stop it?"

A thread keeps its context loader until someone changes it.

A thread pool created while a web application initialises inherits the application's loader as the context loader of every pool thread, and if that pool belongs to the container or to a shared library, the threads outlive the application and keep its loader reachable, which blocks unloading on redeploy.

The same happens with a ForkJoinPool.commonPool() task started from application code, and it is one of the leaks Tomcat's leak detector reports at undeploy.

Prevention: create long-lived pools with a thread factory that sets the context loader to the framework's own loader, and in application code set and restore the context loader in a try-finally around anything that hands work to shared threads.

Handoff.javaruns offline
ClassLoader saved = Thread.currentThread().getContextClassLoader();
try {
    Thread.currentThread().setContextClassLoader(frameworkLoader);   // ✅ FIX: shared thread must not keep the webapp loader
    sharedPool.submit(task);
} finally { Thread.currentThread().setContextClassLoader(saved); }
"Do virtual threads change any of this?"

A virtual thread inherits the context class loader of the thread that created it, like a platform thread, so a virtual thread started from a request thread in a container sees the application's loader, which is what you want. The difference is scale: a service may create millions of short-lived virtual threads, so per-thread setup such as setContextClassLoader in a factory is cheap but must be, and the leak pattern is less about pools and more about a long-lived virtual thread, for example a scheduler loop, that was started during application startup and still references the old loader. The same discipline applies: any thread that outlives a deployment must be stopped at undeploy, and the Thread.Builder API makes it easy to name and track them.

"Why does the JDBC driver registration leak, mechanically?"

DriverManager is a class in java.sql, defined by the platform loader and initialised once per JVM. Its registered-drivers list is a static field, so it lives as long as the JVM does.

Now follow the chain of references. When the application's copy of the driver registers, that list holds a Driver instance. The instance references its class. The class references its loader. And the loader references every class it ever defined.

So the whole application stays reachable from a static field in the platform loader, and redeploying leaks the entire old application into metaspace.

reference chainruns offline
static DriverManager.registeredDrivers (platform loader, lives as long as the JVM)
  └─▶ Driver instance
        └─▶ Driver.class
              └─▶ webapp ClassLoader
                    └─▶ every class, static field and cache of the old application   ✗ never collected

There are two fixes. Call DriverManager.deregisterDriver for application-owned drivers in a shutdown hook. Or better, put the driver jar in the container's shared library directory, so the platform-level registration refers to a platform-level class.

Q16 · Scenario. "A NoClassDefFoundError appears only in production; staging runs the same build and is fine. Where do you start?"

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom decoded: the JVM resolved a reference and could not produce the class. "Could not initialize class X" means the class exists and its static initialiser failed earlier, and the failure was environment-specific, which fits "only in production" very well. A plain class name with a ClassNotFoundException cause means the bytes are genuinely absent or shadowed at runtime.
  2. Evidence, in the order I gather it:
    • Logs: search backwards for the first ExceptionInInitializerError mentioning that class.
    • Loaded classes: if there is none, -Xlog:class+load=info on one production instance shows each class with its source jar, and I diff it with staging for that class and its package.
    • Runtime facts: jcmd <pid> VM.system_properties shows java.class.path and java.version on both.
  3. Causes, ranked:
    1. Initialiser reads the environment: a static initialiser reads a configuration value, secret, hostname or file that exists in staging and not in production, and the first failure was swallowed by a catch block.
    2. Shading or minimisation: a fat jar dropped a class that is only reachable by reflection.
    3. Duplicate classes: two versions of a class are on the classpath and first-wins order differs, because a container builds the classpath from a directory listing.
    4. Missing provided jar: a provided-scope dependency exists in the staging server's shared libraries and is absent from the production image.
    5. Different JDK: another release picks a different META-INF/versions entry.
  4. Fix: for the initialiser case, fix the environment or the code and make the initialiser fail loudly at startup; for shading, exclude the class from minimisation or stop minimising; for order, remove the duplicate; for the missing jar, add it to the deployable.
  5. Prevention: run the identical image in staging with production-shaped configuration, fail startup on the first initialisation error instead of catching it, and a duplicate-class check in the build.

Picture it the two-step failure of a class whose static initialiser throws, which is why the first error is easy to miss.

The setup: a class that reads an environment variable in its static initialiser.

Config.javaruns offline
class Config {
    // ❌ TRAP: DB_URL is set in staging, unset in production -> NullPointerException inside <clinit>
    static final String URL = System.getenv("DB_URL").trim();
}

Make the invisible visible: the JVM keeps a state per class and remembers a failed initialisation forever.

class initialisation statesruns offline
 Config:  loaded ─▶ linked ─▶ initialising ─▶ initialised            (staging)
                                   │
                                   └─ <clinit> throws ─▶ ERRONEOUS state                (production)
                                      every later use ─▶ NoClassDefFoundError: Could not initialize class

The trace: the first use throws the real error, every later use throws a vaguer one.

call traceruns offline
request 1: Config.URL  -> run <clinit> -> NPE -> ExceptionInInitializerError   ✗ logged once, maybe swallowed
request 2: Config.URL  -> class is ERRONEOUS -> NoClassDefFoundError            ✗ no cause in the message
request 3..N: same as request 2                                                 ✗ the log is full of the vague one

What you see: the real cause is only in the first stack trace.

application logruns offline
# illustrative output
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException: Cannot invoke "String.trim()" because the return value of "java.lang.System.getenv(String)" is null
    at com.acme.Config.<clinit>(Config.java:4)
... 4000 lines later ...
java.lang.NoClassDefFoundError: Could not initialize class com.acme.Config

Why: a failed initialiser is recorded on the class and the JVM never retries it.

The fix: no failing work in a static initialiser; initialise explicitly at startup and stop the process on failure.

Config.java (fixed)runs offline
final class Config {
    private final String url;
    private Config(String url) { this.url = url; }
    // ✅ FIX: explicit init step, called from main() before the readiness probe turns green
    static Config load() { return new Config(Objects.requireNonNull(System.getenv("DB_URL"), "DB_URL not set")); }
}

What you see now: one clear startup failure, and the deployment rolls back.

application logruns offline
# illustrative output
Exception in thread "main" java.lang.NullPointerException: DB_URL not set
    at com.acme.Config.load(Config.java:6)

Land it "Only in production" almost always means an earlier, swallowed static-initialisation failure, so read the message for "Could not initialize" before you go looking for a missing jar.

Likely follow-ups
"There is no earlier error in the logs and the class is in the jar. What next?"

Then the initialisation failure was swallowed without logging, or the class was found by a different loader than I assume.

For the first, I would temporarily start one instance with -Xlog:class+init=info,exceptions=info, which logs every exception thrown by the JVM, including one inside <clinit> that user code then caught, with the class and method.

For the second, I would print the loader chain at the failing point and check whether the class is being requested by a class defined in a loader that cannot see the jar, such as a library in a shared container directory asking for an application class without using the context loader.

I would also check whether production runs with a Java agent that transforms this class and fails, since a transformer exception surfaces as a plain NoClassDefFoundError.

"Why is first-on-classpath order not stable between environments?"

The application loader searches jars in the order of the classpath string and takes the first match. A build tool writes the classpath from the dependency tree, which is deterministic.

A container or a launch script that builds the string from a wildcard such as lib/* gets the order the file system returns, which is not sorted and can differ between hosts, images and file systems.

Spring Boot's launcher fixes this by writing the order into BOOT-INF/classpath.idx; a plain servlet container does not promise any order for WEB-INF/lib. So two copies of one class, which the build never flagged, resolve to different versions on different machines.

same classpath wildcard, two hostsruns offline
# illustrative output
host-a: java -cp 'lib/*' ...   expands to  lib/guava-31.jar lib/guava-33.jar   -> first match wins: 31
host-b: java -cp 'lib/*' ...   expands to  lib/guava-33.jar lib/guava-31.jar   -> first match wins: 33   ✗

The only cure is to not have two copies, enforced in the build.

"How would you make an initialiser failure impossible to miss?"

Two rules. First, static initialisers do not do work that can fail: no I/O, no configuration reads, no lookups; they build constants. Work that can fail goes into an explicit initialisation step with a logged result and a hard stop on failure.

Second, where a static initialiser must stay, nothing catches Throwable around first use, and the readiness probe of the service only turns green after the classes in question have been touched deliberately at startup with Class.forName.

That turns a lazy, per-request failure into a startup failure with one clear stack trace, which the deployment system rolls back automatically.

Q17 · Design. "Design a plugin system for our service using class loaders: third-party plugins, isolation between them, versioning, unloading, and whatever security is possible now that the SecurityManager is gone."

Reveal answer

Strong answer Requirements: plugins come from other teams with their own dependencies, two plugins may need different versions of one library, a plugin must be replaceable at runtime, and some plugins are untrusted.

Design: a small API jar, containing only interfaces and value types, defined by the host loader. Each plugin gets its own loader with the host loader as parent.

Delegation is mixed: parent-first for java., jdk. and com.acme.api, and child-first for everything else, so a plugin can carry its own JSON library without affecting the host or its neighbours; the loader refuses to define any class in the API package from the plugin jar.

Only API types cross the boundary, which prevents the cast and constraint errors of Q12. Versioning: the API is semantically versioned, each plugin manifest declares the API version it was built against, and the host refuses a plugin with a higher major version.

Unloading: the host replaces a registry entry atomically, tells the plugin to stop its threads through a lifecycle method, closes the URLClassLoader, and confirms unloading with -Xlog:class+unload. Security: as of JDK 24 the SecurityManager is permanently disabled, so there is no in-process sandbox.

The trust boundary is a process. Untrusted plugins run in a separate JVM launched with ProcessBuilder, with a memory limit and a cgroup, and talk to the host over a local socket using the same API mapped to messages; trusted plugins run in-process for speed.

Trade-offs: process isolation costs a few hundred microseconds per call and a JVM's worth of memory per plugin, and child-first delegation needs a tested package list.

What I would not do: share one loader between plugins, use Thread.stop to kill a misbehaving plugin, let plugins register JDBC drivers or use ThreadLocal on host threads, or claim that a class loader provides security.

Picture it the plugin loader tree, and the three decisions the loader makes for each class name.

The setup: a per-plugin loader that is mixed: parent-first for the API and JDK, child-first for the rest, and strict about the API package.

PluginLoader.javaruns offline
final class PluginLoader extends URLClassLoader {
    PluginLoader(URL[] jar, ClassLoader hostLoader) { super(jar, hostLoader); }

    @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        if (name.startsWith("java.") || name.startsWith("jdk.") || name.startsWith("com.acme.api."))
            return super.loadClass(name, resolve);      // ✅ parent-first: one definition of the contract
        synchronized (getClassLoadingLock(name)) {
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                try { c = findClass(name); }            // child-first: plugin's own libraries
                catch (ClassNotFoundException e) { c = super.loadClass(name, false); }
            }
            return c;
        }
    }
    @Override protected Class<?> findClass(String name) throws ClassNotFoundException {
        if (name.startsWith("com.acme.api."))
            throw new ClassNotFoundException(name + " must not be packaged in a plugin");  // fail loudly
        return super.findClass(name);
    }
}

Make the invisible visible: who defines what.

class-loader hierarchyruns offline
 app loader (host + api.jar : com.acme.api.Plugin)      <- defined once, shared
   ├─ PluginLoader A : plugin-a.jar + json-lib 1.x      <- child-first for json
   ├─ PluginLoader B : plugin-b.jar + json-lib 2.x      <- child-first for json
   └─ (untrusted plugins: separate JVM process, talks over a socket)

The trace: three class names resolved by plugin A.

call traceruns offline
com.acme.api.Plugin         -> prefix com.acme.api. -> parent (app loader)         ✓ same Class as host
com.fasterxml.json.Mapper   -> not found in parent-first list -> plugin jar        ✓ A gets 1.x, B gets 2.x
com.acme.api.Extra in jar   -> findClass refuses                                   ✗ load-time error, not a cast in production

What you see: two plugins running different library versions side by side, and one rejected plugin.

-Xlog:class+load=inforuns offline
# illustrative output
[3.101s][info][class,load] com.fasterxml.json.Mapper source: file:/opt/plugins/a/json-1.9.jar
[3.480s][info][class,load] com.fasterxml.json.Mapper source: file:/opt/plugins/b/json-2.1.jar
java.lang.ClassNotFoundException: com.acme.api.Extra must not be packaged in a plugin

Land it Loaders give isolation of names and versions, the API jar gives a shared contract, and only a process boundary gives security, so decide per plugin which of the three you need.

Likely follow-ups
"The requirement changes: all plugins must share the host's Jackson version and its ObjectMapper. What changes?"

Jackson moves into the shared contract.

I would add a middle loader between the host and the plugins, a "shared libraries" loader holding Jackson and anything else that must be one version, and make the plugin loaders delegate parent-first for com.fasterxml.jackson as well as the API package.

The shared ObjectMapper is passed to plugins through an API interface, never reached through a static.

The cost is that a plugin can no longer pick its own Jackson, so the plugin manifest must declare compatibility with the host's Jackson major version and the host must document upgrades.

It also means Jackson's own class-generating parts, such as its module registrations, must be cleaned per plugin at unload, otherwise the shared mapper pins the plugin's classes.

"What would you cut under time pressure?"

Unloading first: I would document that replacing a plugin requires a rolling restart of the host, because reliable unloading is the part that takes weeks of leak hunting, and a restart is cheap in a container platform. Then process isolation: everything in-process, with a written rule that only plugins reviewed by us are deployed, and process isolation added later for the first external plugin. I would keep the API jar in the parent, the per-plugin loader with the API package always delegated, and the build check that a plugin jar contains no API classes, because those three lines are what prevent the cast errors that would otherwise consume the team's time from day one.

"How do you protect the host from a plugin that uses all the CPU or memory in-process?"

I cannot, fully, which is the honest answer and the reason for process isolation. In-process, the JVM has one heap; a plugin's allocations count against the host's -Xmx, and an OutOfMemoryError lands on whichever thread allocates last.

What I can do is bound the damage: run plugin calls on a dedicated executor with a fixed thread count, so a CPU-hungry plugin cannot take all request threads; apply timeouts to plugin calls and stop routing to a plugin that exceeds them; watch allocation per thread with the JFR event jdk.ObjectAllocationSample attributed to plugin threads; and give the process enough headroom that one plugin's spike does not kill the host.

For anything stronger, a separate JVM with its own -Xmx and a cgroup CPU quota is the tool.

"How would you verify isolation actually works before shipping?"

With tests that try to break it. One test loads two plugins that each bundle a different version of the same library and asserts each sees its own version through a method that returns the library's version string.

One loads a plugin whose jar contains a copy of the API interface and asserts the host rejects it at load time with a clear message. One asserts that Plugin.class obtained through the plugin loader is the same object as the host's.

One reloads a plugin fifty times in a loop with a WeakReference to each old loader and asserts every reference clears after a collection, with -Xlog:class+unload captured. And one starts a plugin that spawns a thread and asserts the host's unload hook stops it.

Those five tests catch most of what production would otherwise teach me.

the core assertionsruns offline
assertSame(Plugin.class, loaderA.loadClass("com.acme.api.Plugin"));          // API defined once
assertNotSame(libFrom(loaderA), libFrom(loaderB));                           // each plugin has its own library
assertEquals("1.9", versionOf(loaderA));  assertEquals("2.1", versionOf(loaderB));

Q18. "Explain class loader memory leaks: what keeps a loader alive after redeploy, and how you would find the culprit in a heap dump."

Reveal answer

Strong answer Class metadata lives in metaspace and is owned by the defining loader, so it is only freed when the loader is garbage collected.

A loader is collectable when nothing reachable references it, any Class it defined, or any instance of those classes, because an instance references its class and a class references its loader.

On redeploy, an application server creates a new loader for the new version and drops its references to the old one.

If anything outside the application still points into it, the old loader and every class it defined stay in metaspace, and after enough redeploys the JVM fails with OutOfMemoryError: Metaspace. The culprits share one shape: something long-lived in a parent loader holding something from the child.

A ThreadLocal whose value is an application object, stored in a container pool thread that survives the redeploy, keeps the value, its class and its loader alive.

A static cache in a shared library, such as a bean introspector cache or a resource bundle cache, holds application classes as keys. DriverManager holds an application-loaded JDBC driver instance in a static list in the platform loader.

A thread started by the application and never stopped, a timer or a scheduled executor, holds its Runnable and its context class loader. Registered MBeans and shutdown hooks do the same.

Finding it: take a dump with jcmd <pid> GC.heap_dump /tmp/h.hprof after a redeploy and a full collection, open it in Eclipse MAT, list instances of the application's loader class, and I expect one but see several.

I select an old one and ask for the path to GC roots, excluding weak and soft references.

The path ends at the holder:

  • Thread local: a thread's threadLocals map.
  • Static field: a static field in the parent loader.
  • Live thread: a thread whose context loader is the application's.

That path names the fix.

Picture it the chain of references that keeps an old loader alive, and the path-to-GC-roots answer in the heap dump.

The setup: the four classic pins in the code block below.

what keeps a class loader alive after a redeployruns offline
// A class loader is unloadable only when NOTHING reachable from a GC root
// refers to it, or to any class it loaded, or to any instance of those classes.
// A single reference from a JDK-owned static field is enough to pin it — and
// with it, every class it loaded, and their metaspace.

// THE FOUR CLASSIC PINS:

// 1. A ThreadLocal on a POOLED thread. The thread outlives the application;
//    the value's class was loaded by the application's loader.
static final ThreadLocal<MyContext> CTX = new ThreadLocal<>();
// -> the pool thread -> ThreadLocalMap -> MyContext -> its Class -> the loader

// 2. A JDBC driver registered in java.sql.DriverManager (a JDK static).
DriverManager.registerDriver(new com.acme.Driver());   // never deregistered

// 3. A shutdown hook, a timer thread, or any thread the app started and
//    did not stop. The Thread's contextClassLoader field pins the loader.
new Thread(this::poll).start();          // still running after undeploy

// 4. A JDK-level cache holding an application class: a custom URLStreamHandler,
//    a java.beans Introspector cache, a logging LogManager reference.

// FINDING IT — the reliable method, not guessing:
//   jcmd <pid> GC.class_stats                       (count classes per loader)
//   jmap -dump:live,format=b,file=heap.hprof <pid>
//   then in Eclipse MAT: find the ClassLoader instance and run
//   "Path to GC Roots -> exclude weak/soft references"
// The single strong reference that remains IS the leak.

Make the invisible visible: from a GC root to the loader.

reference chainruns offline
GC root: pool thread "http-nio-8080-exec-3"           (survives the redeploy)
  └─ Thread.threadLocals (ThreadLocalMap)
       └─ Entry.value : com.acme.web.MyContext        (application class)
            └─ MyContext.class
                 └─ WebappClassLoader @ 0x7a1c00     ✗ pinned; so is every class it defined

What you see: the path MAT prints for one stale loader, and the loader count before the fix.

Eclipse MAT: Path to GC Roots (exclude weak/soft)runs offline
# illustrative output
Class Name                                                    Shallow Heap
java.lang.Thread @ 0x7b2c1000  http-nio-8080-exec-3                     120
  '- threadLocals java.lang.ThreadLocal$ThreadLocalMap @ 0x7b2c1100      24
     '- table java.lang.ThreadLocal$ThreadLocalMap$Entry[16]             80
        '- value com.acme.web.MyContext @ 0x7b2c1200                     24
           '- <class> class com.acme.web.MyContext
              '- <classloader> org.apache.catalina.loader.WebappClassLoader @ 0x7a1c1000

The fix: clear the value after each request.

RequestFilter.javaruns offline
try { CTX.set(new MyContext(req)); chain.doFilter(req, res); }
finally { CTX.remove(); }            // ✅ FIX: the pool thread no longer holds the application class

What you see now: one application loader after three redeploys.

jcmd VM.classloadersruns offline
# illustrative output (after 3 redeploys, fix applied)
+-- <bootstrap>
      +-- "platform"
            +-- "app"
                  +-- WebappClassLoader @ 0x7a1c4000     <- exactly one; the old three were collected

The MAT step is the answer worth giving. "Path to GC roots, excluding weak and soft references" turns this from a guessing exercise into a definite answer in about two minutes, and it names the exact field holding the loader.

Land it A loader leaks when a longer-lived loader holds any object from it, and one path-to-GC-roots query in a heap dump names the holder, so take the dump before guessing.

Likely follow-ups
"What can you check without a heap dump?"

Counting loaders. jcmd <pid> VM.classloaders lists live loaders with their names and parents; after three redeploys there should be one application loader, and seeing four proves the leak without opening anything.

jcmd <pid> VM.classloader_stats adds class counts and metaspace bytes per loader, so I can also tell how big each stranded loader is. jcmd <pid> VM.metaspace shows usage per loader in detail.

-Xlog:class+unload=info in the startup flags prints unloading as it happens, so silence after a redeploy is itself the symptom. Tomcat prints a specific warning at undeploy for threads and thread locals it detected.

None of these tells me the holder, though; for that I still need the dump.

"Why do weak references not save you here?"

They do save you when the holder is the only reference, which is why ThreadLocal keys are weak and why WeakHashMap is used for class-keyed caches.

The trouble is that a weak reference to the key does not help when the value strongly references the key's loader.

ThreadLocal is the standard example: the map entry's key is a weak reference to the ThreadLocal object, but the value is strong and stays in the thread until the entry is cleaned, which only happens on later access to that thread's map.

A cache keyed weakly on a Class whose value holds an instance of that class has the same problem. The fix is to clear per-deployment state explicitly at undeploy, not to hope a weak reference will do it.

"How do you write an application so that it can be undeployed cleanly?"

Own every long-lived thing and release it in a shutdown hook of the framework, not of the JVM. Executors are shut down and awaited; timers cancelled; JDBC drivers deregistered, or better placed in the container's shared library directory; MBeans unregistered; listeners removed; caches in shared libraries flushed, for example java.beans.Introspector.flushCaches(); and thread locals on request threads cleared in a finally block after each request.

Never start threads from static initialisers. Then a test deploys and undeploys the application twenty times in an embedded container while holding a WeakReference to each loader, forces a collection and asserts every reference cleared. That test fails the day someone adds a leak.

Q19 · Scenario. "An application server dies with OutOfMemoryError: Metaspace after roughly the fortieth hot redeploy. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom decoded: metaspace holds class metadata, and it grows by roughly one application's worth of classes per redeploy, so each old deployment's loader is staying alive. Forty redeploys times a typical 20 to 40 megabytes of metadata is enough to hit whatever -XX:MaxMetaspaceSize was set to; note that without that flag metaspace is unlimited and the failure would instead be the process being killed, or "Compressed class space" at its one gigabyte default.
  2. Evidence, cheapest first:
    • Loader count: jcmd <pid> VM.classloaders shows one web application loader per redeploy still alive.
    • Loader size: VM.classloader_stats shows each one with thousands of classes.
    • Metaspace trend: jstat -gc <pid> shows metaspace used never dropping after a full collection.
    • Holder: a heap dump with jcmd <pid> GC.heap_dump, opened in Eclipse MAT, with the path to GC roots from one old loader.
  3. Causes, ranked:
    1. Unstopped thread: a thread started by the application and not stopped at undeploy keeps its context loader.
    2. Thread local: a ThreadLocal value is left in a container request thread.
    3. JDBC driver: one registered from the application into the platform-level DriverManager.
    4. Shared cache: a static cache in a shared library keyed by application classes.
    5. Class generation: a framework generates classes that are never released; this shows as one loader with a growing class count rather than many loaders.
  4. Fix: whichever holder the dump names, released at undeploy: shut down the executor, clear the thread local, deregister the driver or move it to the shared library directory, flush the cache. If several holders exist, fix them all; one remaining path keeps the whole loader.
  5. Prevention: stop hot redeploying in production and restart the container image instead, which is the normal practice now; keep hot redeploy for development; and add the deploy-undeploy loop test from Q18 so leaks fail in CI.

Picture it how loaders pile up across redeploys until the metaspace limit is reached.

The setup: the leaking shape from Q18, one pinned reference per deployment, and a capped metaspace.

JVM flagsruns offline
java -XX:MaxMetaspaceSize=1g -XX:+HeapDumpOnOutOfMemoryError -jar server.jar
# ❌ TRAP: each redeploy leaves its loader pinned by a pool-thread ThreadLocal

Make the invisible visible: one stranded loader per deployment, each holding its classes.

metaspace pictureruns offline
 metaspace (limit 1 GB)
 [ webapp v1 loader: 14k classes, 26 MB ] ✗ pinned
 [ webapp v2 loader: 14k classes, 26 MB ] ✗ pinned
 [ webapp v3 loader: 14k classes, 26 MB ] ✗ pinned
 ...  after about 40 deployments the limit is reached
 pinned by: pool thread ─▶ ThreadLocal value ─▶ class ─▶ loader

The trace: a redeploy that should free the old loader.

call traceruns offline
redeploy 1: new loader v2, drop reference to v1        v1 still pinned          ✗ 2 loaders
redeploy 2: new loader v3, drop reference to v2        v1, v2 pinned            ✗ 3 loaders
...
redeploy N: class definition needs space               no space, GC cannot free ✗ OutOfMemoryError

What you see: the loader count grows and the error names Metaspace.

consoleruns offline
# illustrative output
$ jcmd 4242 VM.classloaders | grep -c WebappClassLoader      -> 12   (expected 1)
java.lang.OutOfMemoryError: Metaspace

Why: metaspace is freed only when the defining loader is collected, and one live reference prevents that.

The fix: release the holder at undeploy.

AppListener.javaruns offline
public void contextDestroyed(ServletContextEvent e) {
    executor.shutdownNow();                       // ✅ FIX: stop the application threads
    CTX.remove();                                 // clear request-thread state
    DriverManager.deregisterDriver(driver);       // or put the driver in the shared lib directory
}

What you see now: the loader count stays flat.

consoleruns offline
# illustrative output
$ jcmd 4242 VM.classloaders | grep -c WebappClassLoader      -> 1    after 40 redeploys

Land it Forty loaders alive means forty deployments each still held by one reference, and the durable fix is to replace hot redeploy with a process restart and keep the leak test for development.

Likely follow-ups
"You fixed the thread local and the loaders still accumulate. What next?"

Take the dump again. A loader with several independent holders only becomes collectable when the last one is gone, so the path-to-roots query now shows the next holder. I would repeat until the reference clears in a test, rather than guessing from a list.

If the path shows the holder is the JVM itself, for example a class with a running <clinit>, a JIT-compiled method still on some stack, or a JFR recording, I would confirm that a full collection actually ran, because metaspace is only reclaimed when a collection unloads classes; jcmd <pid> GC.run forces one, and -Xlog:gc+phases shows the class unloading phase.

And I would verify that -XX:-ClassUnloading was not set in some inherited startup script, because that disables unloading entirely.

"Would raising MaxMetaspaceSize help?"

Only as a way to buy time, and I would say so.

Raising it from, say, 512 megabytes to 1 gigabyte changes the fortieth redeploy into the eightieth, and meanwhile each leaked loader also holds heap objects, so the heap shrinks as well and garbage collection slows.

Removing the cap altogether moves the failure to the operating system's memory limit, which in a container means the process is killed with no Java stack trace at all.

The honest use of the flag is as a guard: set it to roughly two times the steady-state usage reported by jcmd <pid> VM.metaspace, so that a leak produces a clear Java error with a heap dump, from -XX:+HeapDumpOnOutOfMemoryError, rather than a silent kill.

guard flagsruns offline
# steady state measured with jcmd <pid> VM.metaspace: 240 MB  ->  cap at about 2x
java -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError ...
# Result: a leak ends in a Java OutOfMemoryError plus a .hprof file, not a silent container kill
"What is the difference between the Metaspace error and the Compressed class space error?"

Metaspace is the whole area for class metadata: method bytecode, constant pools, annotations and the rest.

The compressed class space is a fixed reserved part of it that holds only the Klass structures, the objects an instance's header points to, kept in one contiguous region so that pointer can be stored as a 32-bit offset.

Its size is fixed at startup by -XX:CompressedClassSpaceSize, one gigabyte by default, and it cannot grow. So a leak fills it with a separate message even when metaspace itself has room, and the fix is the same leak hunt, not the flag.

With compact object headers, on by default from JDK 27 as of Aug 2026, the class pointer is narrower still, so the class space limit matters even more.

Q20 · Design. "Design hot reload of business rules in a running service without a restart: the rules are Java code, they change several times a day, and we must be able to roll back."

Reveal answer

Strong answer Requirements and assumptions: a rule set is a versioned jar produced by the rules team's build, a new version must take effect atomically for new requests while in-flight requests finish on the old one, rollback is a reload of the previous version, memory must not grow with the number of versions, and every switch must be auditable.

Design: the host owns a tiny API with a RuleSet interface and immutable input and output types. Each rule version is loaded by a fresh loader, a URLClassLoader with the host's API loader as parent, and instantiated through ServiceLoader.

Rule classes must be stateless and immutable, and the host checks by reflection at load time that no static field is non-final.

Activation is a three-step sequence: load and instantiate, validate by running a fixed set of golden cases through the new rule set and comparing with expected outcomes, then swap a single AtomicReference<RuleSet>.

A request captures the reference once at its start and uses it throughout, so a swap in the middle of a request cannot mix versions.

The previous version is kept for rollback; older loaders are closed, and a health metric built on WeakReference counts live rule loaders, which should be at most two.

Logging on every switch: the version identifier and jar checksum, who triggered it, validation results and duration, the identity hash of the new loader, and later the unload of the old one.

Trade-offs: every version costs metaspace until unloaded, and the first calls after a swap are slower because the call site through the interface becomes megamorphic and the JIT deoptimises and recompiles.

What I would not do: use Instrumentation.redefineClasses, because it cannot change shape and confuses the JIT; allow rules to keep state across versions in statics; or keep more than two loaders alive to make rollback faster.

Picture it the rule loaders, the single atomic reference, and what a request captures.

The setup: the activation sequence in code.

RuleHost.javaruns offline
private final AtomicReference<RuleSet> active = new AtomicReference<>();

void activate(Path jar) throws Exception {
    URLClassLoader loader = new URLClassLoader(new URL[]{jar.toUri().toURL()}, RuleSet.class.getClassLoader());
    RuleSet next = ServiceLoader.load(RuleSet.class, loader).findFirst().orElseThrow();
    validateWithGoldenCases(next);               // a failure here leaves 'active' untouched
    RuleSet old = active.getAndSet(next);        // the atomic swap
    retire(old);                                 // keep for rollback, close older loaders
}
Result handle(Request r) { RuleSet rules = active.get(); return rules.evaluate(r); }   // captured once

Make the invisible visible: which loader owns which version.

memory pictureruns offline
 active ──▶ RuleSet v7      (loader L7)     <- new requests
 previous ─▶ RuleSet v6     (loader L6)     <- rollback target, in-flight requests finish here
 v5, v4 ... closed, held only by WeakReference in the health metric -> collected

The trace: a swap in the middle of a request.

call traceruns offline
t0 request A: rules = active.get()      -> v6                     ✓ captured once
t1 activate(v7): validate golden cases  -> pass                   ✓
t2 active.getAndSet(v7)                 -> new requests see v7    ✓
t3 request A keeps using v6 to the end  -> no mixed versions      ✓

What you see: the audit line on switch, and the JIT recompiling right after.

log and PrintCompilationruns offline
# illustrative output
INFO rules.switch version=v7 sha256=9c1e... by=deploy-bot golden=48/48 took=212ms loader=@5f3a21
    41230  912       4       com.acme.Engine::run (96 bytes)   made not entrant
    41233  977       3       com.acme.Engine::run (96 bytes)

Land it One fresh loader per version, immutable rule objects, and one atomic reference give you reload and rollback for free, and the health metric on live loaders is what keeps the design honest over months.

Likely follow-ups
"The requirement changes: rules must keep counters and learned thresholds across versions. What changes?"

State moves out of the rule classes into the host. I would define a RuleState API type, owned by the host and stored in a concurrent map keyed by rule name, and pass it into each RuleSet evaluation.

A rule reads and updates state through that interface, never through its own static fields, so a new version sees the same counters, and the old loader still unloads because nothing from it is stored.

If the state's shape changes between versions, the API includes a migration hook called once at activation with the old state, run inside the validation step so a failed migration blocks the swap.

The cost is that state schema becomes part of the API contract, which needs versioning like any other API.

RuleSet APIruns offline
public interface RuleSet {
    Result evaluate(Request r, RuleState state);          // state owned by the host, never a static in the rule
    default RuleState migrate(RuleState old) { return old; }   // called once during validation
}
"What would you cut under time pressure?"

Unloading and the loader metric: I would keep the last two versions and restart the service nightly, which bounds metaspace at a known cost and removes the leak hunt from the critical path.

I would also cut the reflection check for static fields and replace it with a review rule.

I would keep the fresh loader per version, the atomic swap with capture at request start, and the golden-case validation before the swap, because those three are what make a bad rule version fail before it takes traffic.

If I had to cut one of those, it would be validation, replaced by a canary: switch one instance first and watch its error rate for five minutes.

"Why not an expression language or a scripting engine instead of Java jars?"

It is a real option and I would put it on the table. An interpreted rule language, such as a small expression library, removes class loading entirely, so no metaspace, no unloading and no loader identity problems, and non-engineers can edit rules.

The costs are performance, typically ten to a hundred times slower than compiled Java per evaluation, which matters if rules run per request at high rates; weaker tooling, since there is no compiler, refactoring or unit-test framework; and a second language to secure and maintain.

If rules are simple predicates changed by analysts, the interpreter wins. If rules are complex, tested code written by engineers and performance matters, compiled jars in fresh loaders win. The interface and the atomic swap design are the same either way.

"How do you prove the old version is really gone, and what does it cost the JIT when you swap?"

For unloading, the metric of live rule loaders comes from a list of WeakReference objects that the host prunes when get() returns null, exported as a gauge; an alert fires if it stays above two for more than an hour, and -Xlog:class+unload confirms it in the logs.

For the JIT: the host calls rules through the RuleSet interface at one call site, and after a swap that site has seen two receiver classes, so a monomorphic inlined call becomes bimorphic and, after a third version, megamorphic, which costs a virtual dispatch instead of an inlined body.

With -XX:+PrintCompilation the deoptimisation and recompilation is visible as "made not entrant" lines right after the swap, lasting seconds.

call site state across swapsruns offline
before swap : RuleSet.evaluate  receivers {V6}          monomorphic -> inlined body
after v7    : receivers {V6, V7}                        bimorphic   -> two guarded inlines
after v8    : receivers {V6, V7, V8}                    megamorphic -> itable/vtable dispatch  ✗

If that matters, the host can call through a MethodHandle held in a MutableCallSite, which the JIT treats as a constant per version and recompiles cleanly after setTarget.

Drill · Tiered compilation, inlining & escape analysis

This group tests whether you can explain how HotSpot turns bytecode into fast machine code, which decisions the compiler makes on your behalf, and how you would check those decisions instead of guessing.

Q21. "Before any compiler runs, what is the interpreter actually doing, and why does the JIT depend on it?"

Reveal answer

The real test Whether you know the interpreter is a profiler first and an executor second, so you can explain where the JIT's input comes from.

Strong answer HotSpot's interpreter is a template interpreter. At start-up it generates, for each of the roughly 200 bytecodes, a small piece of machine code called a template, and it executes a method by jumping from one template to the next.

That is faster than a classic switch-based interpreter, but it is still ten to fifty times slower than compiled code, because every bytecode is executed in isolation with no knowledge of its neighbours. The interpreter's second job is the important one: it counts and it profiles.

Every method has an invocation counter, incremented on entry, and a back-edge counter, incremented every time a loop jumps backwards. When those counters cross the tier thresholds, the method or the loop is queued for compilation.

Once a method reaches tier 3, the interpreter and the C1 compiler also fill a MethodData object, one per method, with per-bytecode facts:

  • Branches: which were taken and how often.
  • Receivers: which classes were seen at each call site, the type profile, up to TypeProfileWidth=2 classes.
  • Nulls: whether a reference was ever null.
  • Dead code: which bytecodes never executed at all.

The JIT, meaning the just-in-time compiler that produces machine code while the program runs, reads that MethodData and makes bets on it: inline the one receiver class it saw, compile a never-taken branch as a trap, skip a null check that never failed.

Without the profile, C2 would have to compile the general case everywhere, and most of its advantage would disappear. That is why HotSpot deliberately runs code slowly first: the slow phase is buying the information the fast phase needs.

Picture it the bytecode the interpreter steps through, the two counters it bumps, and the profile it leaves for C2.

The setup: a small hot method with a loop.

Sum.javaruns offline
static int sum(int[] a) {
    int s = 0;
    for (int i = 0; i < a.length; i++) s += a[i];
    return s;
}

Make the invisible visible: the bytecode the interpreter executes, one template per instruction.

javap -cruns offline
static int sum(int[]);
  Code:
     0: iconst_0
     1: istore_1
     2: iconst_0
     3: istore_2
     4: iload_2
     5: aload_0
     6: arraylength
     7: if_icmpge     22      // branch profile slot here: taken / not taken counts
    10: iload_1
    11: aload_0
    12: iload_2
    13: iaload
    14: iadd
    15: istore_1
    16: iinc          2, 1
    19: goto          4       // backward jump: back-edge counter ++
    22: iload_1
    23: ireturn               // method entry (offset 0): invocation counter ++

The trace: how the counters drive the tiers.

call traceruns offline
calls 1..199         interpreter, invocation counter rising, no MethodData yet         ✓ slow but cheap
call 200 or 60000 back-edges  -> queue a tier-3 (C1 + profile) compile                ✓
tier 3 runs          fills MethodData: branch at bci 7, loop trip counts               ✓
counters pass tier-4 thresholds -> C2 reads MethodData, bets on what it saw           ✓

What you see: one compile line per step in -XX:+PrintCompilation.

-XX:+PrintCompilationruns offline
# illustrative output
    118   41       3       Sum::sum (24 bytes)
   1630  305       4       Sum::sum (24 bytes)
   1631   41       3       Sum::sum (24 bytes)   made not entrant

Land it The interpreter is the measurement phase of a two-phase system, and the quality of compiled code is bounded by the quality of what the interpreter measured.

Likely follow-ups
"Where does the profile physically live, and what does it cost?"

It lives in the MethodData object, often called the MDO, which is allocated in metaspace, the native memory area that holds class metadata.

It is created lazily, only when a method reaches a profiling tier, and it holds a slot per profiled bytecode: branch counters, receiver-type entries, and trap history.

Its size is proportional to the method's bytecode size, so a service with 50,000 hot methods carries some tens of megabytes of MDOs.

The runtime cost is the extra work at tier 3, where every branch and call updates counters; that is why tier 3 code is around 30 percent slower than tier 1 code and why the JVM tries not to leave methods at tier 3 for long.

You can see the total under the Class line of jcmd <pid> VM.native_memory summary.

"What happens to the counters when the method is compiled?"

They keep working at tier 3, because C1's full-profiling variant emits the same counter updates into its machine code, and they are what push a method from tier 3 to tier 4.

Once C2 has compiled the method at tier 4, the counters stop, because tier 4 code carries no profiling instructions.

If that code is later deoptimised, meaning thrown away because one of its assumptions failed, the method returns to the interpreter, which continues incrementing the same counters and the same MethodData, so the next compilation sees both the old and the new evidence.

The trap history in the MDO is what stops C2 from making the same failed bet twice.

"Is there any way to skip the profiling phase?"

Yes, as of JDK 25, with the Leyden AOT cache. JEP 515, ahead-of-time method profiling, records the MethodData collected during a training run and stores it in the AOT cache file that -XX:AOTCacheOutput=app.aot produces.

At the next start with -XX:AOTCache=app.aot, hot methods begin life with a warm profile, so the JIT can compile them at tier 4 much sooner instead of waiting for thousands of interpreted invocations.

The cache does not contain machine code in the mainline JDK as of Aug 2026, so the compiler still runs; it just starts with the answers. The older trick, -XX:TieredStopAtLevel=1, skips profiling entirely by never using C2, at the price of lower peak performance.

two-run AOT cacheruns offline
# training run writes the cache (JDK 25), including method profiles
java -XX:AOTCacheOutput=app.aot -jar app.jar
# production start reads it: hot methods begin with a warm profile
java -XX:AOTCache=app.aot -jar app.jar

Q22. "Walk me through the five tiers of tiered compilation, the thresholds, and when the JVM leaves the normal 0-to-3-to-4 path."

Reveal answer

Strong answer HotSpot has two compilers and five levels. Level 0 is the interpreter.

Levels 1, 2 and 3 are all produced by C1, the fast client compiler:

  • Level 1: C1 code with no profiling.
  • Level 2: C1 with only invocation and back-edge counters.
  • Level 3: C1 with full profiling, including type and branch profiles.

Level 4 is C2, the optimising compiler. The normal path is 0 to 3 to 4. A method runs interpreted until its invocation counter passes Tier3InvocationThreshold=200, or its loops pass Tier3BackEdgeThreshold=60000, and it is queued for C1 at level 3.

Level 3 code runs while collecting a profile until the counters pass Tier4InvocationThreshold=5000 or Tier4BackEdgeThreshold=40000, and then C2 compiles it at level 4, which replaces the level 3 version.

Those thresholds are not fixed numbers; they are scaled by how long the compile queues are, so a busy C2 queue raises the bar for entry. Two detours matter.

  • Trivial method: a getter with no branches would give C2 nothing from a profile, so it goes straight from 0 to 1 and stays there, because level 1 code is as fast as C2 would be for that case.
  • Backed-up C2 queue: the JVM compiles at level 2 instead of level 3, because level 2 is around 30 percent faster than level 3, and moves the method to level 3 later when C2 has capacity.
  • C2 switched off: -XX:TieredStopAtLevel=1 gives quick warm-up, low compile CPU and a smaller code cache, at the price of noticeably lower peak throughput, a fair trade for short-lived tools and test runs but not for a server.

Picture it the five levels side by side, and a compile log showing the normal path and the trivial-method detour.

The setup: a trivial getter and a method with a loop.

Calc.javaruns offline
double getRate() { return rate; }                                  // 5 bytes, no branches -> 0 to 1
double price(int[] qty) {                                          // loop + multiply -> 0 to 3 to 4
    double t = 0;
    for (int q : qty) t += q * rate;
    return t;
}

Make the invisible visible: what each level is.

The five levels
LevelProduced byProfilingUsed for
0InterpreterCounters and full MethodData once profiling startsCold code
1C1NoneTrivial methods, or everything with TieredStopAtLevel=1
2C1Invocation and back-edge counters onlyStand-in while the C2 queue is backed up
3C1Full profile (types, branches)Normal step before C2
4C2None (uses the profile)Hot methods at peak speed

The trace: the normal path and the two detours.

call traceruns offline
price():   0 --(200 calls)--> 3 --(5000 calls)--> 4                       ✓ normal path
getRate(): 0 ----------------------------------> 1  (stays)               ✓ nothing to learn
price() with C2 queue long: 0 -> 2 -> (queue shortens) -> 3 -> 4          ✓ protects the trade

What you see: the tier is the fourth column.

-XX:+PrintCompilationruns offline
# illustrative output
    105   41       3       com.acme.Calc::price (38 bytes)
    131   44       1       com.acme.Calc::getRate (5 bytes)
   1840  312       4       com.acme.Calc::price (38 bytes)
   1841   41       3       com.acme.Calc::price (38 bytes)   made not entrant

Land it The tiers exist so that the JVM can run acceptable code immediately while it buys a profile for excellent code later, and every deviation from 0-3-4 is the JVM protecting that trade.

Likely follow-ups
"The thresholds are 200 and 5000 invocations, but I have seen methods compiled much earlier. Why?"

Because the predicate combines invocations and back-edges. The tier 3 rule is: compile if invocations exceed Tier3InvocationThreshold=200, or if invocations exceed Tier3MinInvocationThreshold=100 and invocations plus back-edges exceed Tier3CompileThreshold=2000. So a method called 120 times with a loop of 20 iterations each qualifies.

worked example of the tier 3 ruleruns offline
invocations = 120, back-edges = 120 * 20 = 2400
rule A: 120 > Tier3InvocationThreshold (200)?                                  no
rule B: 120 > Tier3MinInvocationThreshold (100)  and  120 + 2400 = 2520 > Tier3CompileThreshold (2000)?   yes ✓
Result: queued for tier 3 at 120 calls, long before the headline 200

The tier 4 rule works the same way with Tier4MinInvocationThreshold=600 and Tier4CompileThreshold=15000.

All of these are multiplied by a scale factor derived from queue length, controlled by Tier3LoadFeedback=5 and Tier4LoadFeedback=3, so on an idle compiler the effective thresholds can be lower than the headline numbers, and on a saturated one they are higher. You can print the effective values with -XX:+PrintFlagsFinal.

"When would you actually set TieredStopAtLevel=1 in production?"

For a short-lived process where warm-up dominates total run time: a CLI, a build step, a batch job that finishes in a minute, or a serverless function that is recycled often.

In those cases C2 rarely pays for itself, and C1-only code can be ready in a fraction of the time with far less compiler CPU competing with application threads.

I would not use it for a long-running service, because C2's inlining, escape analysis and loop optimisations are worth a large factor on compute-heavy code.

The honest way to decide is to measure both under the real workload with JFR and compare throughput at ten minutes, not at ten seconds.

"How would you see which tier a method is at right now?"

The quickest live view is jcmd <pid> Compiler.codelist, which prints every compiled method with its compile id, tier level, and address, so I can grep for the method and read the level.

At start-up, -XX:+PrintCompilation prints one line per compilation with the tier in the fourth column.

For history, the JFR event jdk.Compilation records the method, the tier, the duration and the code size for each compile, and jfr print --events jdk.Compilation recording.jfr shows them.

If a method never appears at level 4 after minutes of load, that is a finding in itself.

"What does it mean when a method is stuck at tier 3?"

It means C2 has not produced level 4 code for it, and there are three usual reasons. The C2 queue may be behind, which shows as a long jcmd <pid> Compiler.queue output and high CPU on the C2 compiler threads.

The method may be too large: bytecode over HugeMethodLimit=8000 is not compiled at all, and very large methods time out in C2. Or C2 may have failed or bailed out, which appears in -XX:+PrintCompilation as COMPILE SKIPPED with a reason.

Being stuck at tier 3 is worse than tier 1, because tier 3 code carries profiling overhead, so a service with many methods stuck there runs slower than it would with C1 only.

Q23 · Scenario. "A developer wrote a main method with one big loop to benchmark a parser, got 40 microseconds per document, and production shows 12. Same JDK, same code. Explain the gap and how you would prove it."

Reveal answer

Strong answer I would work through it in this order:

  1. Symptom: a single long-running loop inside one method is being measured. That loop never returns to its caller, so the method's invocation counter never reaches the tier thresholds. The only way the JVM can speed it up is on-stack replacement, OSR for short: when the back-edge counter passes Tier3BackEdgeThreshold=60000 and later Tier4BackEdgeThreshold=40000, the compiler produces a special version of the method whose entry point is the loop header, and the running interpreter frame is swapped for a compiled frame mid-loop.
  2. Evidence: run with -XX:+PrintCompilation. OSR compilations carry a % flag and print @ bci with the bytecode index of the loop. If the benchmark method only ever appears with %, we are timing OSR code.
  3. Why that is slower: an OSR compilation is built around the loop entry state rather than the method's normal entry. Values that were locals in the interpreter arrive through a migration buffer, loop-invariant code motion and range-check elimination are weaker because the compiler cannot assume anything about the state before the loop, and escape analysis often fails on objects created before the loop began. C2 also cannot inline the benchmark method into anything. The result is commonly two to four times slower than the normal compiled version of the same code.
  4. Fix: measure with JMH, the Java microbenchmark harness, which calls the benchmark method many times so it is compiled the normal way, runs separate warm-up iterations, forks fresh JVMs, and consumes results through Blackhole so dead-code elimination cannot remove the work. If we must keep a hand-written harness, put the work in a method called repeatedly from the loop and time only after a warm-up of tens of thousands of calls.
  5. Prevention: a team rule that no performance number is quoted without a JMH run, and a JMH module in the repository with a -prof gc profile so allocation is reported alongside time.

Picture it the benchmark loop being swapped from interpreted to OSR-compiled code mid-run, and the JMH version that measures the real thing.

The setup: the hand-written harness with the three defects listed in its comments.

the benchmark that measured nothingruns offline
// BROKEN — and 40 microseconds is the tell: it is too fast to be real.
public static void main(String[] args) {
    long start = System.nanoTime();
    for (int i = 0; i < 1_000_000; i++) {
        parser.parse(DOC);            // result is never used
    }
    System.out.println((System.nanoTime() - start) / 1_000_000);
}

// THREE THINGS WENT WRONG, and each alone invalidates the number:
//
// 1. DEAD CODE ELIMINATION. The result is unused and parse() has no visible
//    side effect, so C2 proves the whole call is unnecessary and deletes it.
//    You timed an empty loop.
//
// 2. NO WARM-UP. The first thousands of iterations run interpreted, then in
//    C1, then C2, and OSR-compile the loop mid-flight. The average mixes
//    four different execution modes.
//
// 3. CONSTANT FOLDING. DOC is effectively final, so the JIT may hoist work
//    out of the loop entirely, or profile the branch as always-taken and
//    compile a version that is wrong for real input.

Make the invisible visible: the running frame of main being replaced in the middle of the loop.

memory pictureruns offline
 stack, before                      stack, after OSR (loop header bci 8)
 ----------------                   -----------------------------------
 [ main  interpreter frame ]        [ main  OSR frame, compiled: locals copied via a migration buffer ]
   i = 61_000, start, parser          the method's normal entry point is still NOT compiled

The trace: what the loop passes through.

call traceruns offline
iterations 0..60k   interpreter, back-edge counter rising                    ✗ slow
60k back-edges      OSR compile at tier 3 (profiling), frame swapped        ✗ still carries profiling cost
+40k back-edges     OSR compile at tier 4, frame swapped again              ✗ weaker optimisation than a normal compile
end                 average over all phases = 40 us per document           ✗ not what production runs

What you see: OSR compilations carry a % and an @ bci, and the method never appears without it.

-XX:+PrintCompilationruns offline
# illustrative output
    210   45 %     3       Bench::main @ 8 (60 bytes)
    498   47 %     4       Bench::main @ 8 (60 bytes)

Why: the loop never returns, so only back-edge counting can trigger compilation, and OSR code is built around the loop entry state.

The fix: JMH calls the benchmark method repeatedly, so it is compiled the normal way.

the same measurement, done honestly with JMHruns offline
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 5, time = 1)         // let it reach a steady state
@Measurement(iterations = 10, time = 1)
@Fork(3)                                  // separate JVMs: separate profiles
@State(Scope.Benchmark)
public class ParserBenchmark {

    private Parser parser;
    private String doc;

    @Setup public void setup() { parser = new Parser(); doc = loadRealisticDoc(); }

    @Benchmark
    public Document parse() {
        return parser.parse(doc);        // RETURNED -> JMH consumes it, no DCE
    }

    @Benchmark
    public void parseWithBlackhole(Blackhole bh) {
        bh.consume(parser.parse(doc));   // explicit form when there are several results
    }
}
// Run with -prof gc as well: allocation rate is often the real difference,
// and it is invisible in a wall-clock number.

@Fork(3) is the option people skip and should not. The JIT's profile is per-JVM, so running all variants in one JVM lets the first benchmark's profile pollute the second's compilation — which routinely produces differences of two or three times that vanish under separate forks.

What you see now: JMH reports the steady-state figure, close to production.

JMH outputruns offline
# illustrative output
Benchmark                    Mode  Cnt   Score   Error  Units
ParserBenchmark.parse        avgt   30  12.4 ±   0.3  us/op
ParserBenchmark.parse:gc.alloc.rate.norm  avgt  30  3120 B/op

Land it A single big loop measures OSR code, which is a different and worse artefact than the code production runs, so the harness itself was the bug.

Likely follow-ups
"They switched to JMH and now get 9 microseconds, better than production. Is that believable?"

Yes, and it is the opposite trap. A JMH benchmark that feeds the parser one document shape produces a perfectly monomorphic profile, so C2 inlines every call site and eliminates every branch it never saw.

Production feeds hundreds of shapes, so its profile is polymorphic and some inlining is lost. It can also be dead-code elimination if a result is not returned or passed to a Blackhole.

I would check three things: that the benchmark cycles through a realistic sample of inputs, that every result is consumed, and that -prof gc reports similar allocation per operation to what JFR's jdk.ObjectAllocationSample shows in production.

Nine versus twelve with those checks passed is a plausible gap for lost polymorphic inlining.

"The fix did not work: JMH still shows 40 microseconds. What next?"

Then the difference is not OSR. I would compare JVM flags first with -XX:+PrintFlagsFinal in both environments, because a benchmark laptop often runs a different GC, a different heap, or a different CPU count, which changes CICompilerCount. Then I would run the benchmark with -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining and look for callee is too large or too many traps on the parser's hot methods, which would say the shape of the benchmark code prevents inlining. Finally I would profile both with async-profiler in CPU mode and diff the flame graphs; if the benchmark spends time in a frame production never shows, that frame is the answer.

"Can you switch OSR off, and would you?"

You can, with -XX:-UseOnStackReplacement, and I would only ever do it in a diagnostic run to prove that OSR was the cause: with it off, the big-loop benchmark stays interpreted and gets dramatically slower, which confirms the whole measurement was OSR-bound. In production OSR is essential, because request-processing threads often sit in a long-lived loop, such as a consumer polling a queue, and without OSR that loop would stay interpreted until the method returned, which might be never. The right response is to fix the harness, not to disable a mechanism that production depends on.

"Does OSR happen at tier 3 and tier 4 separately?"

Yes. With tiered compilation there are OSR versions at level 3 and at level 4, each triggered by its own back-edge threshold, and -XX:+PrintCompilation shows them as two separate lines with the % flag and different tier numbers.

The level 3 OSR version collects a profile for the loop body just as normal level 3 code does, and once Tier4BackEdgeThreshold=40000 more back-edges pass, C2 produces the level 4 OSR version.

If the loop later exits and the method is called again normally, that call goes through the interpreter or the normal compiled version, not the OSR one, because OSR code is only enterable at its loop header.

-XX:+PrintCompilationruns offline
# illustrative output: the same loop, two OSR versions, then a normal compile once the method is called often
    210   45 %     3       Bench::run @ 8 (60 bytes)      <- OSR, tier 3
    498   47 %     4       Bench::run @ 8 (60 bytes)      <- OSR, tier 4
    931  118       4       Bench::run (60 bytes)          <- normal entry, no %

Q24. "What is the practical difference between C1 and C2, and how are compile threads and queues organised?"

Reveal answer

Strong answer C1 is built to be fast to run; C2 is built to produce fast code.

C1 compiles a method in a fraction of a millisecond using a simple intermediate form.

  • C1 does: inlining of small methods, constant folding, local value numbering, and removal of obvious null and range checks.
  • C1 does not: global analysis, so it does not move code out of loops, does not eliminate allocations, and does not make speculative bets beyond what the profile trivially allows.

C2 works on a sea-of-nodes representation, a graph in which every operation is a node and only true data and control dependencies are edges, so the compiler can reorder freely.

On that graph it does:

  • Inlining: aggressive, guided by the profile.
  • Allocation removal: escape analysis and scalar replacement.
  • Loop work: unrolling, loop invariant code motion, range-check elimination and auto-vectorisation.
  • Speculation: never-taken branches compiled as traps.

A C2 compilation of a hot method typically takes milliseconds to tens of milliseconds and can take seconds for huge methods.

Both compilers run on background threads; compilation is asynchronous by default under -XX:+BackgroundCompilation, so the application keeps running the old version, interpreted or level 3, while the new one is built.

The number of compiler threads is set by CICompilerCount, which the JVM sizes from the CPU count, and it is split roughly one third C1 to two thirds C2, so a 16-core machine gets 12 threads, 4 for C1 and 8 for C2.

Each compiler has its own queue, and the queues are prioritised so that hotter methods compile first. You can inspect the queues live with jcmd <pid> Compiler.queue.

Picture it the two compiler thread groups with their queues, and what each compiler does to the same loop.

The setup: one loop with a field read and a bounds-checked array access.

Scale.javaruns offline
long scale(int[] a, int k) {
    long sum = 0;
    for (int i = 0; i < a.length; i++) sum += (long) a[i] * k + bias();   // bias() is a tiny final-field getter
    return sum;
}

Make the invisible visible: the threads and queues on a 16-core machine, and the code each compiler produces.

compiler threads and queuesruns offline
 16 cores -> CICompilerCount = 12  (about 1/3 C1, 2/3 C2)
 C1 queue ─▶ [C1 thread x4]   ms per method        │ app threads keep running the old
 C2 queue ─▶ [C2 thread x8]   ms .. seconds        │ version (BackgroundCompilation)
 hotter methods are picked first in each queue
what the compiler generatesruns offline
C1 (pseudo):  loop { check i < a.length; load a[i]; call-free bias inlined; multiply; add }   // checks stay per iteration
C2 (pseudo):  b = bias();                      // hoisted out of the loop
              unrolled x4, range check proved by loop bounds, no check inside
              vector multiply-add on 4/8 lanes where the shape allows

The trace: what an application thread sees while a hot method is being built.

call traceruns offline
t0   scale() runs interpreted, counters cross threshold          ✓
t1   queued for C1 (tier 3), app keeps calling the interpreter   ✓ not blocked
t2   tier 3 code installed; profile fills                         ✓
t3   queued for C2; app keeps running tier 3                      ✓ not blocked
t4   tier 4 code installed, tier 3 version made not entrant       ✓

What you see: compiler threads show up by name in a thread listing.

top -H -p <pid>runs offline
# illustrative output
  PID USER   %CPU COMMAND
 4311 app     48.0 C2 CompilerThre
 4310 app     12.0 C1 CompilerThre
 4290 app     60.0 http-nio-exec-1

Land it C1 gets you off the interpreter quickly and C2 gets you to peak, and the compile queue is where you look when either is not happening fast enough.

Likely follow-ups
"Compiler threads are burning 30 percent of a small container's CPU at start-up. What do you do?"

First I confirm it is compilation, because top -H shows threads named C2 CompilerThre and C1 CompilerThre, and JFR's jdk.CompilerStatistics event gives total compile time. Then I decide whether it is a start-up spike or a steady drain.

A spike of a few minutes is normal and best handled by ramping traffic. A steady drain means recompilation churn, which I would chase with jdk.Deoptimization events.

If the container is tiny, I can lower -XX:CICompilerCount=2 to leave CPU for requests, accepting slower warm-up, and I would ship an AOT cache with -XX:AOTCache on JDK 25 or later so fewer methods need profiling at all.

I would not set -XX:TieredStopAtLevel=1 on a long-lived service just to save start-up CPU.

"Why is C2 compilation of a method sometimes abandoned?"

C2 has bail-out conditions. The method may exceed DesiredMethodLimit=8000 bytecodes after inlining, the node graph may exceed MaxNodeLimit=80000 nodes, an unloaded class may be needed, or an internal assertion may trip on an unusual bytecode shape.

In each case C2 gives up and the method stays at level 3, or drops to level 1 if the JVM decides profiling is pointless. -XX:+PrintCompilation prints COMPILE SKIPPED with a reason, and -XX:+UnlockDiagnosticVMOptions -XX:+LogCompilation records the failure in the XML log.

-XX:+PrintCompilationruns offline
# illustrative output (reason text varies by failure)
   7311  842       4       com.acme.Big::run (9100 bytes)   COMPILE SKIPPED: out of nodes (not retryable)
# ✅ FIX: split Big::run so each part compiles within the node limit

The practical fix is almost always to split a very large method or to reduce inlining depth into it with -XX:CompileCommand=dontinline on a specific callee.

"Can you force a method to compile synchronously?"

Yes. -XX:-BackgroundCompilation makes every compilation blocking, so the calling thread waits until the compiled code exists, and -XX:+PrintCompilation then shows a b flag on those lines.

It is a diagnostic tool, not a production setting, because request threads would stall for tens of milliseconds while C2 works.

A narrower version is -XX:CompileCommand=compileonly,com.acme.Parser::parse combined with -Xcomp, which compiles at first invocation without profiling; that produces poor code and is only useful for reproducing a compiler bug.

The JMH harness uses its own warm-up phases rather than these flags, which is the right model for benchmarks.

Q25. "Explain HotSpot's inlining rules, the messages PrintInlining gives when it refuses, and how you make a hot method inlinable."

Reveal answer

The real test Whether you know inlining is the optimisation that enables every other one, and can name the limits and read the compiler's own explanation.

Strong answer Inlining means copying the body of a called method into the caller so there is no call at all.

It matters far beyond saving a call instruction: once the callee is inside the caller, C2 can see its allocations for escape analysis, fold its constants, and move its loads out of loops. The rules are size-based and profile-based.

The size rules, each with its flag:

  • Any call site: a callee of at most MaxInlineSize=35 bytecode bytes is inlined, however hot or cold the site.
  • Hot call site: the limit rises to FreqInlineSize=325 bytes.
  • Depth: inlining nests up to MaxInlineLevel=15 deep, and the same method recursively only one level.
  • Already compiled: if the callee's compiled code is larger than InlineSmallCode=2500 bytes of machine code, C2 prefers to call it rather than copy it.
  • Whole unit: the compilation is capped at DesiredMethodLimit=8000 bytecodes.
  • Virtual and interface calls: inlined only when the profile shows one or two receiver classes.

To see the decisions, run with -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining.

Each call site prints the callee and either inline (hot) or a refusal:

  • too big: over 35 bytes at a cold site.
  • callee is too large or hot method too big: over 325 bytes at a hot site.
  • already compiled into a big method: the InlineSmallCode rule.
  • inlining too deep: level 15.
  • no static binding or virtual call: the profile was megamorphic.

To make a method inlinable, I shrink its bytecode below the threshold by moving rare branches into a separate method, which also fixes depth, I avoid megamorphic call sites inside it, and I never rely on raising FreqInlineSize globally, because that bloats every compilation.

Picture it PrintInlining output for a hot loop before and after the cold path is moved out of the hot callee.

The setup: a hot caller and a callee whose rare error path makes it big.

OrderService.javaruns offline
long sumTotals(List<Order> orders) {
    long t = 0;
    for (Order o : orders) t += o.checked();            // hot call site
    return t;
}
// ❌ TRAP: the rare branch builds a long message, pushing checked() to about 410 bytecode bytes
long checked() {
    if (items == null)
        throw new IllegalStateException("order " + id + " customer " + customer + " at " + Instant.now() + " " + audit());
    return total();
}

Make the invisible visible: the size the inliner compares with the limits.

javap -c (size line)runs offline
long checked();
  Code:
     0: aload_0 ... ~400 bytes including string building ...
   409: lreturn          // size seen by the inliner = last offset + 1 = 410 > FreqInlineSize (325)

The trace: the decision at the hot call site.

call traceruns offline
site o.checked() is hot            -> limit is FreqInlineSize = 325
callee size 410                    -> 410 > 325                              ✗ not inlined
caller cannot see through checked() -> no escape analysis, no hoisting       ✗

What you see: the refusal message with the callee name and size.

-XX:+PrintInliningruns offline
# illustrative output
@ 24   com.acme.Order::checked (410 bytes)   hot method too big

Why: the limit counts bytecode size, so a rare branch costs as much as a hot one.

The fix: keep the hot path small and move the cold path to its own method.

Order.java (fixed)runs offline
long checked() {
    if (items == null) throw failure();          // ✅ FIX: cold path lives in failure(), 7 bytes here
    return total();
}
private IllegalStateException failure() { return new IllegalStateException("order " + id + " ..."); }

What you see now: the same call site is inlined, and so is what it calls.

-XX:+PrintInliningruns offline
# illustrative output
@ 24   com.acme.Order::checked (17 bytes)   inline (hot)
  @ 10   com.acme.Order::total (32 bytes)   inline (hot)

Land it Inlining is decided by bytecode size and profile shape, and the fix is almost always to make the hot path small and the cold path a separate method rather than to touch the flags.

Likely follow-ups
"Why is the limit in bytecodes rather than lines or machine code?"

Because bytecode size is known before compilation starts and correlates well with the amount of work the compiler will do. Machine-code size is only known afterwards, which is why InlineSmallCode=2500 exists as a second rule for callees that have already been compiled.

A single line of Java can be a large amount of bytecode: a string concatenation with five parts, a lambda creation, or a switch on strings each expand to dozens of bytes, so a method that looks short in the editor can be well over 35 bytes.

The reliable way to know is javap -c, which prints the bytecode with offsets; the last offset plus one is the size the inliner sees.

"Can you force inlining for one method without changing global flags?"

Yes, with a compiler directive: -XX:CompileCommand=inline,com.acme.Codec::decode tells C2 to inline that method at every call site, and dontinline does the opposite.

Directives can also be loaded at runtime from a JSON file with jcmd <pid> Compiler.directives_add directives.json, which is useful for testing a hypothesis on one production instance.

The JDK's own @ForceInline annotation in jdk.internal.vm.annotation is honoured only for privileged JDK classes, not application code, so it is not an option.

I treat a forced inline as a diagnostic: if it fixes the number, I go back and make the method small enough that the default heuristics reach the same decision.

directives.jsonruns offline
[
  { match: "com/acme/Codec.decode",
    c2: { Inline: ["+com/acme/Codec.decode"] } }       // apply with: jcmd <pid> Compiler.directives_add directives.json
]
"How does inlining interact with exceptions and synchronized?"

Both are fine but visible. A method with a try block inlines normally, and the exception table is merged; -XX:+PrintCompilation marks the resulting compilation with !.

A synchronized method inlines too, marked with s, and the monitor enter and exit come with it, which means C2 can then apply lock coarsening across adjacent inlined synchronized calls or elide the lock completely if escape analysis proves the object is thread-local.

What does hurt inlining is a method that is both large and rarely called, because it contributes bytes to the caller's budget but nothing to the profile; those are the ones I split out.

"What is the cost of inlining too much?"

Three costs. Code cache: every inlined copy is machine code, and a hot method inlined into 200 callers exists 200 times, which is why InlineSmallCode stops copying big compiled methods.

Compile time: the node graph grows with every inline, and C2 hits MaxNodeLimit=80000 or simply takes seconds, which delays every other method in the queue.

Deoptimisation blast radius: when an inlined callee's assumption fails, for example a new subclass appears, the whole caller is thrown away and recompiled, not just the callee.

So raising MaxInlineLevel or FreqInlineSize globally usually trades a small win on one hot path for slower warm-up and a bigger code cache everywhere.

Q26 · Scenario. "A shared Formatter.format(Value v) utility is used by twenty services. In one service it is hot and profiles show it is 3× slower than in the others, with time spent in itable stub. Walk me through it."

Reveal answer

Strong answer I would diagnose it in this order:

  1. Symptom: itable stub in a profile means an interface call is being dispatched through the interface table, the slow, generic lookup path. That only happens when the call site is megamorphic, which means the JIT's inline cache at that bytecode has seen more than two receiver classes. Every call site in HotSpot starts monomorphic, a single cached class with a direct jump; a second class makes it bimorphic, two checks; a third class, past TypeProfileWidth=2, makes it megamorphic and C2 gives up on inlining there and emits a real virtual dispatch.
  2. Evidence: run the slow service with -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining and find the v.render() call inside format. In the fast services it says inline (hot) with one receiver type; in the slow one it says virtual call or no static binding. jcmd <pid> Compiler.codelist confirms which compiled version is live.
  3. Ranked causes:
    1. Mixed receivers: the slow service passes three or more Value implementations through the same format method. The type profile at that one bytecode lives in format's own MethodData, so it is polluted for every caller: even a caller that only ever passes IntValue gets the megamorphic code.
    2. Early poisoning: a warm-up or test path fed odd types through it before real traffic arrived.
  4. Fix: give each hot caller its own call site. The simplest form is to duplicate the small utility per type, for example formatInt and formatDecimal, so each has its own profile. If the code must stay generic, peel the common case by hand: if (v instanceof IntValue iv) return renderInt(iv); before the interface call, which gives C2 a guarded fast path. Verify with PrintInlining and a JMH run.
  5. Prevention: in shared libraries, keep the polymorphic dispatch in the caller's code and the hot work in small type-specific methods, and add a JMH benchmark that feeds the realistic mix of types so a regression to megamorphic shows up in CI.

Picture it the type profile of the one call site inside format, and how it moves from monomorphic to megamorphic.

The setup: a shared utility with one interface call site, called by every service.

Formatter.javaruns offline
interface Value { String render(); }
// ❌ TRAP: one call site (v.render()) shared by every caller, so one profile for all of them
static String format(Value v) { return "[" + v.render() + "]"; }

Make the invisible visible: the receiver slots in format's MethodData for the v.render() bytecode.

type profile of the call siteruns offline
 fast service:   slot1 = IntValue  (100%)                           -> monomorphic, inline
 slow service:   slot1 = IntValue, slot2 = DecimalValue, + others   -> more than TypeProfileWidth=2
                                                                       -> megamorphic, itable stub

The trace: how the site degrades as new classes arrive.

call traceruns offline
v = IntValue      -> cache IntValue, direct jump, inlined                ✓
v = DecimalValue  -> second class: two guards, both inlined             ✓ bimorphic
v = MoneyValue    -> third class: no inlining, itable lookup per call   ✗ megamorphic

What you see: the inlining line differs between the services.

-XX:+PrintInliningruns offline
# illustrative output
fast :  @ 3   com.acme.IntValue::render (9 bytes)   inline (hot)
slow :  @ 3   com.acme.Value::render (0 bytes)   virtual call
# async-profiler (slow service): itable stub shows as a frame above render()

Why: the profile belongs to the call site inside the shared method, not to the caller.

The fix: give the hot caller a guarded fast path or its own site.

Formatter.java (fixed)runs offline
static String format(Value v) {
    // ✅ FIX: type-specific hot path first, generic dispatch only for the rest
    if (v instanceof IntValue iv) return "[" + renderInt(iv) + "]";
    return "[" + v.render() + "]";
}

What you see now: the hot site is inlined again.

-XX:+PrintInliningruns offline
# illustrative output
slow :  @ 1   com.acme.Formatter::renderInt (14 bytes)   inline (hot)

Land it The profile belongs to the call site inside the shared method, so one polluting service degrades the code for every path through it, and the cure is to split the site, not to tune the compiler.

Likely follow-ups
"The fix did not work: after splitting, the call site is still megamorphic. What next?"

Then the pollution is one level down. If renderInt itself calls another shared method that switches on type, that inner call site is now the megamorphic one, and PrintInlining will show it nested under the caller.

I would read the full inlining tree, not just the top line.

The second possibility is that the split method is not inlined at all because it is over FreqInlineSize=325 bytes, so the caller's monomorphic profile never reaches it; the message would be callee is too large.

The third is that the old profile is still in use because the method was never recompiled; a restart, or waiting for the next deoptimisation, gives the JIT a fresh look.

-XX:+PrintInlining (nested tree)runs offline
# illustrative output
@ 5   com.acme.Formatter::format (23 bytes)   inline (hot)
  @ 1   com.acme.Formatter::renderInt (14 bytes)   inline (hot)
    @ 7   com.acme.Digits::toText (30 bytes)   virtual call      <- the megamorphic site is one level down

Finally, JDK 25's AOT method profiles can carry a polluted profile from the training run into every start, so I would check what the training workload fed it.

"Why does C2 stop at two receiver classes? Could it inline three?"

It is a cost decision. Each inlined receiver adds a class check and a copy of the callee body, and with three or more the chain of checks starts costing more than a table dispatch while the code size grows linearly.

Two also happens to cover the most common real pattern, one main implementation plus one fallback.

There is also a majority rule: if one receiver accounts for at least TypeProfileMajorReceiverPercent=90 percent of the samples, C2 inlines that one behind a guard and traps to the interpreter for the rest, even when other classes exist.

You can widen the profile with -XX:TypeProfileWidth=4, but as of Aug 2026 C2's inliner still only specialises up to bimorphic sites, so the extra width helps analysis, not code generation.

"Does the same thing happen with streams and lambdas?"

Yes, and it is the most common form of it. Every stream pipeline calls Function.apply and Predicate.test inside the shared JDK stream classes, and those call sites see every lambda in the application, so they are megamorphic from the first minute.

The JDK mitigates it in part by compiling with -XX:TypeProfileLevel=111 style argument profiling for its own internals, and by inlining the whole pipeline into the caller when it is small enough, which gives the caller's copy of the call site its own profile.

When that inlining fails, the lambda is called through an itable stub. That is why a hot inner loop written as a stream can be several times slower than the same loop written by hand, while a stream in a cold path costs nothing that matters.

"How do you confirm in production without restarting with diagnostic flags?"

Two ways. First, async-profiler in CPU mode already shows itable stub and vtable stub as frames, and their share of the parent frame's time tells me how bad the dispatch is.

Second, compiler directives can be added at runtime: jcmd <pid> Compiler.directives_add pi.json with a directive that sets PrintInlining true for the one method, and then jcmd <pid> Compiler.directives_clear afterwards; the output appears on the JVM's stdout at the next compilation of that method, which I can force by making it deoptimise or by waiting for the next recompilation.

pi.jsonruns offline
[ { match: "com/acme/Formatter.format", c2: { PrintInlining: true } } ]
// jcmd <pid> Compiler.directives_add pi.json   ...   jcmd <pid> Compiler.directives_clear

JFR's jdk.CompilerInlining event also exists but is disabled in the default profiles because of its volume.

Q27. "What does escape analysis actually decide, when does it eliminate an allocation, and when is the claim that 'allocation is free' wrong?"

Reveal answer

Strong answer Escape analysis is a C2 pass that asks, for each new in a compilation unit, where the object can be seen from.

An object does not escape if every use of it is visible inside the compiled code: it is not stored into a field or an array, not passed to a method that was not inlined, not returned, and not used as a lock that another thread could observe.

C2 classifies each allocation as NoEscape, ArgEscape, meaning it is passed to a callee but does not outlive the call, or GlobalEscape.

For NoEscape objects the compiler performs scalar replacement: it deletes the allocation and turns each field into a plain local variable, which then lives in a register or on the stack. Nothing is allocated, nothing is zeroed, and the garbage collector never sees it.

HotSpot does not do true stack allocation of objects; scalar replacement is the only form. The limits are what matter in practice.

The object's entire life must be inside the one compiled method, so every method that touches it must have been inlined, which ties this to the inlining limits from Q25. Arrays are only replaced up to EliminateAllocationArraySizeLimit=64 elements with constant indices.

If the object flows through a control-flow merge, for example it is created in both branches of an if and used afterwards, the analysis has historically given up, though JDK 22 and later reduce that case.

An interface call that is not inlined makes the object escape.

So "allocation is free" is true for a short-lived iterator or a small record inside a fully inlined hot loop, and false the moment the object crosses an un-inlined call, a merge, or a lambda boundary.

On a product JVM the honest check is not a flag but a measurement: a JMH run with -prof gc reporting zero bytes per operation, or JFR's jdk.ObjectAllocationSample showing no samples for that type under load.

Picture it one method before and after scalar replacement, and the allocation figure that proves which one you got.

The setup: three escape states in the code block below.

what escape analysis actually decidesruns offline
// NO ESCAPE — the object is provably confined to this method.
// C2 can scalar-replace it: the allocation disappears and x/y become registers.
double distance(double x1, double y1, double x2, double y2) {
    Point a = new Point(x1, y1);       // never leaves this frame
    Point b = new Point(x2, y2);
    return a.distanceTo(b);            // inlined, then the objects vanish
}

// ARG ESCAPE — passed to a method that does not store it. Still eligible,
// but ONLY if that method is inlined, so the analysis can see what it does.
void log(Point p) { logger.debug("at {}", p); }   // too big to inline -> escapes

// GLOBAL ESCAPE — stored somewhere reachable after the method returns.
// No elimination is possible.
Point cached;
void update() { cached = new Point(1, 2); }        // escapes to a field

// THE THREE THINGS THAT SILENTLY DEFEAT IT:
//   1. The allocating method is not inlined into the caller (too big, megamorphic).
//   2. The object is stored in a field, an array, or a collection.
//   3. It is passed to something the JIT cannot see through — a virtual call
//      with many receiver types, or a native method.

Make the invisible visible: what C2 turns the NoEscape method into.

what the compiler generatesruns offline
// source after inlining distanceTo
double distance(double x1, double y1, double x2, double y2) {
    Point a = new Point(x1, y1);  Point b = new Point(x2, y2);
    double dx = a.x - b.x, dy = a.y - b.y;
    return Math.sqrt(dx*dx + dy*dy);
}
// after scalar replacement: no Point, no header, no zeroing, nothing for the GC
double distance(double x1, double y1, double x2, double y2) {
    double dx = x1 - x2, dy = y1 - y2;      // fields became locals
    return Math.sqrt(dx*dx + dy*dy);
}

The trace: the decision for each allocation.

call traceruns offline
new Point in distance()   all uses inlined, not stored, not returned   ✓ NoEscape -> scalar replaced
new Point passed to log() log() too big to inline                      ✗ ArgEscape -> allocated
cached = new Point(1, 2)  stored in a field                            ✗ GlobalEscape -> allocated

The fix: keep the object off the hot path.

Geometry.javaruns offline
double d = Math.hypot(x2 - x1, y2 - y1);                       // no object
if (d > LIMIT) log.warn("far apart: {}", new Point(x1, y1));  // ✅ FIX: allocation only on the cold branch
how to check rather than assumeruns offline
# Do not claim escape analysis happened. Verify it.
java -XX:+UnlockDiagnosticVMOptions -XX:+PrintEscapeAnalysis \
     -XX:+PrintEliminateAllocations -XX:+PrintInlining MyApp

# Or, far more practical: measure the allocation rate. If the allocation was
# genuinely eliminated, the rate drops. If it did not, it will not.
java -XX:+UnlockDiagnosticVMOptions MyApp   # then: jcmd <pid> GC.heap_info
# JMH: add -prof gc  ->  gc.alloc.rate.norm reports BYTES ALLOCATED PER OPERATION.
#   norm = 0 B/op  -> the allocation really was eliminated
#   norm = 32 B/op -> it was not, whatever the theory says

gc.alloc.rate.norm is the honest test. It reports bytes allocated per benchmark operation, so a claim that escape analysis removed an allocation becomes a number that is either zero or is not — which settles the argument in one run.

What you see: allocation per operation for the three variants.

JMH -prof gcruns offline
# illustrative output
Benchmark                                    Mode  Cnt    Score   Units
Geo.distance:gc.alloc.rate.norm              avgt   10   ≈ 10⁻⁵   B/op   <- eliminated
Geo.distanceLogged:gc.alloc.rate.norm        avgt   10     32.0   B/op   <- ❌ escaped through log()
Geo.distanceColdLog:gc.alloc.rate.norm       avgt   10   ≈ 10⁻⁵   B/op   <- ✅ fixed

Land it Escape analysis only removes an allocation whose whole life is visible in one compiled body, so the design question is always whether the hot path inlines, and the proof is a gc profile, not a belief.

Likely follow-ups
"Which flags print escape analysis decisions, and why can I not use them?"

The flags are -XX:+UnlockDiagnosticVMOptions -XX:+PrintEscapeAnalysis and -XX:+PrintEliminateAllocations, which print each allocation's escape state and each successful scalar replacement. The catch is that as of Aug 2026 they are compiled only into debug builds of HotSpot, so a product JDK rejects them; verify on your build, because vendors occasionally ship them. In practice I use a fastdebug build locally for the one method I care about, and on product builds I rely on -prof gc in JMH, where the gc.alloc.rate.norm line gives bytes per operation, and on -XX:+PrintCompilation plus -XX:+PrintInlining to confirm the callees were inlined, since without that inlining the analysis cannot succeed.

"Does escape analysis remove the lock on a non-escaping object as well?"

Yes. If an object is NoEscape, no other thread can ever reach it, so any synchronized on it is a no-op and C2 removes the monitor enter and exit entirely; this is lock elision, controlled by -XX:+EliminateLocks, which is on by default.

The classic example is a StringBuffer used as a local inside one method: each append is synchronized, but once the appends are inlined and the buffer is proved local, the locks vanish.

The same limits apply: if the buffer is passed to an un-inlined method, it escapes as ArgEscape, and the locks stay. This is one reason a hot method that leaks its temporary into a helper call can cost both an allocation and a lock.

Fmt.javaruns offline
String join(String a, String b) {
    StringBuffer sb = new StringBuffer();     // synchronized methods, but sb never leaves this method
    sb.append(a).append(b);                   // ✅ after inlining: NoEscape, locks elided
    return sb.toString();                     // ❌ passing sb to a non-inlined helper would keep the locks
}
"Give me a concrete case where a developer expects elimination and does not get it."

A method builds a Point record, then calls point.distanceTo(other), and the result is what matters. If distanceTo is inlined, the record is scalar-replaced. Now the developer adds logging: log.debug("computing {}", point).

Even when debug is off, the reference is passed to a method that is not inlined, so the object is ArgEscape and is allocated on every call.

Another case: a Point created in both arms of an if-else and used after the join; before JDK 22 that merge blocked replacement, and even now it depends on the shape.

A third: creating an Optional in a hot path and returning it, because a returned object escapes by definition unless the caller is also part of the compilation.

"Does this change with Valhalla value classes?"

It changes the guarantee. Today escape analysis is a best-effort optimisation that can silently fail.

A value class, from JEP 401 which is still in preview as of Aug 2026 so I would verify the current status, gives up identity, which means the JVM is always allowed to copy it, pass it in registers, or flatten it into an array, regardless of whether the compiler can see its whole life.

So a value Point passed to an un-inlined method can still be passed as two scalars, and an array of value Point can be laid out inline without headers.

Escape analysis remains useful for identity classes, but for the small immutable types where people most want allocation to be free, Valhalla is the mechanism that makes it a property of the type rather than a hope about the compiler.

Q28 · Design. "Design the hot path of a message-processing service that must handle 500,000 messages per second per core with a p99 under 200 microseconds. What do you do to keep the JIT on your side, and how do you prove it?"

Reveal answer

Strong answer Requirements: 500,000 messages per second per core leaves about 2 microseconds per message, so the inner loop cannot afford a megamorphic dispatch, an allocation per message, or any lock.

Assumptions: a fixed set of message types known at build time, and a single consumer thread per partition. Design: the loop is a small set of small, monomorphic methods.

The dispatch on message type is one switch over a sealed interface in the caller, so each branch calls a type-specific handler through a monomorphic call site rather than pushing every type through one Handler.handle(Message) interface call.

Each handler is kept under FreqInlineSize=325 bytes by moving error handling and rare branches into separate methods, so C2 inlines the whole path into the loop.

No streams or lambdas in the loop, because the apply and test call sites inside the stream classes are shared by the whole application and are megamorphic.

Fields are primitives where possible: a long timestamp, not an Instant; an int code, not an enum lookup through a map.

Parsing reads from a reused byte[] or a MemorySegment with an offset; the one short-lived object per message is a record whose whole life is inside the inlined path, so escape analysis removes it. Output is written into a preallocated buffer.

Proof, in order:

  1. JMH: a benchmark that cycles through the realistic mix of message types, with -prof gc showing gc.alloc.rate.norm at zero bytes per operation.
  2. Inlining: a run with -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining confirming every callee in the loop says inline (hot).
  3. JFR: a recording under production-shaped load where jdk.ObjectAllocationSample shows nothing from the loop and jdk.Deoptimization is quiet after warm-up.

Trade-offs: the code is more repetitive and less generic than a strategy-pattern design, and adding a message type means touching the switch.

What I would not do: build a plugin system with handlers loaded by reflection at runtime, because it makes every call site megamorphic and defeats class hierarchy analysis; use Object[] or boxed collections for message fields; or tune MaxInlineSize globally to rescue a design that is too large to inline.

Picture it the per-message time budget and the shape of the loop before and after the design.

The setup: the dispatch loop with a sealed message type and type-specific handlers.

HotLoop.javaruns offline
sealed interface Message permits Order, Cancel, Heartbeat {}

void run(Ring ring) {
    for (;;) {
        Message m = ring.next();
        switch (m) {                                   // ✅ dispatch in the caller: one monomorphic site per handler
            case Order o     -> handleOrder(o);        // each handler is small enough to inline (< 325 bytes)
            case Cancel c    -> handleCancel(c);
            case Heartbeat h -> { }
        }
    }
}
// ❌ TRAP (the design we avoid): handler.handle(m) through one shared interface -> megamorphic itable stub

Make the invisible visible: the budget, and the call sites.

time budget and call sitesruns offline
1 s / 500_000 messages = 2 us = 2000 ns per message, per core
one 48-byte object per message = 500_000 * 48 B = 24 MB/s of garbage            ✗
 before:  loop ─▶ Handler.handle(Message)  ─▶ itable stub ─▶ {Order, Cancel, Heartbeat, ...}   megamorphic
 after :  loop ─▶ handleOrder(o) | handleCancel(c) | inline heartbeat                          monomorphic, inlined

The trace: what each proof step should show.

call traceruns offline
JMH, mixed types, -prof gc          gc.alloc.rate.norm ≈ 0 B/op          ✓
PrintInlining on the loop           every callee inline (hot)            ✓
JFR under load                      no ObjectAllocationSample from loop  ✓   deoptimizations quiet ✓

What you see: inlining output for the loop before and after the redesign.

-XX:+PrintInliningruns offline
# illustrative output
before: @ 22  com.acme.Handler::handle (0 bytes)   virtual call
after : @ 22  com.acme.HotLoop::handleOrder (180 bytes)   inline (hot)
        @ 31  com.acme.HotLoop::handleCancel (96 bytes)   inline (hot)

Land it The JIT rewards code whose shape is visible and stable, so the design decision is to keep the inner loop small, monomorphic and allocation-free and to prove each of those three with a measurement rather than a code review.

Likely follow-ups
"Requirement change: message types are now loaded as plugins at runtime. What changes?"

The switch over a sealed type is gone, so I move the polymorphism to the edge of the loop and keep the loop itself monomorphic.

Each plugin registers a handler, and the consumer thread is dedicated to a partition that carries one message type, or a small number of them, so the call site in that thread's loop sees one or two receivers and stays bimorphic at worst.

BatchDispatch.javaruns offline
// ✅ FIX: group a batch by type, then one handler call per slice
for (var e : batch.groupByType().entrySet())
    handlers.get(e.getKey()).handleAll(e.getValue());    // the megamorphic call runs once per slice, not per message

If a partition must carry many types, I dispatch once per batch, not per message: group a batch by type, then call each handler with its slice, so the megamorphic call happens once per hundred messages.

I would also pre-warm every plugin's handler at registration with a synthetic batch so its profile and compiled code exist before real traffic, and watch jdk.Deoptimization after each plugin load because a new class can invalidate class hierarchy analysis in the existing code.

"What would you cut under time pressure?"

I would keep the monomorphic dispatch and the no-allocation loop, because those two are structural and expensive to retrofit. I would cut the full JMH type-mix benchmark to a single realistic-mix benchmark with -prof gc, because the allocation number is the one that catches most regressions.

I would cut the PrintInlining review and the primitive-field work, because those are one-time wins I can recover in a later sprint by profiling with async-profiler.

I would not cut the JFR check under production-shaped load, because that is the only step that proves the design in the environment that matters, and it costs an afternoon, not a week.

"How would you detect that a later change broke the design?"

With two gates in CI and one in production.

In CI, the JMH benchmark runs on every merge with a threshold: the allocation per operation must be zero and the throughput must be within 10 percent of the recorded baseline, which catches a new boxed field or a lambda in the loop.

In production, a JFR recording with the default profile runs continuously, and a dashboard shows two numbers per instance: the allocation rate, from the GC's jdk.GCHeapSummary and allocation sample events, and the count of jdk.Deoptimization events per minute.

A step change in either after a deploy is the alarm. I would also add an itable stub share to the async-profiler flame graph review on each release.

"Would virtual threads help here?"

No, and they might hurt. This loop is CPU-bound and per-core; virtual threads are for workloads that block on I/O and need many concurrent waiters, and they add a scheduling layer with its own continuation bookkeeping.

A dedicated platform thread per partition, pinned to a core if the operating system allows, gives the JIT a stable thread and a stable loop for on-stack replacement and profiling.

Where virtual threads make sense is the surrounding service: the HTTP admin endpoint, the outbound calls on the slow path, the health checks. The hot loop itself should be one platform thread, one partition, one monomorphic loop.

Q29. "What does an uncontended synchronized cost today, what happened to biased locking, and what is the lightweight locking mode?"

Reveal answer

Strong answer Uncontended means only one thread ever takes the lock, and for years that was made almost free by biased locking: the JVM marked the object as biased to the first thread, and that thread could re-enter without any atomic instruction.

JEP 374 disabled biased locking by default in JDK 15 and JDK 18 removed it, because its bookkeeping, especially bias revocation which required a safepoint, had become a source of latency spikes, and because modern CPUs made the atomic instruction it avoided much cheaper.

So today an uncontended synchronized costs a compare-and-swap on entry and another on exit, a compare-and-swap being an atomic instruction that costs roughly 20 to 50 cycles on current hardware, plus a memory fence.

That is a few tens of nanoseconds, small but not zero, which is why code that locks in an inner loop noticed the JDK 18 change.

C2 removes some of that cost on its own:

  • Lock elision: it deletes locks on objects that escape analysis proves are thread-local.
  • Lock coarsening: it merges a sequence of adjacent lock and unlock pairs on the same object into one, for example ten consecutive StringBuffer.append calls become one monitor enter and one exit.

The other change is how the lock itself is represented. The legacy scheme wrote a pointer to a stack-allocated lock record into the object's header, which meant every locked object's header was overwritten.

JDK 21 introduced -XX:LockingMode with a new lightweight mode that keeps a small per-thread lock stack instead, leaving the header mostly intact; as of Aug 2026 lightweight became the default in JDK 24 and the legacy mode has since been removed in later releases, which I would verify on the release notes for the exact JDK. Lightweight locking is also the prerequisite for compact object headers, since a 64-bit header has no room for a lock pointer.

Picture it what synchronized compiles to, and what the object header and thread look like under the two lock representations.

The setup: an uncontended counter.

Counter.javaruns offline
void inc() {
    synchronized (this) { count++; }      // one thread only: uncontended
}

Make the invisible visible: what javac generated.

javap -cruns offline
void inc();
  Code:
     0: aload_0
     1: dup
     2: astore_1
     3: monitorenter
     4: aload_0
     5: dup
     6: getfield      #7       // Field count:I
     9: iconst_1
    10: iadd
    11: putfield      #7
    14: aload_1
    15: monitorexit
    16: goto          24
    19: astore_2               // handler: also exits the monitor
    20: aload_1
    21: monitorexit
    22: aload_2
    23: athrow
    24: return
  Exception table:
     from    to  target type
         4    16    19   any
        19    22    19   any
object header and thread under the two modesruns offline
 legacy:       object header ─▶ pointer to a lock record in the thread's native stack frame (header overwritten)
 lightweight:  object header keeps its layout, marked "locked"; thread holds a small lock stack: [objA, objB, ...]

The trace: the cost of one pass.

call traceruns offline
monitorenter  -> compare-and-swap on entry                 ✓ atomic, no contention
count++       -> normal field update
monitorexit   -> compare-and-swap on exit                  ✓
C2 + NoEscape -> both removed (lock elision)               ✓ only when the object is provably thread-local

What you see: a small per-call cost that a plain method does not pay.

JMH outputruns offline
# illustrative output
Benchmark                 Mode  Cnt   Score   Units
Counter.incSynchronized   avgt   10   18.4    ns/op
Counter.incPlain          avgt   10    1.1    ns/op

Land it Uncontended locking is now a predictable few tens of nanoseconds rather than free-but-spiky, and the right response in a hot loop is to let C2 elide or coarsen it or to remove the lock from the design, not to look for a flag to bring the bias back.

Likely follow-ups
"Which code got slower when biased locking went away, and what did people do about it?"

Code that takes an uncontended lock millions of times per second from one thread: StringBuffer, Vector, Hashtable, Collections.synchronizedList, and old I/O streams like BufferedInputStream, whose read method is synchronized.

In JDK 15 to 17 you could re-enable it with -XX:+UseBiasedLocking, which prints a deprecation warning; from 18 that flag is gone.

consoleruns offline
# JDK 15 to 17, illustrative output
OpenJDK 64-Bit Server VM warning: Option UseBiasedLocking was deprecated in version 15.0 and will likely be removed in a future release.
# JDK 18 and later: the flag no longer enables anything

The real fixes were to replace those classes with their unsynchronized counterparts, StringBuilder, ArrayList, HashMap, and to keep the lock outside the loop so coarsening is not needed.

The JDK did the same in its own code, for example in JDK 19 and later several stream classes were rewritten to use an internal lock only when needed, partly for virtual-thread friendliness.

"How do you measure the lock cost in a real service rather than guessing?"

JFR has two events for it. jdk.JavaMonitorEnter records contended acquisitions over a threshold, default 20 milliseconds in the default profile and 10 in the profiling profile, so it shows contention, not uncontended cost.

For uncontended cost I use async-profiler in CPU mode and look for frames in the monitor enter and exit stubs, or JDK 25's jdk.CPUTimeSample from JEP 509 for a precise CPU attribution.

A JMH benchmark with and without the synchronized keyword on the hot method gives the per-call number, typically 20 to 40 nanoseconds.

If the difference under load is a few percent, I leave it alone; if the lock is in a loop taken millions of times per second, I redesign.

"What is the connection between lightweight locking and virtual threads?"

Before JDK 24, a virtual thread holding a monitor was pinned to its carrier thread, because the lock record lived on the carrier's native stack and the JVM could not unmount the virtual thread without losing it. JEP 491 in JDK 24 reworked monitor ownership so that a virtual thread owns the monitor itself and can be unmounted while blocked on it, and the lock-stack design of lightweight locking is part of what made that possible, because the state that has to move with the thread is small and explicit. The remaining pinning cases are native frames on the stack and class initialisation running in native code; the JFR event jdk.VirtualThreadPinned now records the reason.

"When is ReentrantLock faster than synchronized now?"

Rarely on the uncontended path; both are a compare-and-swap in and out, and synchronized has the advantage that C2 can elide or coarsen it while a ReentrantLock is opaque to the compiler.

ReentrantLock wins on features rather than speed: tryLock with a timeout, fairness, interruptible waiting, multiple Condition objects, and the ability to lock in one method and unlock in another. Under heavy contention the two behave similarly since both park the thread after a short spin.

My rule is synchronized by default for a simple critical section, ReentrantLock when I need one of those features, and StampedLock or a lock-free structure when the profile proves the lock is the bottleneck.

Q30. "What are intrinsics, when does C2 auto-vectorise a loop, and how would you find out whether it did?"

Reveal answer

Strong answer An intrinsic is a method whose Java body the JIT ignores in favour of hand-written machine code that the JVM engineers embedded in the compiler.

The JDK marks them with the internal annotation @IntrinsicCandidate, and the list is long: Math.sqrt, Math.fma, Integer.bitCount and numberOfLeadingZeros, System.arraycopy, String.indexOf, equals and compareTo, Arrays.equals and hashCode, CRC32.update, the AES and SHA primitives used by the crypto providers, and many Unsafe operations.

The benefit is that System.arraycopy becomes a vector copy loop and CRC32 becomes a hardware instruction, at speeds a Java loop cannot reach. The practical rule is to call the JDK method rather than reimplement it, because your copy of indexOf is not an intrinsic.

Auto-vectorisation is different: C2's SuperWord pass looks at a counted loop, meaning a loop with an int index, a constant stride, and a bound that does not change, and if the body does simple element-wise array operations with no calls, no data dependency between iterations, and no early exit, it rewrites groups of iterations into single SIMD instructions that process 8 or 16 elements at once.

A loop that sums an int[], copies with a transform, or compares two arrays qualifies; one that calls a method, throws, or writes an element read by the next iteration does not.

To see whether it happened:

  • Definitive: read the machine code. -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly needs the hsdis disassembler library on the JVM's library path, and JMH's -prof perfasm wraps that with hardware counters so the hot instructions are annotated. Vector instructions such as vpaddd on x86 or add v0.4s on ARM in the loop are the proof.
  • Cheap: time it with -XX:-UseSuperWord; if nothing changes, the loop was never vectorised.

The explicit alternative is the Vector API, which as of Aug 2026 is still incubating, tenth round in JDK 25 under JEP 508, because its final form waits on Valhalla value types.

Picture it the same loop as scalar and as SIMD instructions, and the checks C2 applies before it vectorises.

The setup: an element-wise add over two arrays.

Add.javaruns offline
void add(int[] a, int[] b, int[] c, int n) {
    for (int i = 0; i < n; i++) c[i] = a[i] + b[i];     // counted loop, no calls, no dependency between iterations
}

Make the invisible visible: one iteration versus eight, in illustrative x86 form.

what the compiler generatesruns offline
scalar  (1 element):  mov eax,[a+i*4] ; add eax,[b+i*4] ; mov [c+i*4],eax
SuperWord (8 ints):   vmovdqu ymm0,[a+i*4] ; vpaddd ymm0,ymm0,[b+i*4] ; vmovdqu [c+i*4],ymm0

The trace: the shape tests C2 applies.

call traceruns offline
int index, constant stride, fixed bound      ✓ counted loop
no call, no throw, no early exit             ✓
c[i] depends only on a[i], b[i]              ✓ no loop-carried dependency
-> pack iterations into vector ops; scalar pre/post loops handle alignment and the tail     ✓

What you see: a speed difference when SuperWord is switched off.

JMH outputruns offline
# illustrative output
Add.add (default)              avgt   10    0.21   us/op
Add.add (-XX:-UseSuperWord)    avgt   10    0.64   us/op    <- slower: the default build was vectorised

Land it Intrinsics are the JDK's hand-tuned fast paths and vectorisation is C2's automatic one, and both only apply to code shaped the way the compiler expects, so the check is always the generated assembly, not the source.

Likely follow-ups
"How do you verify an intrinsic is actually being used on your hardware?"

Two checks.

-XX:+UnlockDiagnosticVMOptions -XX:+PrintIntrinsics logs each intrinsic C2 applies, so I grep for the method, and -XX:+PrintFlagsFinal shows the hardware-dependent switches such as UseAES, UseCRC32Intrinsics, UseSHA256Intrinsics and UseFMA, which the JVM turns off when the CPU lacks the instruction or when it is running under a virtualised CPU model that hides the feature.

That last case is common: a cloud instance type that reports an old CPU flag set silently loses AES-NI, and TLS throughput drops several times.

For a controlled experiment, -XX:DisableIntrinsic=_arraycopy turns off one intrinsic by its internal id, and the difference in a JMH run shows what it was worth.

"Why did the loop not vectorise even though it looks simple?"

The common reasons, in order. The index is a long, so the loop is not a counted loop; change it to int. There is a conditional write inside the body, which needs masked stores that C2 only handles in some shapes.

The loop reads and writes overlapping ranges of the same array, so the compiler cannot prove independence. There is a call in the body, even a tiny one that did not inline. The arrays are of a type C2 cannot vectorise, such as Object[].

Or the loop runs too few iterations to justify the vector version, which has a scalar pre-loop and post-loop for alignment.

Add.javaruns offline
for (long i = 0; i < n; i++) c[(int) i] = a[(int) i] + b[(int) i];   // ❌ TRAP: long index, not a counted loop
for (int  i = 0; i < n; i++) c[i] = a[i] + b[i];                     // ✅ FIX: int index

JDK 23 and later have -XX:+UnlockDiagnosticVMOptions -XX:TraceAutoVectorization=SW_INFO, and older releases -XX:+TraceSuperWord on debug builds, which print why the pass rejected a loop; verify the exact tag names for your version.

"When would you reach for the Vector API despite it being incubating?"

When the loop cannot be written in the shape SuperWord accepts, for example a reduction with a lane shuffle, a lookup-table transformation, or a search that exits early with a mask, and the operation is on the measured critical path.

The API in jdk.incubator.vector compiles to the same SIMD instructions and falls back to scalar code on hardware without them, so correctness is portable even if speed is not.

The cost is that it requires --add-modules jdk.incubator.vector, prints an incubator warning at start-up, and its classes may change between releases, so I would isolate it behind one small interface with a scalar implementation next to it.

I would not use it for a loop that already vectorises automatically, because the automatic version needs no maintenance.

Drill · Deoptimisation, the code cache & JIT incidents

This group tests whether you can read what the JIT is doing from its logs and turn a "the service got slower" report into a compiler-level diagnosis.

Q31. "What is the code cache, how big is it, and what happens when it fills up?"

Reveal answer

The real test Whether you know that compiled code is a finite resource with its own failure mode, separate from the heap.

Strong answer The code cache is the native memory region where the JVM stores everything the just-in-time (JIT) compilers produce: the compiled versions of methods, plus the interpreter's own generated code, stubs and adapters.

With tiered compilation on, which is the default, it is reserved at 240 MB (-XX:ReservedCodeCacheSize=240m) and since JDK 9 it is segmented into three parts:

  • Non-method segment: the interpreter and stubs.
  • Profiled segment: tier-2 and tier-3 code, which is short-lived.
  • Non-profiled segment: tier-1 and tier-4 code, which is meant to stay.

Memory is committed as it is used, so a small service may touch only 30–60 MB. When it fills, the JVM prints CodeCache is full. Compiler has been disabled, stops compiling new methods, and runs anything not yet compiled in the interpreter, which is ten to fifty times slower.

A sweeper frees code for methods that were deoptimised or whose classes were unloaded, and -XX:+UseCodeCacheFlushing (on by default) lets it also evict cold compiled methods under pressure, but the eviction and recompilation churn is itself a slowdown.

The usual way a service fills the cache is class churn: generating a new class or lambda per request, heavy use of method handles that spin adapters, or a scripting engine compiling scripts repeatedly.

You watch it with jcmd <pid> Compiler.codecache, which prints used and free bytes per segment, and with the JFR event jdk.CodeCacheFull.

Picture it the three code-cache segments filling up, and the warning when the compiler stops.

The setup: a service that compiles a script on every request, producing new classes and new code each time.

ScriptHandler.javaruns offline
Object handle(String script) throws Exception {
    return engine.eval(script);        // ❌ TRAP: a fresh script class per call, so fresh compiled code per call
}

Make the invisible visible: the segments and their fill level.

code cache pictureruns offline
 ReservedCodeCacheSize = 240 MB
 [non-method      ][ 5 MB used ]  interpreter, stubs
 [profiled        ][██████████████ full ] tier 2/3 code, churns constantly
 [non-profiled    ][██████░░░░░░░░ part ] tier 1/4 code, long-lived

The trace: how the leak ends.

call traceruns offline
request N   new script class, compile at tier 3, code installed       ✓
request N+k  segment full, sweeper/flush cannot keep up               ✗
compiler disabled: new hot methods stay interpreted                    ✗ 10 to 50 times slower

What you see: the JVM warning and the segment report.

consoleruns offline
# illustrative output
OpenJDK 64-Bit Server VM warning: CodeCache is full. Compiler has been disabled.
OpenJDK 64-Bit Server VM warning: Try increasing the code cache size using -XX:ReservedCodeCacheSize=
$ jcmd 4242 Compiler.codecache
CodeHeap 'profiled nmethods': size=120000Kb used=119950Kb max_used=119950Kb free=50Kb
CodeHeap 'non-profiled nmethods': size=120000Kb used=41000Kb max_used=41200Kb free=79000Kb

Why: the cache is a fixed budget and per-request code generation spends it without end.

The fix: compile once and reuse.

ScriptHandler.java (fixed)runs offline
private final Map<String, CompiledScript> cache = new ConcurrentHashMap<>();
Object handle(String script) throws Exception {
    // ✅ FIX: one compilation per distinct script
    return cache.computeIfAbsent(script, this::compile).eval();
}

What you see now: a plateau after warm-up.

consoleruns offline
# illustrative output
CodeHeap 'profiled nmethods': size=120000Kb used=18000Kb max_used=21000Kb free=102000Kb    <- flat over days

Land it The code cache is a fixed budget for compiled code; when a service runs out, it silently falls back to interpreting, and the fix is usually to stop generating code rather than to raise the budget.

Likely follow-ups
"Should I just raise ReservedCodeCacheSize to 1 GB?"

Only after confirming the cache is genuinely needed at that size, because a bigger cache hides a class-generation leak instead of fixing it.

If Compiler.codecache shows steady growth over days rather than a plateau after warm-up, something is producing new code continuously and it will fill any size eventually.

A stable large application, such as a big Spring service with many endpoints, may legitimately need 300–500 MB, and raising the flag there is correct.

The cache is reserved virtual memory and committed lazily, so a higher reservation does not cost resident memory until it is used.

"How does a full code cache look different from a GC problem?"

The heap graph is normal and GC logs are quiet, but CPU is high and throughput is low, and a profiler shows a large share of samples in interpreted frames, which async-profiler marks with an _[i] suffix and JFR reports as interpreted. The JVM's warning line is in stdout or stderr, not in the GC log, so it is easy to miss; the JFR event jdk.CodeCacheFull and a jcmd Compiler.codecache reading near 100 percent confirm it in seconds.

"Why does the segmented layout matter?"

Because the profiled segment turns over constantly as tier-3 code is replaced by tier-4 code, and keeping it separate stops that churn from fragmenting the long-lived segment; it also lets the sweeper concentrate on the segment that produces garbage. The split is sized automatically from the total, and it is rarely tuned by hand; the important effect is that a full profiled segment can stall promotions to C2 even while the non-profiled segment has space, so read the per-segment numbers rather than the total.

Q32. "Here is a line from -XX:+PrintCompilation: 4512 871 % s! 3 com.acme.Parser::scan (212 bytes) made not entrant. Read it to me."

Reveal answer

Strong answer Read the line left to right, one column at a time:

  • Timestamp: 4512 is milliseconds since JVM start.
  • Compile id: 871 is a counter, so you can match this line with an earlier line for the same compilation.
  • Flags: % is an on-stack replacement (OSR) compile: the method was compiled while a loop in it was already running, and the compiled code was entered mid-loop. s means the method is synchronized. ! means it has exception handlers. Other flags you may see are b, a blocking compile where the calling thread waited, and n, a native method wrapper.
  • Tier: 3 is C1 with full profiling.
  • Method and size: 212 bytes of bytecode matters because it is over the 35-byte trivial inlining limit but under the 325-byte hot-method limit, so it can still be inlined into callers if it is hot.
  • What happened: made not entrant means this compiled version is retired. No new calls will enter it, and running frames will deoptimise at their next safepoint.

On its own that is normal, because it is how a tier-3 version is replaced by tier 4. The pattern to worry about is the same method being made not entrant repeatedly at tier 4, which means a speculation keeps failing.

Correlate the line with JFR's jdk.Compilation and jdk.Deoptimization events, which add the reason, such as unstable_if or class_check. For a full XML log that JITWatch can visualise, add -XX:+UnlockDiagnosticVMOptions -XX:+LogCompilation.

and the flags that tell you WHY it was invalidatedruns offline
# PrintCompilation says what; these say why.
java -XX:+UnlockDiagnosticVMOptions \
     -XX:+PrintCompilation \
     -XX:+TraceDeoptimization \
     -XX:+PrintInlining MyApp

# In practice, use JFR instead — it costs ~1% and works in production:
#   jdk.Deoptimization events carry the method, the bytecode index and the REASON
#   (unstable_if, class_check, null_check, bimorphic).
jcmd <pid> JFR.start name=deopt settings=profile duration=60s filename=d.jfr

A steady trickle of "made not entrant" is normal during warm-up and a problem in steady state. If it continues for hours, some call site is repeatedly changing shape — usually a new implementation class appearing — and the method is being recompiled forever instead of settling.

Picture it one method's compile lines in order, and which one is the warning sign.

The setup: a synchronized method with a hot loop and a try/catch, which is what produces the %, s and ! flags.

Parser.javaruns offline
class Parser {
    synchronized int scan(byte[] buf) {            // s = synchronized
        int hits = 0;
        try {                                      // ! = has an exception handler
            for (int i = 0; i < buf.length; i++) { // hot loop: OSR candidate (%)
                if (buf[i] == '\n') hits++;
            }
        } catch (RuntimeException e) { return -1; }
        return hits;
    }
}

Make the invisible visible: the same line, one column at a time, so every field has a meaning.

reading a PrintCompilation line, field by fieldruns offline
4512   871   %  s!  3   com.acme.Parser::scan (212 bytes)   made not entrant
 |      |    |  |   |            |               |                   |
 |      |    |  |   |            |               |                   +-- what happened
 |      |    |  |   |            |               +-- bytecode size
 |      |    |  |   |            +-- method
 |      |    |  |   +-- TIER: 3 = C1 with full profiling
 |      |    |  +-- ! = has an exception handler
 |      |    +-- s = synchronized method
 |      +-- % = ON-STACK REPLACEMENT: compiled while already running in a loop
 +-- milliseconds since JVM start

// The compile id (871) is unique; "made not entrant" on it means THIS compiled
// version was invalidated. New calls go back to the interpreter and recompile.

// OTHER MARKERS WORTH KNOWING:
//   n           native wrapper
//   made zombie the invalidated code is now unreachable and can be freed
//   COMPILE SKIPPED: too large / trivial

// WHAT THIS PARTICULAR LINE MEANS: an OSR compilation of a hot loop at tier 3
// was thrown away — almost always because a speculative assumption failed.
// A CLASS WAS LOADED that broke a monomorphic inline, or a branch the profile
// said was never taken was finally taken.

The trace: the life of one method in the log, from first compile to retirement.

lifecycle of Parser::scanruns offline
tier 0  interpreter runs scan()           counters start ticking
tier 3  C1 + full profiling   (id 871)    ✓ fast enough, collects branch/type profile
tier 4  C2 optimised          (id 903)    ✓ speculates on the profile
        871 is made not entrant           ✓ NORMAL: replaced by tier 4, frames drain
tier 4  903 made not entrant              ✗ speculation failed (unstable_if / class_check)
tier 0  back to the interpreter           ✗ slow until recompiled
tier 4  new id 957 compiled again         ✗ if this repeats for hours: deopt loop

What you see: the log lines for that history, and the one that should make you look closer.

consoleruns offline
# illustrative output
    311  871 %  s!  3       com.acme.Parser::scan @ 57 (212 bytes)
    498  903 %  s!  4       com.acme.Parser::scan @ 57 (212 bytes)
    512  871 %  s!  3       com.acme.Parser::scan @ 57 (212 bytes)   made not entrant   <- one-time promotion
  91203  903 %  s!  4       com.acme.Parser::scan @ 57 (212 bytes)   made not entrant   <- worry: tier 4 retired
  91260  957 %  s!  4       com.acme.Parser::scan @ 57 (212 bytes)
 182410  957 %  s!  4       com.acme.Parser::scan @ 57 (212 bytes)   made not entrant   <- and again

Why: a not-entrant line at tier 3 is a promotion, but the same method retired at tier 4 again and again means a profile assumption keeps being broken.

The fix: ask the VM why, then stabilise the branch or the receiver types that break the assumption.

find the reasonruns offline
jcmd <pid> JFR.start name=deopt settings=profile duration=60s filename=d.jfr
jfr print --events jdk.Deoptimization d.jfr | grep -E 'method|reason'
# ✅ FIX: the reason names the cause, e.g. unstable_if -> a rarely taken branch got taken

What you see now: a retirement count that stops growing once the cause is fixed.

consoleruns offline
# illustrative output
 182410  957 %  s!  4       com.acme.Parser::scan @ 57 (212 bytes)   made not entrant
 182461 1002 %  s!  4       com.acme.Parser::scan @ 57 (212 bytes)
        (no further "made not entrant" lines for 1002 for the rest of the run)

Land it Every column has a meaning, and the one that matters in an incident is whether "made not entrant" is a one-time promotion or a repeating loop.

Likely follow-ups
"What is 'made zombie' and how is it different?"

A not-entrant method may still have frames executing in it, so its code must stay in the cache until they are gone.

Once no activation remains, the sweeper marks it a zombie, which means the code is dead and its space can be reclaimed on the next sweep. So not entrant is "retired but possibly still running", zombie is "safe to free".

In JDK 21 and later the sweeper was reworked and the zombie state is mostly internal, but the log term still appears in older logs and in interviewers' questions.

code cache statesruns offline
in use  ->  not entrant  ->  (no activation left)  ->  zombie  ->  freed
        "retired, maybe still running"            "safe to free"
"How would you see the deoptimisation reason, not just the fact?"

Two ways. A JFR recording with jdk.Deoptimization enabled records, per event, the method, the bytecode index, the reason such as unstable_if, class_check, null_check or unloaded, and the action, such as reinterpret or make_not_entrant. Or run with -XX:+UnlockDiagnosticVMOptions -XX:+TraceDeoptimization on a diagnostic build, which prints the same to stdout. I would use JFR in production because it costs almost nothing and can be turned on with jcmd without a restart.

jfr printruns offline
# illustrative output
jdk.Deoptimization {
  compileId = 903
  method = com.acme.Parser.scan(byte[])
  bci = 112
  reason = "unstable_if"
  action = "reinterpret"
}
"Why does the bytecode size matter so much?"

Because inlining decisions are made on bytecode size, not on how fast the method is. A 212-byte method is only inlined into a caller when the call site is hot, and never into a caller that is already large after its own inlining.

A method that looks small in source can be big in bytecode if it uses string concatenation, boxing or lambdas, and that alone can stop it being inlined into a hot loop.

Splitting the rare path out into a separate method is the standard way to get the hot part under the threshold.

Q33. "Why is a freshly started JVM slow for the first minutes, what exactly is happening, and what shortens it as of 2026?"

Reveal answer

Strong answer Two different things are happening, and they need different fixes.

  • Startup: loading, verifying and linking thousands of classes, running static initialisers and framework reflection, and building the object graph the application needs before it can serve a request.
  • Warm-up: every method starts in the interpreter and gets profiled. C1 compiles it after a few hundred calls and C2 after a few thousand. Until that has happened for every hot path, the service runs many times slower than its steady state.

Warm-up is proportional to how much code the traffic touches, so a service with fifty endpoints may take minutes of real traffic before the last one is compiled.

What shortens startup:

  • CDS and AppCDS: map pre-parsed, pre-verified class metadata from an archive.
  • Leyden AOT cache, JDK 24 (JEP 483): also caches classes already loaded and linked.

What shortens warm-up:

  • JDK 25, JEP 515: adds the method profiles from a training run to that cache, so C1 and C2 can start compiling the right methods immediately instead of waiting for counters.
  • JDK 25, JEP 514: made it a one-step training run with -XX:AOTCacheOutput=app.aot.

Typical gains are startup cut by 40–60 percent and time-to-peak cut by a similar fraction.

What also works, more crudely:

  • Ramped traffic from the load balancer.
  • Synthetic warm-up requests before the health check reports ready.
  • -XX:TieredStopAtLevel=1 for services that never need C2's peak: it compiles everything with C1 quickly and stops.

Picture it one program timed in six rounds, so you can see the interpreter-to-C2 climb and what the AOT cache changes.

The setup: a loop that times the same method in six equal rounds, so the first rounds show warm-up.

Warm.javaruns offline
public class Warm {
    static double price(int qty) { return Math.sqrt(qty) * 1.07 + qty % 13; }

    public static void main(String[] a) {
        for (int round = 1; round <= 6; round++) {
            long t = System.nanoTime();
            double s = 0;
            for (int i = 0; i < 20_000_000; i++) s += price(i);   // same work every round
            System.out.printf("round %d: %d ms%n", round, (System.nanoTime() - t) / 1_000_000);
        }
    }
}

Make the invisible visible: where one method runs as its call count grows.

execution tiers of price()runs offline
calls so far:  0 ......... a few hundred ......... a few thousand ........>
runs in:       interpreter -> C1 tier 3 (+profiling) -> C2 tier 4 (optimised)
speed:         slowest        faster, but profiling   fastest, steady state
                              overhead

The trace: what the first minutes of a freshly started service look like.

startup then warm-upruns offline
t = 0 s      load, verify, link classes, run static init       ✗ not serving yet
t = 3 s      health check says ready, 100% of traffic arrives  ✗ hot endpoints still interpreted
t = 3-60 s   hot methods reach C1, then C2                     ✓ latency falls
t = 4 min    last rare endpoint compiled                       ✓ steady state

What you see: the same work getting faster round after round.

consoleruns offline
# illustrative output
round 1: 410 ms
round 2: 180 ms
round 3:  96 ms
round 4:  71 ms
round 5:  70 ms
round 6:  70 ms

Why: the early rounds ran in the interpreter and in profiled C1 code, and only later rounds ran C2 code.

The fix: record profiles in a training run and start production from the resulting AOT cache.

build pipelineruns offline
# build: run once with a representative workload, stop cleanly; cache written at exit
java -XX:AOTCacheOutput=app.aot -jar app.jar
# ✅ FIX: production start reads the cache
java -XX:AOTCache=app.aot -jar app.jar

What you see now: the same rounds, with the first ones much closer to steady state.

consoleruns offline
# illustrative output
round 1: 150 ms
round 2:  85 ms
round 3:  71 ms
round 4:  70 ms
round 5:  70 ms
round 6:  70 ms

Land it Startup and warm-up are different problems; the AOT cache attacks both, and the honest operational fix is not to send full traffic to a JVM that has not finished compiling.

Likely follow-ups
"How do you produce and use the AOT cache in a container pipeline?"

In the build pipeline, run the application once against a representative workload with java -XX:AOTCacheOutput=app.aot -jar app.jar, drive the training traffic, and stop it cleanly; the cache is written at exit. Copy app.aot into the image next to the jar and start production with -XX:AOTCache=app.aot.

The cache is tied to the exact JDK build, the classpath and the main flags, so it must be rebuilt per release and the JVM silently ignores a mismatched cache, which is why I would log the -Xlog:aot line at startup to confirm it loaded. As of JDK 26 it works with every collector, including ZGC.

pipeline commandsruns offline
# 1. train (build stage)      java -XX:AOTCacheOutput=app.aot -jar app.jar
# 2. ship app.aot next to the jar
# 3. run (production)         java -XX:AOTCache=app.aot -jar app.jar
# ✅ FIX if the cache does not load: rebuild it with the exact JDK, classpath and flags
"What does TieredStopAtLevel=1 cost you?"

It gives up C2 entirely, so no escape analysis, no aggressive inlining, no loop optimisations, and no profile-driven speculation; steady-state throughput is typically 20–50 percent lower on compute-heavy code and close to the same on code dominated by I/O and framework overhead. It also removes the profiling work from tier 3, so the JVM uses less CPU during warm-up. It is a reasonable choice for short-lived jobs, command-line tools and test suites, and the wrong one for a long-running service that needs peak throughput.

TieredStopAtLevel=1runs offline
default tiered:         interpreter -> C1 (profiling) -> C2          fast peak, slower warm-up
-XX:TieredStopAtLevel=1: interpreter -> C1 (no profiling), stop       quick, lower peak (typically 20-50% on compute-heavy code)
"How do you measure time-to-peak so you can prove an improvement?"

Record a JFR file from launch with -XX:StartFlightRecording and plot two things against time: the count of jdk.Compilation events per second, which falls to near zero when warm-up is done, and the p50 latency of a fixed synthetic request. Time-to-peak is when both flatten. Compare that curve before and after the change on the same hardware with the same traffic replay; a single "it feels faster" is not evidence.

time-to-peak curveruns offline
# illustrative output
minute   jdk.Compilation/s   p50 latency
0-1      420                 180 ms
1-3       35                  60 ms
3-5        2                  21 ms    <- both curves flat: time-to-peak = minute 3
5-10       0                  21 ms

Q34 · Design. "Our compute-heavy pricing service runs on JDK 21 with C2. A team wants to move it to GraalVM's JIT compiler. Design the evaluation: what would it buy, what would it cost, and how would you decide?"

Reveal answer

Strong answer Assumptions: the service is CPU-bound and long-running, and its hot paths use streams, lambdas and small immutable objects heavily. That is where the Graal compiler differs most from C2.

Background for the room:

  • JVMCI (JEP 243): the JVM Compiler Interface lets a compiler written in Java plug in as the tier-4 compiler.
  • Availability: the Graal compiler was an experimental option inside OpenJDK until JDK 17, when it was removed from the standard builds. It now ships in GraalVM, where -XX:+UseJVMCICompiler selects it in place of C2.

What it buys:

  • Partial escape analysis: eliminates allocations that C2 gives up on because the object escapes on one branch.
  • Inlining: more aggressive across lambda and stream plumbing.
  • Result: generally better code on allocation-heavy functional code, often 5–15 percent more throughput, sometimes more.

What it costs:

  • Warm-up: longer, because the compiler itself is Java code that has to warm up too, unless the vendor's build precompiles it (libgraal does).
  • Memory: more during compilation.
  • Vendor: a different vendor and support contract.
  • People: a smaller pool who can read its diagnostics.

Evaluation design:

  • Setup: one canary pair on identical hardware, same JDK major, same flags apart from the compiler.
  • Load: a traffic replay of at least an hour.
  • Compare: peak throughput, p99, CPU per request, time-to-peak, and RSS from JFR on both.
  • Then: a week of production canary at 5 percent.

Decision rule agreed up front: adopt only if peak throughput improves by more than 10 percent with no p99 regression and warm-up within the deployment budget.

What I would not do: benchmark with JMH microbenchmarks alone, because the compilers differ most on real call-site shapes, or change the compiler and the JDK version in the same experiment.

Picture it the escape-analysis difference that might pay for the swap, and the result table the decision is made from.

The setup: a pricing function whose temporary object escapes on one rare branch only.

Pricer.javaruns offline
double price(Order o) {
    Quote q = new Quote(o.px(), o.qty());   // allocated on every call?
    if (o.isRare()) {                       // taken ~0.1% of the time
        audit(q);                           // q escapes here, and only here
    }
    return q.px() * q.qty();
}

Make the invisible visible: what each compiler effectively keeps, written as Java.

what each compiler effectively runsruns offline
// C2: the object escapes on one branch, so it gives up and allocates every time
double price(Order o) {
    Quote q = new Quote(o.px(), o.qty());       // ❌ allocation on 100% of calls
    if (o.isRare()) audit(q);
    return q.px() * q.qty();
}

// Graal, partial escape analysis: allocate only where it escapes
double price(Order o) {
    if (o.isRare()) audit(new Quote(o.px(), o.qty()));   // ✅ allocation on ~0.1%
    return o.px() * o.qty();
}

The trace: the evaluation as a decision with the threshold fixed in advance.

decision traceruns offline
1. same hardware, same JDK major, flags differ only in the compiler     ✓ valid experiment
2. replay >= 1 hour, record JFR on both nodes                           ✓ production-shaped
3. peak throughput gain > 10 percent?                                   ✓ / ✗
4. p99 not worse, warm-up inside the budget?                            ✓ / ✗
5. all ✓ -> 5% canary for a week; any ✗ -> stay on C2

What you see: the numbers the decision rule is applied to.

consoleruns offline
# illustrative output
metric              C2        Graal     verdict
peak throughput     100 %     112 %     ✓ over the 10 percent bar
p99 latency         41 ms     39 ms     ✓ no regression
CPU per request     100 %      91 %     ✓
time-to-peak        6 min     9 min     ✗ over the 8 minute budget
RSS                 3.1 GB    3.4 GB    note

Why: the rule has several conditions, so a big throughput win can still fail on warm-up, and the pre-agreed threshold turns that into a decision rather than an argument.

Land it A compiler swap is a vendor decision as much as a performance one, so the evaluation must measure the whole curve, warm-up included, on production-shaped traffic with a pre-agreed threshold.

Likely follow-ups
"The requirement changes: the service is now mostly I/O-bound. Does the answer change?"

Yes, it becomes "do not bother". The compiler only affects the fraction of time spent executing Java code, and in an I/O-bound service that fraction is small; a 10 percent better compiler on 20 percent of the time is a 2 percent gain, inside measurement noise. The money is better spent on the thread model, the connection pool and the serialisation format. I would run the same JFR comparison anyway to have the number, but I would predict a null result and say so.

the arithmeticruns offline
# illustrative output
time in Java code            20 %
compiler improvement         10 %
whole-service gain           20 % x 10 % = 2 %     (inside measurement noise)
"What would you cut under time pressure?"

The week-long production canary, replaced by a two-hour replay on the canary pair, and the RSS and warm-up measurements, keeping only peak throughput and p99. I would not cut the identical-hardware requirement or the pre-agreed threshold, because without those the experiment cannot produce a decision, only an argument.

"Would native image be a better fit than the Graal JIT here?"

No, for a long-running compute service it is usually worse. Native image compiles ahead of time with a closed world and no runtime profile, so its peak throughput is typically below C2 unless you use profile-guided optimisation in the commercial build, and it cannot adapt to traffic shifts. Native image wins on startup and footprint, which this service does not care about. The Graal JIT keeps the adaptive runtime and only changes the optimiser, which is the right axis for a throughput question.

Q35 · Scenario. "We upgraded a service from JDK 17 to JDK 25 last night. CPU is at 100 percent and throughput dropped 30 percent. Nothing in the application changed. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: more CPU for less work, which means each request costs more cycles. That points at the runtime, not at a dependency being slow, because a slow dependency lowers CPU.
  2. Evidence, in the first ten minutes:
    • A 60-second JFR recording with the profile settings, or an async-profiler CPU flame graph.
    • jcmd <pid> VM.flags -all diffed against the old JDK's flags, to see which defaults changed.
    • The compiler and GC lines of -Xlog:gc*,safepoint if enabled.
    • jcmd Compiler.codecache.
  3. Ranked causes:
    1. Deoptimisation storm: the new C2 speculates differently and a hot method keeps being made not entrant. It is visible as bursts of jdk.Deoptimization events and interpreted frames in the flame graph.
    2. A changed default that adds work: the locking mode changed (biased locking is gone since 18, lightweight locking is default since 24), which makes uncontended synchronized a little more expensive and heavily-synchronised legacy code noticeably so. Or the GC default changed, for example a small container going from Serial to G1, whose concurrent threads burn CPU.
    3. An intrinsic or library change: a method that was an intrinsic on 17, or a String or HashMap implementation detail your hot path leaned on, behaves differently.
    4. A compiler bug on the new release: rare but real.
  4. Fix, by cause:
    • Deopt storm: find the method and stabilise the branch or type, or exclude it from C2 with -XX:CompileCommand=exclude,com.acme.Foo::bar as a stopgap.
    • Changed default: set the old value explicitly while the code is fixed.
    • Suspected compiler bug: bisect with CompileCommand until the guilty method is isolated, and file it with the reproducer.
  5. Prevention: a canary at 5 percent with a JFR comparison before the fleet moves, and a flags diff as a checklist item in every JDK upgrade.

Picture it the flags diff that shows what a JDK upgrade changed behind your back, and the order in which the causes are ruled out.

The setup: capture the effective flags on both JDKs, so you can diff what the upgrade silently changed.

capture and diffruns offline
# on the JDK 17 canary
jcmd <pid> VM.flags -all | sort > flags-17.txt
# on the JDK 25 canary
jcmd <pid> VM.flags -all | sort > flags-25.txt
diff flags-17.txt flags-25.txt

What you see: a flags diff where the same container gets a different collector and different thread counts.

flags diffruns offline
# illustrative output
< bool UseSerialGC                 = true    {product} {ergonomic}
> bool UseSerialGC                 = false   {product} {default}
< bool UseG1GC                     = false   {product} {default}
> bool UseG1GC                     = true    {product} {ergonomic}
> uint ConcGCThreads               = 1       {product} {ergonomic}

The trace: the ranked causes tested one by one.

diagnosis traceruns offline
1. flame graph: mostly interpreted frames, bursts of Deoptimization?   ✗ deopt storm -> stabilise or exclude method
2. flags diff: GC or locking default changed?                          ✗ changed -> pin the old value, retest
3. JVM threads (GC, C2 compiler) high in a CPU profile?                ✗ size ConcGCThreads / CICompilerCount to the quota
4. none of the above, one method slow only on 25?                      ✗ bisect with CompileCommand, file a bug
5. canary now matches the old throughput                               ✓

Why: a JDK upgrade replaces the compiler, the collector defaults and the locking implementation at once, so "nothing changed" is only true of your source code.

The fix: pin the old value explicitly while you fix the real cause.

startup flagsruns offline
# ✅ FIX: pin the collector while you investigate, size VM threads to the CPU quota
java -XX:+UseSerialGC -XX:CICompilerCount=2 -jar app.jar

What you see now: the same diff after the fix has no unexpected lines, and the service is back on the old throughput.

flags diffruns offline
# illustrative output
(diff of the explicitly pinned flags only: UseSerialGC, CICompilerCount; nothing unplanned)

Land it "Nothing changed" is false; the compiler, the collector and the locking defaults all changed, and a flame graph plus a flags diff tells you which one within ten minutes.

Likely follow-ups
"The flame graph shows nothing unusual and there are no deopt events. What next?"

Then the extra CPU is not in Java frames, and I look at the JVM's own threads: GC worker threads and JIT compiler threads show up in a CPU-mode async-profiler run under their own names. A container whose CPU quota was set for Serial GC and now runs G1's concurrent refinement and marking threads, or a JIT that is recompiling the world because the AOT or CDS archive from the old JDK no longer matches, would look exactly like this. -Xlog:gc* and jdk.Compilation event rates settle it; the fix is -XX:ConcGCThreads and -XX:CICompilerCount sized to the quota, or a rebuilt archive.

CPU by thread groupruns offline
# illustrative output
java frames (app threads)     52 %
C2 CompilerThread0..3         23 %    <- recompiling: rebuild the archive / size CICompilerCount
G1 Conc#0..2, G1 Refine#0     21 %    <- concurrent GC burning the quota
other                          4 %
"How would you tell a deopt storm from ordinary warm-up?"

Warm-up produces a burst of compilations that decays to near zero within minutes and never returns; a storm produces "made not entrant" and recompiles for the same handful of methods indefinitely, and the rate does not decay. JFR's jdk.Deoptimization view grouped by method makes it obvious: warm-up is a wide spread of methods once each, a storm is one or two methods hundreds of times.

"Would you roll back first?"

If the service is user-facing and the drop is costing money, yes, roll back immediately and investigate on a canary that still runs the new JDK with a copy of traffic. Rolling back does not destroy evidence as long as the canary exists, and it takes minutes. What I would not do is leave the fleet degraded while the investigation runs, because the diagnosis can be done on one instance.

Q36 · Scenario. "Every few seconds our latency spikes by 50 ms, and a JFR recording shows jdk.Deoptimization events arriving in bursts for the same two methods. What is going on and how do you stop it?"

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: periodic spikes with deoptimisation bursts for a fixed set of methods. That is a deoptimisation storm: C2 keeps making a speculation that keeps failing, throws the compiled code away, runs interpreted while it re-profiles, and compiles again.
  2. Evidence: the jdk.Deoptimization events carry a reason and a bytecode index.
    • unstable_if: a branch the profile said was never taken is now taken.
    • class_check or bimorphic: a type the profile had never seen showed up.
    • unloaded or null_check: rarer.
    • -XX:+PrintCompilation confirms the same method id being made not entrant over and over.
  3. Ranked causes:
    • Bimodal branch: a flag such as "is this a bulk request" that is false for ten thousand calls and then true for a hundred, so each mode looks rare to the other's profile.
    • Type-profile pollution: a shared helper called with one type from the hot path and another from a rare path, or dynamic proxies and generated classes introducing new types periodically.
    • Late class loading: for example a plugin, invalidating class-hierarchy-based devirtualisation each time it loads a fresh class.
  4. Fix, by cause:
    • Bimodal branch: split the two modes into two methods so each has a stable profile, or decide the branch once outside the hot loop.
    • Pollution: duplicate the helper per call site.
    • Late class loading: load the classes at startup or stop regenerating them.
    • Stopgap: -XX:CompileCommand=dontinline or exclude for the method stabilises latency at a lower throughput.
    • HotSpot also self-limits: after -XX:PerMethodTrapLimit=100 traps in a method and -XX:PerBytecodeTrapLimit=4 at one bytecode, C2 stops speculating there and compiles the slower general path. The storm ends by itself but leaves permanently slower code.
  5. Prevention: a JFR alert on the jdk.Deoptimization rate after warm-up, and a rule that hot-path helpers do not get reused from rare paths.

Picture it the profile that makes C2 speculate, and the failure cycle that repeats every few seconds.

The setup: a method with a bimodal branch: single requests almost always, bulk requests in short bursts.

Handler.javaruns offline
long handle(Request r) {
    if (r.isBulk()) {          // ❌ TRAP: false 10,000 times, then true 100 times, repeating
        return bulk(r);
    }
    return single(r);
}

Make the invisible visible: what the profile tells C2 while only single requests have arrived.

branch profile and compiled coderuns offline
profile of r.isBulk():   taken 0   not taken 10,000
C2 compiles:            if (r.isBulk()) -> uncommon trap     (the branch is "never" taken)
                        return single(r);                    (straight-line, fast)
first bulk request ->   trap fires -> deoptimise -> interpreter

The trace: the loop that produces the latency spike every few seconds.

storm cycleruns offline
1. 10,000 single requests, C2 code speculates "never bulk"        ✓ fast
2. 100 bulk requests arrive, uncommon trap hits                   ✗ deoptimise, method made not entrant
3. interpreter re-profiles for hundreds of calls                  ✗ tens of times slower
4. C2 compiles again with a speculation                           ✗ ~ tens of ms of compiler time
5. back to step 1                                                 ✗ repeat until the trap limits stop it

What you see: bursts of the same reason for the same method.

jfr printruns offline
# illustrative output
jdk.Deoptimization { method = com.acme.Handler.handle(Request)  bci = 8  reason = "unstable_if"  action = "reinterpret" }
jdk.Deoptimization { method = com.acme.Handler.handle(Request)  bci = 8  reason = "unstable_if"  action = "reinterpret" }
    ... same two methods, every few seconds ...

Why: each mode looks rare to the profile built during the other mode, so the compiler keeps learning the wrong lesson.

The fix: give each mode its own method, so each has a stable profile.

Handler.javaruns offline
long handle(Request r) {
    return r.isBulk() ? handleBulk(r) : handleSingle(r);   // ✅ FIX: decide once, each target has a stable profile
}

What you see now: no repeated events for these methods after warm-up.

jfr printruns offline
# illustrative output
(no jdk.Deoptimization events for Handler.handle, handleBulk or handleSingle after minute 3)

Land it A storm is the compiler learning the wrong lesson repeatedly; the fix is to give it one lesson per call site, not to disable the compiler.

Likely follow-ups
"You split the method and the storm continued. What next?"

Then the unstable thing is not the branch but the types reaching the split methods, so I check the reason field again: if it is now class_check, some call site inside still sees a rotating set of receiver types.

I would look at what creates those types; a framework that generates a new proxy class per request, or lambdas created in a loop that capture different values and therefore compile to different hidden classes, are the usual culprits.

The proof is -Xlog:class+load showing new class names after warm-up. Fix the generator, and the profile becomes stable.

class load logruns offline
# illustrative output
[183.512s][info][class,load] com.acme.$Proxy412 source: __JVM_DefineClass__
[183.730s][info][class,load] com.acme.$Proxy413 source: __JVM_DefineClass__
# ❌ TRAP: new class names well after warm-up = a generator feeding the call site new receiver types
"Why does the JVM not just remember the failed speculation forever?"

It does, up to a point, through the trap limits: the method's profile records each trap, and once the per-bytecode limit of four is hit C2 compiles that site without the speculation. The reason it does not do that on the first failure is that many speculations fail exactly once, for instance during a rare error path, and giving up immediately would cost real throughput on every method that ever saw an exception. The trade-off is a few recompilations before the compiler settles.

"How much does one deoptimisation actually cost?"

The deoptimisation itself is microseconds: the compiled frame is rewritten into interpreter frames at a safepoint. The expensive part is what follows: the method runs interpreted, tens of times slower, for the hundreds or thousands of calls needed to re-profile, and then a C2 compile of a large method can take tens of milliseconds of compiler-thread time. For a method on every request, that is a latency bump of tens of milliseconds and a CPU bump on the compiler thread, every time it happens.

cost of one deoptimisationruns offline
# illustrative output
deoptimise (rewrite frame)           ~ microseconds
interpreted re-profile, 1,000 calls  ~ 20x slower, for as long as it takes
C2 recompile of a large method       ~ tens of ms on the compiler thread
-> latency bump on every request that hits the method, every time

Q37 · Scenario. "A service gets slower every day it runs; after three days it is at half throughput and a restart fixes it. The heap is fine. jcmd Compiler.codecache shows 99 percent used. Diagnose."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: gradual slowdown with a full code cache and a healthy heap. Compiled code is being evicted or never produced, so more and more of the service runs in the interpreter.
  2. Evidence:
    • jcmd <pid> Compiler.codecache per segment, showing the non-profiled segment full.
    • The stdout warning CodeCache is full. Compiler has been disabled, or the JFR event jdk.CodeCacheFull.
    • A flame graph with a growing share of interpreted frames.
    • -Xlog:class+load or jcmd GC.class_histogram showing the class count still rising after warm-up.
  3. Ranked causes:
    • Class churn: something generates a new class per request or per job, such as a serialisation library building a new accessor class per type it meets, a scripting engine compiling expressions on every call, or reflection code spinning method-handle adapters in a hot path. Each new class brings new methods to compile.
    • A large application: it simply needs more than 240 MB and hits the ceiling after the last rarely-used endpoint warms up.
    • Flushing: cache flushing disabled or a sweeper unable to keep up, so retired code is never freed.
  4. Fix, by cause:
    • Churn: find the generator (a heap histogram sorted by class name shows thousands of $$Lambda, GeneratedMethodAccessor or script classes) and cache its output, so a script is compiled once and a method handle is created once.
    • Genuinely large application: raise -XX:ReservedCodeCacheSize=512m.
    • Make sure -XX:+UseCodeCacheFlushing is on, which it is by default.
  5. Prevention: alert on code-cache usage above 80 percent and on class count growth after warm-up; both are available through JMX and JFR.

Picture it how a per-request class generator fills the code cache, with before and after numbers.

The setup: a request handler that compiles a user script on every call, so every request defines new classes.

ReportService.javaruns offline
Object run(String script, Binding b) {
    GroovyShell shell = new GroovyShell(b);
    return shell.evaluate(script);          // ❌ TRAP: compiles the script into new classes on EVERY call
}

Make the invisible visible: the class count and the code cache growing together, day after day.

growth over three daysruns offline
# illustrative output
                 day 0     day 1     day 2     day 3
loaded classes   18,400    61,000    104,000   147,000
code cache used  22 %      61 %      93 %      99 %
throughput       100 %     90 %      70 %      50 %

The trace: how a full cache turns into a slow service.

code cache fillsruns offline
1. every request defines new classes -> each needs methods compiled     ✗ code cache grows
2. segment reaches its limit                                           ✗ "CodeCache is full" warning
3. compiler stops compiling new methods                                ✗ hot paths stay interpreted
4. throughput halves, heap still fine                                  ✗ restart "fixes" it

What you see: the code cache segment output and the warning.

jcmd Compiler.codecacheruns offline
# illustrative output
CodeHeap 'non-profiled nmethods': size=120032Kb used=119871Kb max_used=119871Kb free=161Kb
CodeHeap 'profiled nmethods':     size=120028Kb used=118940Kb max_used=119002Kb free=1088Kb
CodeCache is full. Compiler has been disabled.

Why: every generated class brings methods that need compiled code, so the cache fills until the compiler stops.

The fix: compile once and reuse.

ReportService.javaruns offline
private final Map<String, Class<?>> cache = new ConcurrentHashMap<>();

Object run(String script, Binding b) {
    Class<?> c = cache.computeIfAbsent(script, src -> new GroovyClassLoader().parseClass(src)); // ✅ FIX: once per script
    return InvokerHelper.createScript(c, b).run();        // a cheap new Script instance per call
}

What you see now: class count and code cache flat after warm-up.

growth over three daysruns offline
# illustrative output
                 day 0     day 1     day 2     day 3
loaded classes   18,900    19,200    19,200    19,200
code cache used  22 %      27 %      27 %      27 %
throughput       100 %     100 %     100 %     100 %

Land it A slowly filling code cache is almost always a class leak in disguise; raising the cache size buys days, caching the generated classes buys forever.

Likely follow-ups
"You raised the cache to 512 MB and it still fills in a week. Now what?"

That confirms churn rather than size, and I go back to the histogram. I take two jcmd GC.class_histogram snapshots an hour apart and diff the class names; the ones that appear only in the second snapshot are being generated at runtime.

Their names usually give away the producer: jdk.internal.reflect.GeneratedMethodAccessor means reflection inflation, which JDK 18 and later avoid, LambdaForm$MH means method-handle adapters being built repeatedly, and library-specific prefixes name the framework.

Then I make that producer cache its classes, and confirm with the same diff showing zero new classes.

histogram diffruns offline
# illustrative output
jcmd <pid> GC.class_histogram > h1.txt ; (one hour later) > h2.txt
only in h2.txt:
  Script1712.. Script1713.. Script1714..          <- thousands of generated script classes
  jdk.internal.reflect.GeneratedMethodAccessor...  <- reflection accessors
after the fix: no new class names in h2.txt
"Is metaspace also growing? Why would that matter?"

Almost certainly yes, because every generated class also stores its metadata in metaspace, so the two grow together. That matters because it gives a second, easier alarm: metaspace use is a standard JMX metric most dashboards already chart, whereas code-cache use often is not. It also means the eventual failure could be a Metaspace out-of-memory error rather than a slowdown, depending on which limit is hit first, and the fix is the same.

"Could virtual threads or lambdas cause this?"

Lambdas as normally written do not: a lambda expression compiles to one hidden class per expression site, created once. The problem is code that creates lambdas through LambdaMetafactory or method handles dynamically, per input, or a scripting layer that compiles per call. Virtual threads themselves generate no classes; the continuation machinery is fixed code in the JDK.

Q38 · Scenario. "Every new instance we roll out is five times slower than the rest for about four minutes, fails its latency-based health check, gets killed, and the next one repeats it. Deploys take hours. What is happening and how do you fix it?"

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: a new instance is slow for a fixed period and then would be fine, but a health check that measures latency kills it before it gets there. That is warm-up interacting badly with the rollout policy, not a code fault.
  2. Evidence:
    • A JFR recording from launch shows jdk.Compilation events at a high rate for about four minutes and then tapering.
    • A flame graph in the first minute is dominated by interpreted frames.
    • The instance's latency curve is the classic warm-up decay.
    • The health-check configuration confirms it kills on p99 above a threshold from the first minute.
  3. Causes, ranked:
    • The instance receives full traffic share immediately, so every hot path warms under load and the queue builds.
    • The health check has no warm-up grace.
    • The service touches many code paths, so warm-up is long.
  4. Fix, in layers:
    • Immediately, change the health check: readiness should mean "can serve", and latency-based liveness should have a grace period of at least the measured warm-up, or should use a rolling window that ignores the first minutes.
    • Next, ramp traffic: most load balancers support slow-start, sending a new instance 5 percent of its share and increasing over a few minutes.
    • Then shorten warm-up: a JDK 25 AOT cache with method profiles (-XX:AOTCacheOutput in a training run, -XX:AOTCache in production) typically halves it.
    • A warm-up phase before readiness that replays a few hundred representative requests internally does the rest.
  5. Prevention: measure time-to-peak with JFR as a release metric, and treat a rise as a regression.

Picture it one new instance under the current policy, minute by minute, and the policy after the fix.

The setup: the rollout as it runs today: full traffic on arrival and a latency probe that fires from the first minute.

rollout policy todayruns offline
traffic share on arrival : 100 % of a normal share           # ❌ TRAP: cold JVM gets full load
probe                    : kill if p99 > 200 ms              # ❌ TRAP: no grace period
cold-instance p99        : about 5x steady state for ~4 min

The trace: what happens to one new instance, minute by minute.

instance timelineruns offline
min 0   starts, receives full share, p99 1000 ms       ✗ probe fails
min 1   queue builds, p99 still 900 ms                 ✗ probe fails again -> killed
        replacement starts: min 0 again                ✗ same loop
min 4   (never reached) p99 would be 200 ms            ✓ it would have been fine

What you see: the same instance judged by the probe, over time.

probe logruns offline
# illustrative output
t=30s   p99=1040ms  threshold=200ms  FAIL
t=60s   p99= 910ms  threshold=200ms  FAIL   -> instance killed
(a surviving instance would show: t=240s p99=190ms  PASS)

Why: the probe treats a warming JVM as a broken one.

The fix: ready only when warm, ramp the traffic, and give the latency probe a grace period.

rollout policy fixedruns offline
readiness      : ready after internal warm-up replay (~30 s)       # ✅ FIX
slow-start     : 5 % of share, ramp to 100 % over 3 min             # ✅ FIX
latency probe  : ignore first 5 min, then kill if p99 > 200 ms      # ✅ FIX
jvm            : -XX:AOTCache=app.aot                               # ✅ FIX: shorter warm-up

What you see now: the instance passes the probe and the deploy finishes in minutes.

probe logruns offline
# illustrative output
t=30s   ready after warm-up, share 5 %
t=180s  share 100 %  p99=95ms  threshold=200ms  PASS

Land it A JVM that has not compiled its hot paths is not ready, so readiness, traffic ramping and the AOT cache are the three fixes, in that order.

Likely follow-ups
"You added a warm-up phase and it is still slow for two minutes. What next?"

Then the warm-up requests are not touching the paths production touches, or they are warming with the wrong types and the real traffic causes deoptimisation.

I compare the JFR compilation list from the warm-up phase against the first two minutes of production traffic and look at which methods are compiled only in the latter; those are the paths the warm-up misses.

I also check jdk.Deoptimization events in the first minutes, which would show warm-up having trained a profile that production invalidates, for example warming with one tenant's data shape. The fix is to replay recorded real requests, not hand-written ones.

which paths the warm-up missedruns offline
# illustrative output
compiled in first 2 min of production : A B C D E F G
compiled during warm-up phase         : A B C D
only in production                    : E F G    <- paths the warm-up replay never touched
"Why not just start every instance with -Xcomp?"

-Xcomp compiles every method on first call, with no profile, so the code C2 produces is generic and often slower than what it would produce after profiling, and startup becomes much longer because everything, including code that runs once, is compiled. It is a debugging flag, not a warm-up strategy. The AOT cache is the tool that gives C2 a real profile at startup.

"How does this interact with autoscaling?"

Badly, unless handled: an autoscaler that adds instances during a traffic spike adds instances that are at their slowest exactly when load is highest, and if the scaling metric is latency it may add more, all cold. Slow-start on the load balancer and a readiness gate that includes warm-up are what make scale-out safe; the AOT cache shortens the window; and the scaling policy should look at CPU or queue depth of warm instances rather than fleet-wide latency.

Q39 · Design. "Design the hot path of a message-processing service to be JIT-friendly: one million messages per second, a dozen message types, each parsed, validated and routed. What do you do and how do you prove it worked?"

Reveal answer

Strong answer Assumptions: a single JVM handles the volume on a few cores, the twelve types are known at build time, and the p99 matters as much as throughput. Design principles, each tied to a compiler mechanism:

  1. Monomorphic or bimorphic call sites: instead of one handler.handle(msg) site that sees twelve implementations and goes megamorphic, dispatch once with a switch over a sealed type or a type id into twelve separate call sites, each seeing one type, so each is inlined.
  2. Small hot methods: split rare paths out, so the hot body is under the 325-bytecode hot-inlining limit and the rare path (error handling, logging) is a separate call that is never inlined.
  3. Eliminable or absent allocation: parse into a reusable mutable message object per thread, or into small objects whose whole life is inside one inlined method so escape analysis removes them. Never box in the loop; use primitive arrays and long ids.
  4. No streams or lambdas in the inner loop: their plumbing adds megamorphic sites and allocation the compiler cannot always remove. Use plain loops there and streams everywhere else.
  5. Stable branches: a profile that is right 99.9 percent of the time is what C2 optimises for.

Proof:

  • A JMH benchmark with production-shaped messages and -prof gc, showing near-zero bytes per operation.
  • -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining showing the hot methods inlined and no "callee is too large" or "megamorphic" notes.
  • A JFR recording in production confirming a low allocation rate and no deoptimisation after warm-up.

What I would not do: write everything with final and hope, hand-unroll loops, or micro-optimise before the profile shows where the cycles go.

Picture it how the type profile of one call site decides whether the compiler can inline, and the numbers that prove it.

The setup: one dispatch site that sees twelve handler types, next to the version with one site per type.

Router.javaruns offline
// ❌ TRAP: one call site sees twelve receiver classes -> megamorphic -> virtual call, no inlining
void route(Message m) { handlers[m.type()].handle(m); }

// ✅ FIX: decide once, each call site sees exactly one class -> inlined
void route(Message m) {
    switch (m.type()) {
        case 0  -> orderHandler.handle(m);     // always OrderHandler here
        case 1  -> cancelHandler.handle(m);    // always CancelHandler here
        // ... ten more
        default -> unknown(m);                 // rare path, a separate small method
    }
}

Make the invisible visible: what C2 sees at each call site.

type profile per call siteruns offline
site A  handlers[type].handle(m)     Order 9%  Cancel 8%  Amend 8%  ... 12 types   -> megamorphic: virtual call
site B  orderHandler.handle(m)       Order 100%                                   -> monomorphic: inline
site C  cancelHandler.handle(m)      Cancel 100%                                  -> monomorphic: inline

The trace: a message through each version.

per messageruns offline
before: load handler -> vtable/itable dispatch -> call           ✗ no inlining, no escape analysis across the call
after : switch -> inlined handle() body -> parse into reused buffer   ✓ allocation-free, branch-predictable

What you see: PrintInlining and JMH output for the first version.

PrintInlining and -prof gcruns offline
# illustrative output
@ 14   com.acme.Handler::handle (0 bytes)   virtual call
Benchmark          Mode  Cnt     Score    Error  Units
Router.route      thrpt   10   9.1e6 ± 2.0e5  ops/s
·gc.alloc.rate.norm      10    96.0 ± 0.0      B/op

Why: a megamorphic site cannot be inlined, so the callee body stays opaque and its temporary objects stay allocated.

The fix: the switch version above, plus a reused message object.

What you see now: the same lines after the fix.

PrintInlining and -prof gcruns offline
# illustrative output
@ 20   com.acme.OrderHandler::handle (88 bytes)   inline (hot)
Router.route      thrpt   10   2.3e7 ± 3.0e5  ops/s
·gc.alloc.rate.norm      10    0.001 ± 0.001  B/op

Land it JIT-friendly means giving the compiler stable types, small hot bodies and no escaping garbage, and then reading its own log to prove it took the hint.

Likely follow-ups
"Requirement change: the message types are loaded as plugins at runtime. What breaks?"

The sealed-type switch is gone, because the set is open, and a single dispatch site will go megamorphic as plugins load; each plugin load can also deoptimise compiled callers through class-hierarchy invalidation. I would keep a per-type registry that maps a type id to a handler and accept one megamorphic interface call per message, which costs a few nanoseconds, while keeping everything inside each handler monomorphic and allocation-free. I would load all plugins at startup, before warm-up, so the hierarchy is stable when C2 compiles.

plugin registryruns offline
// plugins loaded at startup, before warm-up
Handler h = registry[m.typeId()];   // ❌ one megamorphic interface call per message (few ns)
h.handle(m);                        // ✅ inside each handler everything stays monomorphic and allocation-free
"What would you cut under time pressure?"

The per-type call-site splitting and the reusable message objects, which are the fiddly parts, keeping the two cheapest wins: no streams or boxing in the inner loop, and rare paths split out of hot methods. Those two alone usually get most of the benefit. I would keep the JMH-with--prof gc measurement, because without it I cannot tell whether the cut items mattered.

"How do you keep a later change from undoing this?"

A performance gate in CI: the JMH benchmark runs on every merge with a fixed input set and fails if bytes per operation rise above a threshold or throughput falls more than a tolerance across forks. Plus a comment block at the top of the hot-path class explaining which constraints exist and why, because the next engineer will add a stream for readability if nobody tells them what it costs.

Q40 · Design. "Design the warm-up and rollout strategy for a fleet of 200 latency-sensitive JVM services deployed several times a day."

Reveal answer

Strong answer Requirements: no latency regression visible to users during a deploy, deploys that finish in minutes, and a mechanism that works for services with very different code shapes. Design in four layers:

  1. Build layer: each release's pipeline runs a training pass, java -XX:AOTCacheOutput=app.aot with a recorded traffic replay, and ships the cache in the image. On JDK 25 this includes method profiles, so the JIT starts warm. The pipeline fails if the cache is not produced.
  2. Startup layer: the service runs a short internal warm-up before it reports ready, replaying a few hundred recorded requests against its own handlers with realistic data, bounded to thirty seconds. Readiness is gated on that plus dependency checks.
  3. Traffic layer: the load balancer uses slow-start, giving each new instance 5 percent of its share and ramping to full over three minutes. The rollout replaces instances in batches sized so the warm fleet always carries the load.
  4. Verification layer: every instance emits time-to-peak, measured as the moment its compilation rate falls below a threshold and its p50 flattens, as a metric. The rollout controller compares each new instance's p99 with the fleet after the ramp and pauses the deploy on a regression.

Trade-offs:

  • The training replay must be maintained as traffic changes.
  • The AOT cache must be rebuilt per JDK build.
  • Warm-up adds thirty seconds to every start.

What I would not do: rely on a latency-based liveness probe during warm-up, use -Xcomp, or treat a hand-written warm-up endpoint as a substitute for recorded traffic.

Picture it one instance walked through all four layers, and the table the rollout controller decides from.

The setup: the four layers as one pipeline definition that a single service goes through on every deploy.

deploy pipelineruns offline
build   : train with traffic replay -> app.aot, ship in image            (fail the build if app.aot is missing)
start   : java -XX:AOTCache=app.aot -jar app.jar
warm-up : replay ~300 recorded requests (max 30 s) -> then report ready
traffic : slow-start 5 % -> 100 % over 3 min
verify  : emit time-to-peak; pause deploy if new-instance p99 > fleet p99

The trace: one instance from process start to full traffic.

instance timelineruns offline
t=0     JVM starts from the AOT cache                        ✓ fast startup, profiles preloaded
t=5 s   internal warm-up replay begins, not ready            ✓ no user traffic yet
t=35 s  readiness true, load balancer sends 5 %              ✓ ramp starts
t=3 min 100 % share, compilation rate near zero              ✓ time-to-peak recorded
t=3 min p99 above the fleet?                                  ✗ pause the rollout

What you see: the per-instance numbers the rollout controller compares.

rollout controllerruns offline
# illustrative output
instance  time-to-peak  p99 after ramp  fleet p99  verdict
web-201   2m40s         42 ms           41 ms      ✓ continue
web-202   2m55s         43 ms           41 ms      ✓ continue
web-203   9m10s         190 ms          41 ms      ✗ pause deploy

Why: warm-up is a property of each release, so it has to be produced by the build, gated by readiness, spread by the load balancer and measured per instance.

Land it Warm-up is a release artefact, a readiness gate and a traffic policy at the same time, and the metric that keeps it honest is time-to-peak per instance.

Likely follow-ups
"Requirement change: the services run as scale-to-zero functions with a 500 ms cold-start budget. Does the design change?"

Completely. A three-minute ramp and a thirty-second warm-up do not exist in that world.

The choice becomes GraalVM native image, which starts in tens of milliseconds at the price of lower peak throughput and build-time reachability metadata, or a JDK with the AOT cache and a very small framework, which can reach a few hundred milliseconds.

I would pick native image for genuinely bursty functions and keep the JVM path for anything that stays warm most of the day, and I would measure cold start as the release metric instead of time-to-peak.

"What would you cut under time pressure?"

The internal warm-up phase and the automatic rollout pause, keeping the AOT cache in the build and slow-start on the load balancer, because those two are configuration rather than code and give most of the effect. I would keep the time-to-peak metric even if nothing acts on it yet, because it is what tells me whether the cuts were safe.

"How do you keep the training replay representative?"

Sample real requests continuously, scrubbed of secrets, into a rolling set that the pipeline uses, and compare the set of methods compiled during training with those compiled in the first ten minutes of production from a JFR recording; methods only in the second list mean the replay has drifted. Refresh the sample when that gap exceeds a threshold. Without this, the cache silently becomes a cache for last quarter's traffic.

replay driftruns offline
# illustrative output
compiled during training replay            : A B C D E
compiled in first 10 min of production     : A B C D E F G H
only in production                         : F G H     <- replay drifted, refresh the sample

09 · DrillMemory Model, Garbage Collection & Memory — Q41–Q80

This section pairs the two halves of "memory" that interviews test: the rules that decide what one thread sees of another's writes, and the machinery that lays out, allocates and reclaims objects. Expect to state happens-before precisely, pick a VarHandle mode on purpose, read a G1 or ZGC log line, and explain why a container killed a JVM whose heap was half empty.

Drill · Happens-before, volatile & safe publication

This group tests whether you can state the Java Memory Model as rules rather than folklore, and use those rules to explain exactly why an object can be seen half-built and exactly which line fixes it.

Q41. "Define the Java Memory Model precisely. What is happens-before, what are the rules that create it, and what does the model guarantee a program that has no data races?"

Reveal answer

The real test Whether you can list the happens-before edges from memory and state the data-race-free guarantee, instead of saying "volatile makes things visible".

Strong answer The Java Memory Model, chapter 17 of the language specification, is a set of rules about which values a read may return. It talks about actions: reads and writes of fields and array elements, monitor locks and unlocks, thread starts and joins.

Two orders matter:

  • Program order is the order of actions inside one thread.
  • Synchronizes-with is a cross-thread edge created by specific pairs of actions.

Happens-before is the transitive closure of both: if A happens-before B, then B is guaranteed to see the effects of A. The edges are:

  • Monitors: an unlock happens-before every later lock of that same monitor.
  • Volatile: a write to a volatile field happens-before every later read of that field.
  • Thread start: a call to Thread.start() happens-before every action in the started thread.
  • Join: every action in a thread happens-before another thread's join() on it returning, or isAlive() returning false.
  • Interrupt: a call to interrupt() happens-before the target detecting it.
  • Defaults: the default initialisation of a field (zero, null, false) happens-before the first action of every thread.
  • Finalizer: the end of a constructor happens-before the start of that object's finalizer.
  • Transitivity: all of this is transitive.

Final fields have a separate rule, the "freeze" at the end of the constructor, which I cover in Q45. A data race is formally two accesses to the same variable, at least one a write, that are not ordered by happens-before.

The central promise is the DRF guarantee: a program with no data races behaves as if it were sequentially consistent, meaning every thread sees one global interleaving of operations.

Programs with races get much weaker promises: reads still return some value that was written at some point, never a value out of thin air, but which value is decided by the compiler and the hardware.

Picture it one write-then-flag handoff drawn as a happens-before chain, and the same code with the chain broken.

The setup: two threads, a plain field and a volatile flag.

Handoff.javaruns offline
int data;                       // plain field
volatile boolean ready;         // creates the edge; remove "volatile" and the proof below breaks

// Thread A                     // Thread B
data = 42;                      if (ready) {
ready = true;                       System.out.println(data);
                                }

Make the invisible visible: the happens-before chain from the write to the read.

happens-before chainruns offline
Thread A                                   Thread B
data = 42            --program order-->
ready = true  (volatile write) --synchronizes-with--> read ready == true  (volatile read)
                                           --program order--> println(data)

chain: data = 42  hb  ready = true  hb  read ready  hb  println(data)   ✓ B must print 42

The trace: the same two threads when "ready" is a plain field, so no edge exists.

thread interleavingruns offline
step  Thread A                Thread B                      note
1     data = 42                                              
2     ready = true                                           (may be reordered before step 1)
3                             read ready == true             ✗ no edge: data race
4                             println(data) -> 0             ✗ stale: also allowed

What you see: racy code may print either value, and nothing in the spec says which.

consoleruns offline
# illustrative output
run 1: 42
run 2: 42
run 3: 0        <- allowed: the program has a data race

Why: without a happens-before edge from the write of data to the read of data, the read may return any value written to it, including the default zero.

The fix: make the flag volatile, which creates the edge in the chain above.

What you see now: whenever B sees the flag it prints 42.

consoleruns offline
# illustrative output
run 1: 42
run 2: 42
run 3: 42       <- guaranteed whenever the flag was seen as true

Land it If I can draw a happens-before chain from the write to the read, the read is correct; if I cannot, the program is racy and any argument about "what the CPU probably does" is a guess.

Likely follow-ups
"Does happens-before mean A physically executes before B?"

No, and this is the most common confusion. Happens-before is a rule about visibility, not about clock time. The compiler and the processor may still execute A after B as long as no thread can observe the difference.

For example, two volatile writes in one thread must appear in program order to another thread that reads both, but a plain write followed by an unrelated plain read can be freely swapped.

The model is deliberately phrased this way so that the just-in-time compiler can still reorder, hoist and eliminate accesses in the huge majority of code that touches no shared state.

When I want a physical ordering guarantee I have to express it through the rules, for example with VarHandle.fullFence() or a volatile access.

allowed reorderingruns offline
// Thread A                 // as executed, allowed: no thread can observe the difference
int a = x;   // plain read
y = 1;       // plain write   -> may be performed before the read of x
v1 = 1;        // volatile write
v2 = 1;        // volatile write: a reader that sees v2 == 1 must also see v1 == 1
"Give me a concrete example of an edge you get for free that people forget."

Submitting a task to an executor. The ExecutorService contract says actions in the submitting thread before submit() happen-before the task runs, and actions in the task happen-before Future.get() returns.

So I can build a mutable object, hand it to a task, and read the task's result without any volatile fields at all. The same applies to CompletableFuture completion, CountDownLatch.countDown() and await(), and putting into a ConcurrentHashMap and reading the value back from another thread.

These are documented in the java.util.concurrent package summary under "Memory Consistency Properties". Forgetting them leads to over-synchronising; not knowing them leads to under-synchronising.

free edge from an executorruns offline
Data d = new Data();                 // plain object, plain fields
d.value = 7;                         // write BEFORE submit()
Future<Integer> f = pool.submit(() -> d.value * 2);   // ✅ submit() happens-before the task body
int r = f.get();                     // ✅ task body happens-before get() returns -> r == 14
"What does the model say about a racy read? Can it return garbage?"

A racy read must return a value that some write actually stored to that variable, which includes the default zero value. It cannot return a mixture of two writes, except for the special long and double case in Q56.

It also cannot return a value "out of thin air", meaning a value that no write ever produced, even through a self-justifying causality loop; the model's causality rules in section 17.4.8 exist to rule that out.

What a racy read can do is return a stale value forever, because nothing forces the reader to look at memory again. That is exactly the while (!stop) bug in Q51, and it is why "it worked in the test" is not evidence of correctness.

"Where do synchronized and ReentrantLock fit in the rule list?"

The monitor rule covers synchronized directly: every exit of a synchronized block is an unlock, every entry is a lock, and the unlock happens-before a later lock of the same object.

ReentrantLock is not a monitor, so the language specification does not mention it, but the java.util.concurrent.locks.Lock contract promises the same edge: unlock() happens-before a later successful lock().

Internally the lock is built on a volatile state field in AbstractQueuedSynchronizer, so the edge is really the volatile rule in disguise.

That is a useful way to remember it: nearly every synchroniser in the JDK reduces to a volatile write followed by a volatile read of the same field.

Q42 · Scenario. "A lazily initialised singleton throws a sporadic NullPointerException inside one of its methods, even though the reference to the singleton was clearly non-null when the caller checked it. It happens a few times a day on the ARM fleet and never on developer laptops. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: a non-null reference to an object whose fields look uninitialised. The null is not the singleton; it is a field inside it, for example a Map the constructor was supposed to fill. That pattern has one classic cause: unsafe publication, where a reader sees the reference before it sees the constructor's writes.
  2. Evidence:
    • Read the stack trace to confirm the null is a field set in the constructor, and read the singleton code.
    • Expect something like if (instance == null) instance = new Config(); with no volatile, or double-checked locking whose field is not volatile.
    • Reproduce with a jcstress test (Q60) that has one actor create the object and a second actor read the reference then its field.
    • On the ARM machines jcstress will show the "non-null reference, zero field" outcome within seconds. On x86 it may never appear because the store order is stronger there.
  3. Ranked causes:
    • A non-volatile field in double-checked locking.
    • A singleton published through a plain static field written after class initialisation.
    • A constructor that leaks this into a registry before its fields are set.
    • Less commonly, a reflection-based framework that sets fields after publication.
  4. Fix, in order of preference:
    • Use the initialisation-on-demand holder idiom, a nested class whose static initialiser creates the instance, because class initialisation is guaranteed to be safely published by the virtual machine.
    • Or declare the field volatile so the constructor's writes happen-before the reference write, and the reader's volatile read happens-after it.
    • If the object is immutable, make its fields final and the freeze rule protects it regardless of how it is published.
  5. Prevention: a rule in code review that every lazily created shared object goes through a holder class, a volatile field, or an AtomicReference; and a jcstress test for any hand-written publication code so the ARM behaviour is exercised in CI, not discovered by customers.

Fix 2 is the one to reach for. It is lazy, thread-safe, allocation-free after the first call, and has no synchronisation on the hot path — the JVM guarantees a class's static initialiser runs exactly once, and that guarantee is exactly what a lazy singleton needs.

Picture it the half-built read as a two-thread interleaving, with the bytecode order that makes it possible.

The setup: the broken double-checked locking and its two correct forms, in the code below.

broken double-checked locking, and the two correct formsruns offline
// ❌ TRAP: BROKEN — the classic. Without volatile this is a real, reproducible bug.
class Holder {
    private static Engine instance;            // NOT volatile

    static Engine get() {
        if (instance == null) {                // read 1
            synchronized (Holder.class) {
                if (instance == null) {
                    instance = new Engine();   // ❌ TRAP: THREE steps, and they can reorder
                }
            }
        }
        return instance;                       // read 2 — may see a HALF-BUILT object
    }
}
// `new Engine()` is: (1) allocate, (2) run the constructor, (3) assign the field.
// The JIT is permitted to reorder (2) and (3), because within a single thread
// the difference is unobservable. Another thread taking read 1 can therefore see
// a NON-NULL reference to an object whose constructor has not run — every field
// still at its default. Hence a NullPointerException inside a method of an
// object that "cannot be null".

// ✅ FIX 1 — volatile. The write to `instance` becomes a release: everything the
// constructor wrote is visible to any thread that reads it.
private static volatile Engine instance;

// ✅ FIX 2 — the initialisation-on-demand holder. No synchronisation at all,
// no volatile, and it is the JVM's own class-initialisation lock doing the work.
class Holder {
    private static class Lazy { static final Engine INSTANCE = new Engine(); }
    static Engine get() { return Lazy.INSTANCE; }   // <clinit> runs once, safely
}

Make the invisible visible: what new Engine() compiles to, and the order a reader may observe.

javap -cruns offline
// source order in the bytecode of get():
new           #7      // allocate Engine, fields all zero/null
dup
invokespecial #9      // Engine.<init>: the constructor writes the fields
putstatic     #10     // instance = <the reference>

// order another core may observe (ARM, or a JIT reordering):
allocate -> putstatic (reference visible)  ... later ... constructor stores

The trace: two threads, one row per step, showing the half-built read.

thread interleavingruns offline
step  Thread A (first call)                  Thread B
1     read instance == null
2     lock, allocate Engine (fields null)
3     instance = ref  (store becomes visible)
4                                            read instance != null       ✗ skips the lock
5                                            engine.table.get(k) -> table still null   ✗ NPE
6     constructor stores table  (too late)

What you see: the exception names a field, not the singleton.

stack traceruns offline
# illustrative output
java.lang.NullPointerException: Cannot invoke "java.util.Map.get(Object)" because "this.table" is null
    at com.acme.Engine.lookup(Engine.java:31)
    at com.acme.Service.handle(Service.java:58)

Why: the reference store became visible before the constructor's stores, and nothing forced the order.

The fix: the volatile field or the holder idiom in the code above.

What you see now: no half-built reads, even on the ARM fleet.

jcstress resultruns offline
# illustrative output
outcome "ref non-null, table null": 0 occurrences    (before the fix: thousands within seconds on ARM)

Land it A non-null reference to a half-built object is the signature of unsafe publication, and the honest fix is to stop hand-rolling publication and let class initialisation or a volatile write do it.

Likely follow-ups
"You added volatile and it still happens. What next?"

Then the writes I need are not all before the volatile store. The usual reason is that the constructor registers this somewhere, for example Registry.add(this), so another thread obtains the reference through the registry before the constructor finishes, and my volatile field never enters that path.

The second reason is a two-phase object: the constructor runs, the field is published, and then an init() method fills in more state, which is a plain write after the volatile write and so is unprotected.

The third is a field that the class lazily fills on first use without its own synchronisation. I would grep for every place the reference escapes, and I would move all initialisation before the single publishing write, or make the object immutable with final fields.

leak through a registryruns offline
Engine() {
    Registry.add(this);      // ❌ TRAP: another thread gets the reference NOW
    this.table = load();     // ...before this write; a volatile field elsewhere does not help
}
"Why is this seen on ARM and not on x86?"

x86 uses a model called total store order.

Stores from one core become visible to other cores in the order they were issued, so the field stores in the constructor reach memory before the reference store, and a reader that sees the reference almost always sees the fields.

The just-in-time compiler could still reorder the stores, but in practice HotSpot's C2 rarely does for this shape.

AArch64, which Graviton and Apple silicon use, allows stores to become visible out of order unless a release instruction such as stlr separates them, and loads to be satisfied out of order unless ldar is used.

Without volatile, HotSpot emits plain stores and loads there, so the reorder is real and frequent.

what another core may observeruns offline
x86 (TSO)   : store fields; store ref   -> seen in this order     ✓ reader that sees ref sees fields
AArch64     : store fields; store ref   -> may be seen as ref first ✗ unless the ref store is stlr (volatile)
"Would synchronized on the getter fix it, and what would it cost?"

Yes. If every read of the reference goes through a synchronized method, the writer's unlock happens-before the reader's lock and the fields are visible.

The cost is a lock and unlock on every call, which on a hot path is a compare-and-swap on the object header, roughly 20 to 50 nanoseconds uncontended and far worse under contention because threads park and unpark.

Double-checked locking with a volatile field reduces the steady-state cost to one volatile read, which on x86 is a plain load and on AArch64 is an ldar, both nearly free.

The holder idiom is cheaper still: after class initialisation, the just-in-time compiler treats the static final as a constant.

"How would you prove in the running service that this is the cause, not a bug in the constructor?"

I would add a temporary check that captures the evidence.

In the method that fails, before using the field, read it once, and if it is null log the object's identity hash, the current thread, and how long since the singleton was created, using a timestamp the constructor writes last.

If unsafe publication is the cause, the null sightings cluster within microseconds of creation and only in the first calls after a restart or a cache flush. If it is a constructor bug, the null persists for that instance forever.

I would also run the jcstress test on the same machine type, because a forbidden outcome showing up there is the strongest evidence I can present.

Q43. "Explain volatile in depth: what it guarantees, what it does not, and what it actually costs on x86 versus ARM."

Reveal answer

The real test Whether you know that volatile orders the accesses around it, not only the field itself, and whether your cost estimate is hardware-specific rather than "it is expensive".

Strong answer A volatile field gives two things:

  • Visibility: a read always returns the most recent write in the global order of writes to that field, so a reader cannot cache it in a register forever.
  • Ordering: a volatile write happens-before every later volatile read of the same field. Because happens-before is transitive, every plain write the writer did before the volatile write is visible to the reader after the volatile read.

That second property is what makes it a publication tool: I write ten plain fields, then set one volatile flag, and a reader that sees the flag sees all ten.

What volatile does not give is atomicity of compound operations. count++ on a volatile int is still a read, an add and a write, and two threads can interleave them and lose an update. For that I need AtomicInteger or a lock.

On cost, the picture depends on the processor:

  • x86, read: total store order means stores are already seen in order by other cores, so a volatile read compiles to a plain mov and costs nothing extra.
  • x86, write: a volatile write needs to prevent a later load from being served before the store drains, so HotSpot emits a lock-prefixed instruction after the store, typically lock addl $0,(%rsp). It acts as a full fence and costs about 20 to 40 cycles plus a stall while the store buffer empties.
  • AArch64: the model is weaker, so HotSpot uses ldar for a volatile load and stlr for a volatile store. Both are cheaper than a full fence but the load is no longer free.

So "volatile is expensive" is half true: reads are cheap everywhere, writes cost a fence, and neither is remotely as costly as contended locking.

The architecture difference is the practical takeaway. On x86 a missing volatile is frequently benign by accident, because the hardware provides ordering the code never asked for. On ARM it is not — which is why the same build can pass thousands of CI runs and fail at a customer running Graviton.

Picture it the lost update on a volatile counter, and the instructions that make volatile cheap or costly on each architecture.

The setup: a volatile counter incremented by two threads, in the code below, plus the instructions each architecture emits.

what volatile guarantees, and what it does notruns offline
class Counter {
    private volatile int count;

    // GUARANTEED: visibility and ordering.
    //   - every read sees the most recent write (no caching in a register)
    //   - a write to a volatile is a RELEASE: everything written before it is
    //     visible to a thread that then reads it (an ACQUIRE)
    void publish() { data = compute(); count = 1; }   // data is safely published

    // ❌ TRAP: NOT GUARANTEED: atomicity of compound operations.
    void increment() { count++; }    // read-modify-write: STILL A RACE
}                                     // two threads can both read 5 and both write 6

// ✅ FIX: for that, you need an atomic:
private final AtomicInteger count = new AtomicInteger();
count.incrementAndGet();              // one CAS, actually atomic

// THE COST, and it differs sharply by architecture:
//
// x86 (TSO — the hardware already forbids most reordering):
//   volatile READ  = an ordinary mov. Effectively free.
//   volatile WRITE = mov + a lock-prefixed instruction (a StoreLoad barrier).
//                    Roughly the cost of an uncontended CAS, ~20 cycles.
//
// AArch64 / Graviton (weakly ordered — the hardware reorders freely):
//   volatile READ  = ldar   (load-acquire)   -- a real instruction, not free
//   volatile WRITE = stlr   (store-release)
//   Both cost something on every access, which is why a missing volatile
//   often passes on x86 CI and fails on ARM in production.

Make the invisible visible: the machine instructions behind one volatile read and one volatile write.

instructions per architectureruns offline
                 volatile read          volatile write
x86-64           mov                    mov + lock addl $0,(%rsp)     (StoreLoad fence)
AArch64          ldar                   stlr

The trace: two threads doing count++ on a volatile int, losing an update.

thread interleavingruns offline
step  Thread A              Thread B              count
1     read count -> 5                             5
2                           read count -> 5       5
3     write 6                                     6
4                           write 6               6    ✗ two increments, count grew by one

What you see: the total after two threads each add one million.

consoleruns offline
# illustrative output
expected 2000000
actual   1134512

Why: volatile makes each read and each write visible and ordered, but the read-add-write sequence is three separate steps.

The fix: AtomicInteger.incrementAndGet(), one atomic compare-and-set loop.

What you see now: the same run with the atomic.

consoleruns offline
# illustrative output
expected 2000000
actual   2000000

Land it I use volatile for a single flag or a reference that is written rarely and read often, and I reach for atomics or locks the moment the operation is read-modify-write.

Likely follow-ups
"Does a volatile read stop the compiler from reordering the plain reads after it?"

Yes, in one direction. Plain accesses that come after a volatile read in program order cannot be moved above it, and plain accesses before a volatile write cannot be moved below it. This is the acquire and release pattern: the read acquires, the write releases.

The compiler is free to move accesses the other way, for example a plain read from before the volatile read can be pushed after it. That asymmetry is enough for publication and is why volatile is cheaper than a full fence.

The VarHandle access modes in Q52 expose the same two halves separately as getAcquire and setRelease, so I can pay for only the half I need.

one-way barriersruns offline
plain read A
volatile read V      // acquire: later accesses cannot move ABOVE this line
plain read B         // stays after V
plain write C
volatile write W     // release: earlier accesses cannot move BELOW this line
// plain read A may still move down past V, and write C may not move below W
"How would you see what the compiler emitted for a volatile write?"

I would run the method under a benchmark with -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly, which needs the hsdis disassembler plugin on the library path, and restrict the output with -XX:CompileCommand=print,com.acme.Flag::set. On x86 the compiled code shows the store followed by lock addl $0x0,(%rsp). On AArch64 it shows a stlr instruction. If I cannot install hsdis, JMH with the -prof perfasm profiler shows the same hot instructions annotated with sample counts, which also tells me whether the fence is where time actually goes.

PrintAssembly excerptruns offline
# illustrative output
x86-64:   mov %eax,0x10(%rsi)        ; store the volatile field
          lock addl $0x0,(%rsp)      ; the fence
AArch64:  stlr w1, [x2]              ; store-release
"Is a volatile long atomic?"

Yes. The language specification section 17.7 says that writes and reads of volatile long and double values are always atomic, even on 32-bit virtual machines where a plain long may be written as two 32-bit halves.

This is one of the few places where volatile adds atomicity, but only for the single read or write; total += x on a volatile long is still a lost-update race.

On 64-bit HotSpot plain longs are atomic in practice anyway, so the volatile keyword is doing the visibility and ordering work, not the atomicity work.

"When would you choose AtomicBoolean over a volatile boolean?"

When I need a read-modify-write, most often "set it to true and tell me whether I was the one who did it", which is compareAndSet(false, true).

That is the shape of a once-only shutdown hook or a "first caller wins" guard, and a volatile boolean cannot express it without a lock. For a plain flag that one thread sets and others read, a volatile boolean is simpler, allocates nothing, and reads identically.

AtomicBoolean also exposes the weaker modes such as setRelease and getAcquire if I ever want to shave the fence, and lazySet is its older name for the same thing.

Q44 · Design. "Design the lazy initialisation of an expensive, shared, read-mostly object, say a compiled rule engine that takes two seconds to build, inside a service that handles thousands of requests per second. Show me the options and pick one."

Reveal answer

Strong answer Requirements:

  • The object is built at most once.
  • No request ever sees it half-built.
  • The steady-state read is as cheap as a field read.
  • Startup is not delayed if the object is never needed.
  • A failing build must be retryable rather than poisoning the process.

Assumption: the object is immutable once built. Design, in three tiers:

  1. Default, the initialisation-on-demand holder: a nested static final class Holder { static final RuleEngine INSTANCE = build(); } and a getter returning Holder.INSTANCE. The virtual machine runs the static initialiser under the class initialisation lock exactly once and publishes the result safely to every thread. After that the just-in-time compiler folds the static final into a constant, so the read costs nothing.
  2. If the construction needs runtime arguments, correct double-checked locking: a private volatile RuleEngine engine; read once into a local, checked for null, then a synchronized block that re-checks and assigns. The volatile is essential, because without it the reference store can become visible before the constructor's stores and a reader sees a non-null reference to zeroed fields.
  3. If the build may fail and must be retried: keep the volatile field but store a small result holder that records the exception, and let the next caller retry after a back-off.

Trade-offs:

  • The holder cannot take parameters and turns build errors into ExceptionInInitializerError followed by NoClassDefFoundError forever, which is the one reason to avoid it for network-dependent builds.
  • Double-checked locking costs one volatile read per call, which is a plain load on x86.

What I would not do:

  • A synchronized getter, because it puts a lock on every request.
  • A non-volatile double check, because it is the textbook bug.
  • A ConcurrentHashMap.computeIfAbsent with a two-second build inside, because that holds a bin lock and stalls unrelated keys (Q59).

Picture it five lazy-initialisation designs compared on the same concrete actions, and the class-initialisation handoff that makes the holder safe.

The setup: the two good options as code, holder first and volatile double-check second.

RuleEngineProvider.javaruns offline
// Option 1: holder (no arguments, cannot fail)
static RuleEngine get() { return Holder.INSTANCE; }
private static final class Holder {
    static final RuleEngine INSTANCE = RuleEngine.build();   // runs once, under the class-init lock
}

// Option 2: volatile double-check (needs arguments)
private volatile RuleEngine engine;
RuleEngine get(Config c) {
    RuleEngine e = engine;                  // one volatile read
    if (e == null) {
        synchronized (this) {
            e = engine;
            if (e == null) engine = e = RuleEngine.build(c);   // ✅ FIX: volatile makes the publish safe
        }
    }
    return e;
}

Make the invisible visible: each option against the same concrete actions.

Five designs, same five actions
ActionHolderVolatile double-checkSynchronized getterNon-volatile double-checkcomputeIfAbsent
16 threads call get() firstWorks: built onceWorks: built onceWorks: built onceSilently wrong on ARM: half-built readWorks: built once
steady-state readWorks: constantWorks: one volatile readSlow: a lock per callWorks: plain readWorks: hash lookup
build() throwsFails: ExceptionInInitializerError, then NoClassDefFoundErrorWorks: next caller retriesWorks: next caller retriesWorks: next caller retriesWorks: entry not stored
2-second build insideWorks: only first callers waitWorks: only first callers waitSlow: every caller waitsWorksSlow: stalls other keys in the same bin

The trace: two threads on the first call of the holder, showing why no volatile is needed.

class initialisationruns offline
step  Thread A                       Thread B
1     touches Holder -> starts <clinit> under the class-init lock
2                                    touches Holder -> blocks on the lock
3     <clinit> finishes, lock released    ✓ release happens-before B's acquire
4                                    resumes, sees fully built INSTANCE         ✓

What you see: the failure mode that rules the holder out for network-dependent builds.

stack traceruns offline
# illustrative output
java.lang.ExceptionInInitializerError            <- first caller
Caused by: java.net.ConnectException: Connection refused
java.lang.NoClassDefFoundError: Could not initialize class com.acme.RuleEngineProvider$Holder   <- every later caller

Land it Let class initialisation do the publication whenever the build takes no arguments and cannot fail, and fall back to a volatile double check only when it must.

Likely follow-ups
"Change the requirement: the engine must be rebuilt every time the rules file changes. What changes?"

The holder no longer fits because a static final cannot change.

I move to an AtomicReference<RuleEngine> that a single reloader thread swaps with set after building the new engine off to the side, and every request does one get at the start and uses that snapshot for its whole lifetime.

The build stays out of any lock, so requests keep running on the old engine during the two seconds. I add a version number to the engine so logs can say which rules a request used. This is the snapshot pattern in Q48.

The lazy first build can stay lazy with a compare-and-set on the reference, but in practice I build eagerly at startup and fail fast if the rules file is broken.

snapshot swapruns offline
private final AtomicReference<RuleEngine> ref = new AtomicReference<>();

void reload() { ref.set(RuleEngine.build(rulesFile)); }   // built off to the side, then one swap

Result handle(Request r) {
    RuleEngine snapshot = ref.get();                      // one read per request, used for its whole life
    return snapshot.evaluate(r);
}
"What would you cut under time pressure?"

I would cut the retry logic and the parameterised path and ship the holder idiom, because it is six lines, impossible to get wrong, and covers the common case. If the build reads a file, I would make the file read happen in the static initialiser too and accept that a broken file kills the class on first use, since a service that cannot load its rules should not serve traffic anyway. I would keep one test that calls the getter from 16 threads through a CyclicBarrier and asserts a single build, because that test is cheap and documents the intent.

"Why does the holder idiom work without any volatile? What in the specification guarantees it?"

Section 12.4.2 of the language specification describes class initialisation as a procedure run under a per-class lock.

Any thread that touches the class while initialisation is in progress blocks until it completes, and the lock release at the end happens-before the lock acquisition of the waiting thread, so all writes made by the static initialiser are visible.

Threads arriving later see the class already initialised, and the specification guarantees they see the fully initialised state because the virtual machine's initialisation-state check is itself synchronised.

In HotSpot terms, the compiled code for an uninitialised class calls into the runtime, and once initialised the compiler bakes the static final's value into the machine code as a constant.

"Is there anything newer in the platform for this, as of Aug 2026?"

Yes, stable values.

JEP 502 in JDK 25 previews java.lang.StableValue, a holder that is set at most once and afterwards treated by the just-in-time compiler as a constant, the same way a static final is, but usable for instance fields and lists and with a lazy supplier form StableValue.supplier(() -> build()).

It gives the holder idiom's performance with the flexibility of a field.

As of August 2026 it is still a preview feature, so I would verify its status on the JEP page before relying on it in production and would keep the holder idiom in code that must compile without --enable-preview.

Q45. "What do final fields guarantee under the memory model, how can that guarantee be broken, and how do records benefit?"

Reveal answer

The real test Whether you know the freeze rule is a special case outside happens-before, and that it protects only what the constructor wrote before it finished.

Strong answer Section 17.5 of the language specification gives final fields their own rule. At the end of a constructor there is a conceptual freeze action.

Any thread that later obtains a reference to the object, by any route at all, even a racy plain read of a non-volatile static, is guaranteed to see the frozen values of the final fields. It also sees everything reachable through those final fields that was written before the freeze.

That is the guarantee that lets an immutable object be published with no synchronisation: a String, a BigDecimal, or a value class with final fields can be dropped into a plain static field and every reader sees it complete.

HotSpot implements this by emitting a store-store barrier at the end of any constructor that writes a final field, which on x86 is free and on AArch64 is a dmb ishst instruction.

The rule is broken in three ways:

  • Leaking this: registering a listener or starting a thread inside the constructor, because the freeze has not happened yet when the other thread gets the reference.
  • Non-final fields in the same object: they are simply not covered. A class with one final and one plain field publishes the final one safely and the plain one racily.
  • Writing finals after construction: through reflection, Unsafe or deserialisation, which the specification explicitly says voids the guarantee for that field. It can also confuse the just-in-time compiler if it has already treated the field as a constant.

Records help because every component is a final field set in the canonical constructor, the compiler forbids instance fields outside the components, and the constructor cannot easily leak this before assignment. So a record of immutable components is safely publishable by construction.

Break 2 is the one records do not solve for you. A record gives you final components and safe publication of the references; if a component is a mutable collection, the contents are still shared mutable state and the guarantee stops at the reference.

Picture it the final-field guarantee and the moment it does not apply, drawn as a memory picture and an interleaving.

The setup: a safe immutable Config, the leaking Broken, the mutable-content AlsoBroken and a record, all in the code below.

final field guarantees, and the two ways to break themruns offline
// THE GUARANTEE: if an object is not published before its constructor finishes,
// any thread that sees the object sees its FINAL fields fully initialised —
// with no volatile and no synchronisation.
final class Config {
    private final Map<String, String> values;      // final
    Config(Map<String, String> v) { this.values = Map.copyOf(v); }
    String get(String k) { return values.get(k); }
}
// Publishing a Config through a plain, non-volatile field is safe FOR values.

// ❌ TRAP: BREAK 1 — `this` escapes during construction. The guarantee only covers
// objects published after the constructor returns.
final class Broken {
    private final int x;
    Broken(Registry r) {
        r.register(this);      // ANOTHER THREAD CAN SEE THIS NOW
        this.x = 42;           // ...before x is assigned. It reads 0.
    }
}

// ❌ TRAP: BREAK 2 — a final field pointing at a MUTABLE object. The reference is safely
// published; the object's contents are not.
final class AlsoBroken {
    private final List<String> items = new ArrayList<>();   // final reference
    void add(String s) { items.add(s); }                    // unsynchronised mutation
}                                                            // -> data race on contents

// RECORDS get this right by construction: components are final, and the
// canonical constructor cannot leak `this` before assignment. But a record
// holding a mutable list has exactly BREAK 2 — which is why defensive copying
// in a compact constructor matters:
record Order(String id, List<Line> lines) {
    Order { lines = List.copyOf(lines); }    // ✅ FIX: now genuinely immutable
}

Make the invisible visible: what another thread sees of Broken at the moment the registry hands it out.

memory pictureruns offline
Registry (thread B)                   heap
  list[0] ------------------------->  Broken@1a2b
                                        x = 0      <- r.register(this) already ran
                                                   <- this.x = 42 has NOT run yet (no freeze yet)

The trace: two threads, one row per step.

thread interleavingruns offline
step  Thread A (constructor)          Thread B
1     r.register(this)
2                                     b = registry.get(0)         ✗ freeze has not happened
3                                     print(b.x) -> 0             ✗ sees the default
4     this.x = 42
5     constructor ends: freeze        (too late for step 3)

What you see: a final field read as zero.

consoleruns offline
# illustrative output
x = 0

Why: the freeze only protects objects whose reference was published after the constructor finished.

The fix: finish the constructor, then register, for example from a static factory.

Broken.javaruns offline
final class Fixed {
    private final int x;
    private Fixed() { this.x = 42; }
    static Fixed create(Registry r) {
        Fixed f = new Fixed();     // ✅ FIX: constructor and freeze complete first
        r.register(f);
        return f;
    }
}

What you see now: every reader sees the frozen value.

consoleruns offline
# illustrative output
x = 42

Land it Finals buy me publication safety for the object's own state, but only if the constructor finishes before anyone else sees the reference.

Likely follow-ups
"Does a final reference to a mutable ArrayList make the list's contents safe?"

Only the contents written before the constructor ended. The freeze covers everything reachable through the final field at freeze time, so a list filled inside the constructor is seen complete by every reader.

Anything added later is a plain write to the list's internal array and is unprotected, and a reader may see the old size with the new array or the other way around.

So the pattern "final field, mutate after construction" is not thread-safe, and the fix is either to stop mutating, wrapping with List.copyOf in the constructor, or to guard every later access with a lock or use CopyOnWriteArrayList.

final reference, later mutationruns offline
final class Holder {
    final List<String> items = new ArrayList<>(List.of("a", "b"));  // ✅ seen complete: written before the freeze
    void add(String s) { items.add(s); }                          // ❌ TRAP: later writes are unprotected
}
"How does deserialisation set final fields, and why is that not a race?"

ObjectInputStream allocates the object without running its constructor and writes the fields, including finals, through Unsafe.putObject style calls; records go through their canonical constructor instead, which is one of their safety advantages.

It is not a race in practice because the deserialising thread owns the object until it returns it, and it normally publishes it through a queue, a future or a lock, which creates the happens-before edge.

The specification does say the final-field guarantee is void for fields written this way, so if someone published a deserialised object through a plain static with no synchronisation, the freeze would not save them.

Deserialisation frameworks also pay for this: the compiler cannot trust the field as a constant.

"Why does HotSpot trust final fields in records and not in ordinary classes?"

Because ordinary final instance fields can be changed by reflection and by some serialisation libraries, and C2 folding them into constants would then produce wrong code.

HotSpot only constant-folds final instance fields of classes it knows cannot be tampered with: records, hidden classes, and JDK-internal classes annotated with @Stable, plus static finals everywhere. Records have this because Field.set throws IllegalAccessException on a record component even after setAccessible(true).

There is an experimental flag, -XX:+TrustFinalNonStaticFields, that extends the trust to every class, but it is unsafe with any framework that mutates finals and is not for production.

"How do you leak this without noticing?"

The subtle cases are an inner class or lambda created in the constructor, because it captures this; a call to an overridable method from the constructor, because a subclass override runs before the subclass fields exist; and a static registry call such as EventBus.register(this).

Starting a thread in the constructor is the loud version. My review rule is that a constructor assigns fields and validates, and anything that hands the object to someone else moves to a static factory method that runs after new returns.

Static analysis such as Error Prone's ConstructorLeaksThis check catches most of these mechanically.

Q46 · Scenario. "We hot-reload an immutable configuration object every minute. After a reload, some request threads keep using the old values for hours, others switch immediately. The object itself is immutable and correct. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: stale reads that are per-thread and persistent, not a brief delay. That points at the reference to the configuration, not at its fields. Immutability protects the object's contents; it says nothing about how the pointer to the current object reaches other threads.
  2. Evidence: look at how the reference is stored and read.
    • If it is a plain static Config current;, the just-in-time compiler is entitled to read it once and keep it in a register for the life of a compiled loop. I would confirm the compiled state with -XX:+PrintCompilation and by seeing the problem disappear under -Xint.
    • Search for ThreadLocal and for per-thread caches, such as a field on a handler object that copies the config at construction time.
    • "Some threads keep the old one for hours" is exactly what a thread-local or a long-lived worker with a cached copy looks like.
  3. Ranked causes:
    • A plain non-volatile static holding the reference, so compiled code never re-reads it.
    • A ThreadLocal<Config> or a worker object that captured the config once and never refreshes.
    • A reload that mutates a "current" holder object's fields instead of swapping the reference.
    • Rarely, a class-loader split where the reloader and the readers see different Config classes.
  4. Fix:
    • Hold the reference in a volatile field or an AtomicReference<Config>.
    • Have the reloader build the new object fully and then do one set.
    • Have every request call get() once at its start and use that snapshot throughout.
    • Remove the per-thread caches or give them a version check against the volatile version number.
  5. Prevention: an integration test that reloads and asserts every worker thread observes the new version within one request; a log line on reload that prints the new version and a metric that counts requests by config version, so drift is visible on a dashboard.

Picture it which copy of the config reference each thread holds, and why one thread never lets go of version 1.

The setup: a plain static reference to an immutable config, read in a worker loop and replaced by a reloader.

ConfigHolder.javaruns offline
record Config(long version, int timeoutMs) {}        // immutable: contents are safe

class Holder {
    static Config current = new Config(1, 500);      // ❌ TRAP: plain field, no ordering, no visibility

    static void reload(long v) { current = new Config(v, 500); }   // writer: another thread, every minute
}

void workerLoop() {
    while (true) {
        handle(Holder.current.timeoutMs());          // compiled loop may read `current` ONCE
    }
}

Make the invisible visible: which copy of the reference each thread is really using.

memory pictureruns offline
Holder.current -------------------> Config v8 { timeoutMs = 500 }      <- the heap has the new one

worker-1 (compiled loop)  register r1 ----> Config v1                  <- read once, kept in a register
worker-2 (after restart)  loads Holder.current each call -> Config v8  ✓

The trace: one row per step, two threads.

thread interleavingruns offline
step  reloader                       worker-1
1                                    loop becomes hot, C2 compiles it (OSR)
2                                    reads Holder.current -> v1, keeps it in a register
3     Holder.current = v2 ... v8                                          ✓ write happens
4                                    next iteration uses register -> v1   ✗ never re-reads

What you see: request logs from several threads, with some stuck on the first version.

request logruns offline
# illustrative output
12:00:05 worker-1  config.version=1
12:00:05 worker-2  config.version=1
12:08:05 worker-1  config.version=1     <- stuck for hours
12:08:05 worker-2  config.version=9     <- this thread re-reads

Why: a plain field gives the compiler no reason to read it again, and immutability of the object does not change how the reference travels.

The fix: a volatile reference, read once per request.

ConfigHolder.javaruns offline
static volatile Config current = new Config(1, 500);      // ✅ FIX: every read goes to memory

void handleRequest(Request r) {
    Config c = Holder.current;                            // ✅ FIX: one snapshot per request
    process(r, c.timeoutMs());
}

What you see now: all threads move to the new version within one request.

request logruns offline
# illustrative output
12:08:05 worker-1  config.version=9
12:08:05 worker-2  config.version=9

Land it Immutability makes the object safe to share but the pointer to it still has to be published through a volatile or atomic reference, and every cache of that pointer is another place it can go stale.

Likely follow-ups
"You made the field volatile and one thread still shows old values. What next?"

Then that thread is not reading the field.

I would take a thread dump with jcmd <pid> Thread.print and look at what the stuck thread is executing; commonly it is a long-lived object such as a connection handler or a scheduled task that received the Config in its constructor and holds it in a plain field.

The volatile only helps callers who read the volatile. Next I would check for a ThreadLocal or a per-thread Map in that code path.

Finally, I would check whether the reloader actually wrote the field; a reload that catches an exception, logs at debug level and returns leaves the old reference in place, and only threads that restart see a fresh one.

thread dumpruns offline
# illustrative output
"worker-1" #31 RUNNABLE
    at com.acme.ConnHandler.process(ConnHandler.java:57)   <- ConnHandler holds a Config copy in a plain field
    at com.acme.ConnHandler.run(ConnHandler.java:40)
"Why is taking one snapshot per request important rather than reading the volatile each time?"

Consistency. If a request reads the timeout from one config version and the retry count from the next, it may combine values that were never meant to be combined, for example a short timeout with zero retries.

A single get() at the start gives the request a coherent view.

It is also cheaper: the volatile read is nearly free, but passing a local reference through the call chain lets the compiler treat every field access as a plain load from a known object, and it makes the code testable because the config becomes a parameter rather than global state.

"What if the config graph is large and a reload allocates a lot? Any concerns?"

Two. Memory: two full graphs coexist during the swap and for as long as any request still holds the old snapshot, so peak usage is at least double the graph, which matters if the graph is hundreds of megabytes.

I would share unchanged subtrees between versions using a persistent structure or by reusing the old objects for unchanged sections, which is safe because they are immutable.

Garbage collection: a large allocation once a minute is a burst of old-generation promotion, so with G1 I would watch mixed collections with -Xlog:gc*.

If a section is over half a region, 2 MB by default on a small heap, it becomes a humongous allocation and is worth splitting.

memory during the swapruns offline
before swap : [ Config v8: 400 MB ]
during swap : [ Config v8: 400 MB ] + [ Config v9: 400 MB ]   <- old stays until the last request lets go
a 400 MB graph in G1 is many humongous objects; split sections larger than half a region
"Could you have used synchronized or a read-write lock instead?"

I could, and it would be correct, but it is the wrong tool. A read-write lock costs a compare-and-swap on the lock's state for every read, and under thousands of readers per second the state word becomes a contended cache line.

A volatile or atomic reference costs one plain load on x86 per request and never blocks.

Locks make sense when the reload must wait for in-flight readers to finish, for example to close a resource the old configuration owns; in that case I would use StampedLock with optimistic reads, or better, reference-count the old snapshot and close it when the count reaches zero.

Q47. "List every way to safely publish an object in Java, and show me what a reader can see when a mutable object is published unsafely."

Reveal answer

The real test Whether you can name the mechanisms and tie each to the happens-before rule that makes it work.

Strong answer Safe publication means making a reference visible to other threads in a way that also makes the object's state visible. Every mechanism on the list works because it creates a happens-before edge between the constructor's writes and the reader's first use.

The catalogue:

  • Static initialiser: class initialisation is synchronised by the virtual machine.
  • A volatile field: because of the volatile rule.
  • An AtomicReference or any AtomicX: a volatile underneath.
  • Final fields: the freeze rule protects the object regardless of the route.
  • A lock the reader also takes: a monitor or ReentrantLock.
  • A concurrent collection: ConcurrentHashMap, ConcurrentLinkedQueue or a BlockingQueue, whose contracts promise the edge.
  • Handing it to a thread: through Thread.start, an executor submit, or a CompletableFuture.

Now the unsafe case. Suppose class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } } and a writer does shared = new Point(3, 4); into a plain static field.

The virtual machine does three things, and nothing orders them for another thread:

  • Allocates the object, which zeroes its memory.
  • Runs the constructor's two stores.
  • Stores the reference.

A reader can therefore observe the reference as non-null and then read x as 0, or x as 3 and y as 0. On AArch64 hardware this is not theoretical but a routine result in a stress test.

The reader is not seeing garbage; every value it sees was genuinely written, the zero by allocation and the 3 by the constructor. It is seeing them in an order the writer never intended.

Outcome (c) is the one that makes these bugs so hard to believe. The reference is non-null, so every null check passes, and the object's own invariants are violated — which produces a NullPointerException deep inside a class that appears to guarantee the field can never be null.

Picture it what a reader can hold in the unsafe case, and the outcome table that proves it.

The setup: the unsafe field and every safe idiom, in the code below, applied to the Point example.

every safe publication idiom, and what a reader sees without oneruns offline
// ❌ TRAP: UNSAFE — the reader may see a non-null reference to a half-built object,
// or may never see the write at all.
Map<String,String> config;                    // plain field
void publish() { config = buildConfig(); }    // no ordering, no visibility

// ✅ FIX: THE SAFE IDIOMS. Each creates a happens-before edge between the writer's
// construction and the reader's observation:
//
// 1. Static initialiser — the JVM's class-init lock does it.
static final Config CONFIG = new Config();
//
// 2. volatile field (or AtomicReference).
volatile Config config;
//
// 3. final field of a properly constructed object (see Q45).
//
// 4. A field guarded by a lock, written and read under the SAME lock.
synchronized void set(Config c) { this.config = c; }
synchronized Config get() { return this.config; }
//
// 5. Putting it in a concurrent collection — the collection's internal
//    synchronisation provides the edge.
map.put("config", c);        // ConcurrentHashMap
queue.put(c);                // BlockingQueue: put happens-before take

// WHAT AN UNSAFE READER CAN ACTUALLY SEE — all three are legal:
//   a) null              (the write is not visible yet, possibly for ever)
//   b) a fully built object   (what you expected)
//   c) a NON-NULL reference to an object with default-valued fields
//      i.e. config != null, but config.timeout == 0 and config.url == null

Make the invisible visible: what the reader holds in the unsafe case.

memory pictureruns offline
static shared ---------------> Point@2f1 { x = 0, y = 0 }     <- reference visible, constructor stores not yet
                                          (x = 3 and y = 4 arrive later)

legal observations by the reader:   null | Point(0,0) | Point(3,0) | Point(0,4) | Point(3,4)

The trace: writer and reader, one row per step.

thread interleavingruns offline
step  writer                              reader
1     allocate Point (x=0, y=0)
2     shared = ref   (visible early)
3                                         q = shared  (non-null)         ✗ no edge
4                                         q.x -> 0                       ✗ half-built
5     this.x = 3; this.y = 4

What you see: the outcome table of a jcstress run with a plain field.

jcstress outcomesruns offline
# illustrative output
 -1   (null)           expected
 43   (3,4)            expected
  0   (0,0)            ✗ half-built sighting
  3   (3,0)            ✗ half-built sighting
 40   (0,4)            ✗ half-built sighting

Why: nothing orders the constructor's stores before the reference store as seen by the reader.

The fix: any idiom above, for example a volatile field, or final fields in Point.

What you see now: only the two expected outcomes.

jcstress outcomesruns offline
# illustrative output
 -1   (null)           expected
 43   (3,4)            expected
(no 0, 3 or 40 outcomes)

Land it Publication is a contract between the writer's last store and the reader's first load, and if I cannot name which rule links them, the object may be seen half-built.

Likely follow-ups
"Is a HashMap wrapped in Collections.synchronizedMap a safe publication channel?"

Yes, as long as both the writer's put and the reader's get go through the wrapper. Every method of the wrapper synchronises on the same mutex object, so the writer's unlock happens-before the reader's lock and the value's state is visible.

The trap is iteration: the wrapper's iterator() is not synchronised, so a reader iterating without holding the mutex is racing with writers and can see inconsistent internal state or throw ConcurrentModificationException. The other trap is publishing the underlying map instead of the wrapper.

Given the choice I use ConcurrentHashMap, which provides the same publication guarantee without a global lock.

"Is effectively immutable good enough, meaning no finals but never mutated after construction?"

Only if it is also safely published through one of the channels. Without finals the freeze rule does not apply, so the constructor's writes have no ordering relative to the reference store, and a racy reader may see zeros.

Once the object has been published through a volatile, a lock or a concurrent collection, it can be read freely by any number of threads with no further synchronisation, because nobody writes to it again.

This is the distinction Java Concurrency in Practice draws between immutable objects, which are safe however published, and effectively immutable objects, which need one safe publication step and are then free.

"How does a BlockingQueue hand-off give me the guarantee?"

The java.util.concurrent package documentation states that actions in a thread before placing an object into any concurrent collection happen-before actions after accessing or removing it in another thread. For ArrayBlockingQueue the mechanism is a ReentrantLock taken by both put and take. For LinkedTransferQueue and ConcurrentLinkedQueue it is volatile writes to the linked nodes, done through VarHandle release and acquire modes. Either way, the object I built before put and all its reachable state is visible after take with no volatile fields of my own.

"Can you show the unsafe publication actually happening?"

Yes, with jcstress. A test class annotated @JCStressTest holds a plain field Point p. One @Actor method does p = new Point(3, 4); the second actor reads Point q = p and records q == null ? -1 : q.x + q.y * 10 into an I_Result.

Outcomes -1 and 43 are expected; 0, 3 and 40 are the half-built sightings.

On an AArch64 box the interesting outcomes usually appear within the first few seconds; on x86 I typically only see them if C2 reorders the stores, which is why the test must run on the production architecture.

jcstress testruns offline
@JCStressTest
@Outcome(id = {"-1", "43"}, expect = ACCEPTABLE, desc = "null or fully built")
@Outcome(id = {"0", "3", "40"}, expect = FORBIDDEN, desc = "half-built Point")   // ✗ shows on AArch64
@State
public class PublishTest {
    Point p;
    @Actor public void writer()          { p = new Point(3, 4); }
    @Actor public void reader(I_Result r){ Point q = p; r.r1 = (q == null) ? -1 : q.x + q.y * 10; }
}

Q48 · Design. "Design a configuration mechanism for a service where an operator can push a new configuration at any time, thousands of requests per second must read it, and no request may ever see a mix of old and new values."

Reveal answer

Strong answer Requirements:

  • Atomic switch between whole configurations.
  • Reads as cheap as a field load.
  • Reload never blocks requests.
  • Every request internally consistent.
  • An audit trail of which version served which request.

Assumptions: reloads are rare, a few per minute at most; the configuration fits in memory many times over; readers far outnumber writers.

Design:

  • Shape: the configuration is an immutable graph of records, for example record Config(long version, Instant loadedAt, Timeouts timeouts, Map<String, Route> routes), with every collection wrapped by Map.copyOf or List.copyOf in the canonical constructor so nothing inside can change.
  • Holder: the current snapshot lives in a single AtomicReference<Config>.
  • Loader: a loader thread parses, validates, builds the whole new graph off to the side, and performs one set. That is the atomic switch, and because every field is final the freeze rule plus the volatile write guarantee that readers see the complete graph.
  • Readers: each request calls get() exactly once, at the edge, and passes the snapshot down through parameters, never re-reading the global. Version numbers increase monotonically and the request log carries the version.
  • Derived caches: for example a compiled routing trie, computed inside the loader as part of the new snapshot, so cache invalidation is not a separate step. The old snapshot and its caches become garbage together when the last request releases them.

Trade-offs:

  • Memory doubles briefly during a swap.
  • A request that started before the swap finishes on the old version, which is the correct behaviour but must be explained to operators.
  • Derived structures cost time in the loader rather than lazily.

What I would not do: mutate a live configuration object in place, because readers would see torn combinations; use a read-write lock, which makes every read a contended compare-and-swap; or keep per-thread copies, which is how the stale-read incident in Q46 happens.

Picture it two requests on two versions at once, and the torn read the snapshot design rules out.

The setup: an immutable config, a loader that validates then swaps, and a request that takes one snapshot.

ConfigService.javaruns offline
record Timeouts(int connectMs, int readMs) {}
record Config(long version, Timeouts timeouts, Map<String, Route> routes) {
    Config { routes = Map.copyOf(routes); }                 // nothing inside can change
}

private final AtomicReference<Config> ref = new AtomicReference<>(initial());

void reload(Path file) {
    Config next = parseAndValidate(file);                   // built off to the side
    ref.set(next);                                          // the one atomic switch
}

Response handle(Request r) {
    Config c = ref.get();                                   // ✅ FIX: exactly once per request
    return route(r, c);                                     // passed down, never re-read
}

Make the invisible visible: two requests on different versions at the same instant, and nothing shared that changes.

memory pictureruns offline
ref (AtomicReference) -----------> Config v6 { timeouts: 2s/5s, routes: ... }     (current)

request A (started before swap)  local c --> Config v5 { timeouts: 1s/3s, ... }   (stays on v5, complete)
request B (started after swap)   local c --> Config v6                            (complete)
v5 is garbage once request A finishes

The trace: the same swap against a mutable config, and against the snapshot design.

mutable versus snapshotruns offline
step  loader                          request R
1                                     reads timeout (v5: 1 s)
2     config.timeout = 2 s ; config.routes = v6    (in place)
3                                     reads routes (v6)       ✗ torn: timeout from v5, routes from v6
--- snapshot design ---
1                                     c = ref.get()  (v5)
2     ref.set(v6)
3                                     c.routes (v5)           ✓ all from one version

What you see: the request log carries the version, so a mix would be visible.

request logruns offline
# illustrative output
req=a1f  config.version=5  timeout=1000  routes=v5
req=a20  config.version=6  timeout=2000  routes=v6      <- no line ever shows version=5 with routes=v6

Why: a request that never shares anything mutable cannot see a mixture.

Land it One immutable graph, one atomic reference, one read per request: consistency comes from never sharing anything that can change.

Likely follow-ups
"Change the requirement: the configuration is 2 GB and reloads every ten seconds. Does the design survive?"

The snapshot idea survives; the "rebuild everything" part does not.

I would make the graph persistent, meaning a new version shares every unchanged subtree with the old one and only copies the path from the root to the changed nodes, the way an immutable hash trie works.

The loader receives a diff rather than a full file, applies it to the previous snapshot, and produces a new root; unchanged 1.9 GB is shared, only the changed sections allocate. Derived caches become per-subtree so they are shared too.

I would also watch garbage collection closely, because retaining two roots is now cheap but a request that holds an old root for minutes keeps old subtrees alive, so I would add a metric for the age of the oldest snapshot still referenced.

"What would you cut under time pressure?"

The derived caches and the persistent sharing. I would ship the plain immutable record graph in an AtomicReference, rebuilt from scratch on each reload, with a version number and one log line per swap. That is perhaps fifty lines and it is already correct.

Route lookup would be a linear scan or a plain map built inside the record constructor.

What I would not cut is the "one get() per request" rule and the validation before the swap, because those are the two things that prevent a bad reload from taking the service down, and they cost nothing to keep.

"What exactly breaks if the snapshot is mutable?"

Three things. Consistency: a reader in the middle of a request sees the timeout from version 5 and the route table from version 6, and there is no combination of locks short of holding one for the whole request that prevents it.

Visibility: without final fields, a reader that obtained the reference sees whatever mix of old and new field values the hardware delivers, including zeros if the object is new.

Safety of derived caches: a cache keyed on the object identity becomes wrong the moment the object changes underneath it. Mutability also removes the audit trail, because "version 5" no longer names a fixed set of values.

Immutability is what turns "a config" into "a fact I can reason about".

what a mutable snapshot lets throughruns offline
# illustrative output
req=b07  config.version=6  timeout=1000  routes=v6      <- timeout from v5, routes from v6
req=b08  config.version=6  timeout=0     routes=null    <- new object, plain fields, no freeze
"How do you validate before the swap and what happens if validation fails?"

Validation runs in the loader against the fully built candidate: schema checks, referential checks such as every route naming a real upstream, and a dry run of the derived structures.

If it fails, the loader logs the version, the error and the diff, increments a config_reload_failures counter, and does not touch the reference, so the service keeps serving the last good configuration. That is the property operators care about: a bad push never breaks traffic.

I would also keep the last N snapshots in a small ring so an operator can roll back by version number without re-fetching, which is a single set of an already-validated object.

rollback ringruns offline
private final Deque<Config> lastGood = new ArrayDeque<>();   // touched only by the loader thread

void rollback(long version) {
    lastGood.stream().filter(c -> c.version() == version)
            .findFirst().ifPresent(ref::set);                 // one set of an already-validated object
}

Q49 · Scenario. "The full test suite passes on our x86 CI machines. A customer running the same build on AWS Graviton reports corrupted records, roughly one in a hundred thousand. Nothing in the code uses native memory. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: correct on x86 and corrupt on ARM at a low rate is the fingerprint of a missing ordering constraint. x86 keeps stores in order and loads in order, so much racy code works by accident there. AArch64 does not, so the same code exposes its race. I would treat this as a memory-model bug until proven otherwise.
  2. Evidence:
    • The shape of the corruption: records with some fields new and some old, or zeroed fields in an object that was clearly created, point at publication; wrong counts point at lost updates; a missing element in a hand-off structure points at a queue built on plain fields.
    • Get an ARM machine, an m7g instance is enough, and run the suite in a loop under load, because a one-in-a-hundred-thousand rate needs volume rather than cleverness.
    • Grep the codebase for every hand-off between threads that uses a plain field or a plain array element rather than a volatile, an atomic, a lock or a concurrent collection.
  3. Ranked causes:
    • An object published through a plain field, the Q47 pattern.
    • A hand-written ring buffer or queue whose head and tail indices are plain ints.
    • A double-checked lock without volatile.
    • A "flag plus data" pair where the flag is volatile but the data is read before the flag, which is the acquire ordering reversed.
  4. Fix:
    • For each hand-off, make the publishing store a release and the consuming load an acquire, which in plain Java means a volatile field, an AtomicReference, or VarHandle.setRelease paired with getAcquire.
    • Write a jcstress test for each suspect and run it on the ARM box until the forbidden outcome disappears.
  5. Prevention: run at least the concurrency-sensitive part of CI on AArch64, which on GitHub Actions or an ARM runner costs very little; ban plain-field hand-offs in code review; and keep the jcstress tests as the regression suite for the lock-free code.

Picture it a lock-free hand-off drawn as two stores, and the order each architecture lets the consumer see them.

The setup: a hand-written single-producer, single-consumer ring buffer with a plain index, the kind that passes on x86.

Ring.javaruns offline
final long[] buf = new long[1024];
int tail;                                       // ❌ TRAP: plain field, written by producer, read by consumer
int head;                                       // consumer only

void put(long v) { buf[tail & 1023] = v; tail++; }              // producer: data store, then index store

long take() {                                                    // consumer
    while (head == tail) { Thread.onSpinWait(); }                // sees new tail...
    return buf[head++ & 1023];                                   // ...but maybe not the data written before it
}

Make the invisible visible: the two stores and the order each architecture lets the consumer see them.

store order per architectureruns offline
producer program order:   (1) buf[0] = 99      (2) tail = 1
x86 (TSO)    consumer sees: (1) then (2)         ✓ reads 99
AArch64      consumer may see: (2) then (1)      ✗ tail == 1 but buf[0] still 0

The trace: one row per step.

thread interleavingruns offline
step  producer                    consumer (AArch64)
1     buf[0] = 99   (sits in a store buffer)
2     tail = 1      (becomes visible first)
3                                 head == tail? no, tail is 1
4                                 reads buf[0] -> 0          ✗ corrupted record

What you see: records with zeroed fields, at a rate of about one in a hundred thousand.

consoleruns offline
# illustrative output
x86  : 100000000 records, 0 corrupt
ARM  : 100000000 records, 1023 corrupt   (first corrupt: id=48211, payload=0)

Why: the index store is not ordered after the data store for other cores.

The fix: make the index a release store and the consumer's read an acquire load.

Ring.javaruns offline
private volatile int tail;                      // ✅ FIX: volatile write is a release, read is an acquire
// or: static final VarHandle TAIL = ...;  TAIL.setRelease(this, t + 1);  TAIL.getAcquire(this);

What you see now: no corrupt records on ARM.

consoleruns offline
# illustrative output
ARM  : 100000000 records, 0 corrupt

Land it x86 forgives ordering bugs and ARM charges for them, so a difference between the two is evidence of a race, not of a hardware fault.

Likely follow-ups
"You fixed the obvious publication sites and the corruption rate dropped but did not reach zero. What next?"

Then I have fixed some races and missed one, so I need a locating tool rather than a reading tool.

I would enable JFR with jdk.JavaMonitorEnter and thread-allocation events to see which threads touch the corrupted object type, and add a cheap integrity check at the consuming site that records the stack when a torn record is detected.

In parallel I would run the suite on the ARM box with -XX:TieredStopAtLevel=1, which turns off C2's aggressive reordering; if the rate changes, compiler reordering is involved and -XX:+PrintCompilation narrows down which methods.

I would also try the Thread Sanitizer style approach of inserting VarHandle.fullFence() after each suspect store, one at a time, and observing which fence makes the corruption vanish.

fence bisectionruns offline
// ❌ suspect store, one at a time
this.lastWriter = id;
VarHandle.fullFence();      // ✅ FIX candidate: if the corruption stops with THIS fence, this is the racy hand-off
"Why is x86 so much more forgiving? Be specific."

x86 implements total store order. Each core has a store buffer, so a store can be delayed past a later load from a different address, but stores from one core leave the buffer in order, and loads are not reordered with other loads.

That means a writer's constructor stores reach memory before its reference store, and a reader's loads of the reference and then a field come back in order, so publication works without any fence.

AArch64 permits store-store, load-load, and load-store reordering unless stlr, ldar or a dmb barrier is used. HotSpot emits those only for volatile, acquire and release accesses. So the same bytecode is correct on x86 by luck and racy on ARM by design.

"How would you run jcstress on the customer's platform type?"

I would generate a test project from the Maven archetype org.openjdk.jcstress:jcstress-java-test-archetype, write the test with two @Actor methods over the suspect hand-off, and build it with mvn clean verify, which produces a self-contained jcstress.jar. On the Graviton instance I run java -jar target/jcstress.jar -t MyHandoffTest -m quick for a first pass and without -m quick for the full stress run, which forks several virtual machines with different compiler settings. The report lists every observed outcome with counts and marks any that my @Outcome annotations declared FORBIDDEN in red, and that report is what I would attach to the bug.

jcstress reportruns offline
# illustrative output
Observed state   Occurrences   Expectation   Interpretation
0, 0                 412,880   FORBIDDEN     torn hand-off          <- the bug
1, 1           1,904,226,311   ACCEPTABLE    fine
"Could the bug be in a library rather than in our code?"

It could, and the same method finds it. Well-known libraries such as Netty, Disruptor and the JDK itself run jcstress on ARM and are reliable; a small in-house or little-used library with a hand-written lock-free structure is the more likely suspect.

I would look for classes in the dependency tree that use sun.misc.Unsafe, AtomicIntegerFieldUpdater or VarHandle, since those are the places where someone chose to manage ordering by hand, and I would write jcstress tests against their public operations.

If a library is at fault, the short-term fix is often to replace it with a JDK concurrent collection, accepting a small throughput cost.

Q50. "How does the just-in-time compiler actually reorder your code? Give me the classic example, and tell me how you would prove the compiler did it and not the CPU."

Reveal answer

The real test Whether you separate compiler reordering from hardware reordering and know the flags that isolate each.

Strong answer The just-in-time compiler, meaning HotSpot's C1 and C2 tiers that turn hot bytecode into machine code, treats a non-volatile field like any other memory that only this thread can see. That licence produces three common transformations:

  1. Hoisting: in while (!stop) { work(); } with a plain boolean stop, C2 reads the field once before the loop, keeps the value in a register, and compiles the loop as if (!stop) while (true) work();. The thread never sees another thread's write, forever.
  2. Store reordering: two stores to different plain fields can be emitted in either order, or a store can be sunk past a later load, which is the raw material of the publication bug.
  3. Common subexpression elimination: two reads of the same plain field with no intervening write are merged into one, so code that reads a flag, does something, and reads it again to check for a change is compiled as a single read.

The CPU then adds its own reordering on top, through store buffers and out-of-order execution, but that layer is smaller on x86 and larger on ARM.

The tell-tale sign of compiler reordering is timing: the bug appears only after the loop has run enough iterations to trigger compilation, roughly 60,000 back-edges for C1 and about 40,000 more for C2, so a program "works for ten seconds and then hangs".

To prove it was the compiler and not the CPU:

  1. Run with -XX:+PrintCompilation and watch for the line naming the looping method with a percent sign, which marks on-stack replacement, and see that the hang begins right after it.
  2. Run with -Xint, the interpreter only; if the bug disappears, the compiler caused it.
  3. -XX:TieredStopAtLevel=1 distinguishes C1 from C2.
  4. -XX:CompileCommand=exclude,com.acme.Worker::run confirms the single method.

The fix is to make the field volatile, which forbids all three transformations for that field.

The frequency difference is the operational point. A reordering that occurs once in a hundred thousand runs on x86 will pass every test you own and then occur several times a minute on ARM under production load.

Picture it the store-then-load pair at the hardware and compiler level, with the counts that separate the two.

The setup: the classic store-then-load pair and its jcstress test, in the two code blocks below.

the classic reordering, and what it looks like on real hardwareruns offline
// ❌ TRAP: both threads see values that no sequentially consistent execution allows.
class Reordering {
    int x = 0, y = 0;
    int r1, r2;

    void thread1() { x = 1; r1 = y; }    // write then read
    void thread2() { y = 1; r2 = x; }

    // Possible results for (r1, r2):
    //   (0,1) (1,0) (1,1)  -- all explicable by interleaving
    //   (0,0)              -- IMPOSSIBLE under sequential consistency,
    //                         and observable on real hardware
}
// Two independent mechanisms produce (0,0):
//   COMPILER: the write and the read touch different variables, so the JIT may
//             swap them — legal, because a single thread cannot tell.
//   HARDWARE: the store sits in the core's store buffer and is not yet visible
//             to the other core when its load executes. This is StoreLoad
//             reordering, and x86 permits exactly this one despite being TSO.

// ✅ FIX is a StoreLoad barrier on both sides — which is what a volatile
// WRITE emits:
volatile int x = 0, y = 0;    // now (0,0) is forbidden
proving it, rather than arguing about itruns offline
# jcstress is the JDK's own concurrency stress harness. It runs the pair
# billions of times across cores and reports which outcomes actually occurred.
# It is the only honest way to settle "can this reorder?" questions.

@JCStressTest
@Outcome(id = "0, 0", expect = ACCEPTABLE_INTERESTING, desc = "reordered!")
@Outcome(               expect = ACCEPTABLE)
@State
public class StoreLoadTest {
    int x, y;
    @Actor public void a1(II_Result r) { x = 1; r.r1 = y; }
    @Actor public void a2(II_Result r) { y = 1; r.r2 = x; }
}

# On x86 the (0,0) outcome appears in the order of 1 in 100,000 runs.
# On AArch64 it is far more frequent — which is the practical reason to
# run concurrency tests on ARM as well as x86.

Make the invisible visible: the two independent layers that can both produce (0,0).

where the reordering happensruns offline
HARDWARE (store buffer):
  core 1:  x = 1 -> [store buffer]      r1 = y -> reads memory: 0
  core 2:  y = 1 -> [store buffer]      r2 = x -> reads memory: 0      => (0,0)

COMPILER (hoisting, same transformation family):
  source:    while (!stop) { work(); }
  emitted:   if (!stop) while (true) work();       // read hoisted out of the loop

The trace: the (0,0) outcome as a time-ordered table.

thread interleavingruns offline
step  Thread 1                    Thread 2
1     x = 1  (buffered)           y = 1  (buffered)
2     r1 = y -> 0                 r2 = x -> 0           ✗ (0,0): impossible if sequentially consistent
3     stores drain                stores drain          (too late)

What you see: the jcstress counts and the compilation line that marks the hoist.

consoleruns offline
# illustrative output
x86    (0, 0)           1,204 / 100,000,000     <- StoreLoad, allowed even on x86
AArch64 (0, 0)         88,310 / 100,000,000
  8123  412 %  s!  4   com.acme.Worker::run @ 14 (60 bytes)     <- OSR line, hang starts right after

Why: a plain field tells both the compiler and the hardware that no other thread is looking, so each may reorder or cache freely.

The fix: volatile fields, which add the StoreLoad barrier and forbid hoisting.

Reordering.javaruns offline
volatile int x = 0, y = 0;     // ✅ FIX: (0,0) now forbidden
volatile boolean stop;         // ✅ FIX: the loop re-reads it every iteration

What you see now: no (0,0) outcome, and the loop ends.

consoleruns offline
# illustrative output
x86     (0, 0)      0 / 100,000,000
AArch64 (0, 0)      0 / 100,000,000

Land it A plain field is a promise to the compiler that nobody else is looking, and the compiler collects on that promise the moment the code gets hot.

Likely follow-ups
"Why does the bug not appear in the interpreter or in C1?"

The interpreter executes each bytecode as written, so every getfield really loads from memory, and the hardware cache coherence protocol delivers the other thread's write within nanoseconds.

C1 is a fast compiler that does little optimisation across loop iterations, so it also re-reads the field each time.

C2 builds a full data-flow graph, notices the field has no writes inside the loop and no volatile or synchronisation to force a reload, and hoists the load out as a loop-invariant. The bug is therefore a C2 optimisation working exactly as designed.

That is why -Xint and -XX:TieredStopAtLevel=1 are diagnostic tools and not fixes: they hide the race instead of removing it.

"Does calling a method inside the loop prevent the hoisting?"

Only if the compiler cannot see inside the method. If work() is inlined, which happens for anything under 35 bytecodes or any hot method under 325, C2 sees that it does not write stop and hoists anyway.

If the call is not inlined, C2 must assume the callee might write any field, so it reloads after the call. A native call or a Thread.sleep also forces a reload.

Relying on this is fragile, because a later refactoring that shrinks work() makes it inlinable and reintroduces the bug. It is a common reason why "adding a print statement fixed it".

"What is on-stack replacement and why is it relevant here?"

On-stack replacement, OSR, is how HotSpot starts using compiled code for a loop that is already running in the interpreter. When the back-edge counter crosses Tier3BackEdgeThreshold, 60,000 by default, and later Tier4BackEdgeThreshold, 40,000 more, the compiler produces a special version of the method that can be entered in the middle of the loop, and the interpreter frame is swapped for it. It matters here because the stop-flag loop never returns, so the ordinary invocation counter never triggers compilation; OSR is the only way the loop gets compiled, and the % marker in -XX:+PrintCompilation output identifies exactly that event and its timing.

"Is there a cheaper fix than volatile if the loop is extremely hot?"

The volatile read is already a plain load on x86 and an ldar on AArch64, so it is rarely the bottleneck.

If profiling shows it is, the VarHandle opaque mode is the minimal fix: STOP.getOpaque(this) forbids the compiler from hoisting or merging the read while adding no ordering with respect to other fields, so it is a plain load on every architecture.

The trade-off is that opaque gives no guarantee about when the write becomes visible other than "eventually", which is fine for a stop flag and wrong for publication. I would also reconsider checking the flag every iteration; checking every 1,024 iterations amortises the cost to nothing.

opaque stop flagruns offline
private static final VarHandle STOP = ...;          // looked up once for the field "stop"
while (!(boolean) STOP.getOpaque(this)) {            // ✅ FIX (cheap): not hoisted, no extra ordering
    work();
}
Drill · VarHandles, reordering & lock-free structures

This group tests whether you can pick the weakest memory ordering that is still correct, recognise cache-line effects from a latency graph, and build or test a lock-free structure without hand-waving.

Q51 · Scenario. "A worker thread never notices its boolean stop flag. It only happens in production, only after the service has been up for about ten seconds, and never in the unit tests. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: a thread that loops forever on a flag another thread set, with a delay before it starts misbehaving. The delay is the clue: something changes about ten seconds in, and the thing that changes in a Java process at that point is that hot loops get compiled by C2, the optimising tier of the just-in-time compiler.
  2. Evidence:
    • Confirm the loop is spinning with a thread dump, jcmd <pid> Thread.print, showing the worker in RUNNABLE inside its loop.
    • Restart with -XX:+PrintCompilation and watch for a line naming the worker's run method with a % marker, which means the loop was compiled through on-stack replacement. The hang should start right after that line appears.
    • Run once with -Xint, interpreter only. If the flag now works, the compiler is the cause, and the unit tests pass because a short test never runs the loop long enough to reach the compilation threshold.
  3. Ranked causes:
    • The flag is a plain non-volatile field, so C2 hoisted the read out of the loop.
    • The flag is volatile but the loop reads a cached copy through a local variable or a getter that the compiler inlined.
    • The loop body is fully inlined so no call forces a reload.
    • Less likely, the setter thread is itself blocked and never sets the flag.
  4. Fix:
    • Declare the field volatile boolean stop, which forbids the compiler from hoisting or merging the read, or use an AtomicBoolean if the shutdown must also be a compare-and-set.
    • Use Thread.interrupt() as the stop signal where the loop blocks on I/O or sleeps, because the interrupt rule gives the same visibility and also wakes the blocked call.
  5. Prevention: a static analysis rule flagging non-volatile fields written by one thread and read in a loop by another, which Error Prone and IntelliJ both approximate; a soak test in CI that runs long enough to hit C2, at least a minute under load; and a team convention that every cross-thread flag is volatile or atomic, no exceptions.

Read why it takes time to appear. The bug needs the loop to become hot enough for C2 to compile it, which is why it survives every test and every canary and then shows up on a server that has been running for hours.

Picture it the stop-flag loop as written and as C2 emits it, with the timeline that explains the ten-second delay.

The setup: the worker with a plain running flag and both fixes, in the code below.

the stop flag the worker never seesruns offline
// ❌ TRAP: BROKEN — and it usually works in development, which is the trap.
class Worker implements Runnable {
    private boolean running = true;          // NOT volatile

    public void run() {
        while (running) { doWork(); }        // may loop for ever
    }
    public void stop() { running = false; }
}

// WHY IT ONLY FAILS IN PRODUCTION, AFTER A WHILE:
// Interpreted and C1 code re-reads the field each iteration, so it works.
// Once the loop is hot, C2 compiles it, proves `running` is never written
// INSIDE the loop, and hoists the read out — a legal transformation for a
// non-volatile field:
//
//     if (running) { while (true) { doWork(); } }     // what C2 may emit
//
// The thread is now in a genuinely infinite loop. It is not a "stale cache"
// so much as a compiler transformation the memory model permits.

// ✅ FIX 1 — volatile. Forbids hoisting, guarantees visibility.
private volatile boolean running = true;

// ✅ FIX 2 — interruption, which is the idiomatic answer and also unblocks
// a thread that is waiting rather than spinning.
public void run() {
    while (!Thread.currentThread().isInterrupted()) {
        try { doWork(); }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();   // restore the flag
            return;
        }
    }
}
public void stop() { thread.interrupt(); }

Make the invisible visible: the loop as the source states it, and as C2 may emit it.

what the compiler generatesruns offline
// source
while (running) { doWork(); }

// C2, after proving doWork() never writes `running` and the field is not volatile
if (running) {
    while (true) { doWork(); }      // ❌ the flag is never read again
}

The trace: one row per step, main thread and worker.

thread interleavingruns offline
t      main                         worker
0 s                                 loop runs interpreted: re-reads running each time  ✓
10 s                                loop hot -> C2 compiles it, hoists the read
12 s   worker.stop(): running=false
12 s+                               still in while(true)                              ✗ never stops

What you see: a thread dump with the worker still running, and the OSR line.

consoleruns offline
# illustrative output
"worker-1" #31 prio=5 cpu=11902.55ms elapsed=15.2s tid=0x00007f.. nid=0x2f3a runnable
   java.lang.Thread.State: RUNNABLE
	at com.acme.Worker.run(Worker.java:12)

  9874  431 %  s!  4   com.acme.Worker::run @ 2 (22 bytes)     <- OSR compile, hang starts here

Why: for a non-volatile field the memory model lets C2 read it once.

The fix: volatile or interruption, as in the code above.

What you see now: the worker exits shortly after stop().

consoleruns offline
# illustrative output
12.001 s  stop() called
12.002 s  worker-1 exited loop
(thread dump at 15 s: no worker-1 thread)

Land it The bug appears when the code gets fast because the compiler was told nobody else reads the flag, and volatile is how I tell it otherwise.

Likely follow-ups
"You made it volatile and it still hangs. What next?"

Then the loop is not reading the volatile. The first thing I check is a local copy: boolean running = !stop; while (running) … reads the field once by construction, and no keyword fixes that.

The second is a wrapper: the loop calls isRunning() on a different object that cached the flag at construction.

The third is that the loop is not in the place I think; a thread dump shows the real frame, and if it is inside a blocking call such as queue.take() the flag is never checked at all, and the fix is interrupt() or a poison-pill message.

The fourth is that the setter never ran, which a log line in the setter settles in one restart.

flag read once by constructionruns offline
boolean running = !stop;           // ❌ TRAP: read ONCE; volatile on `stop` cannot help
while (running) { doWork(); }
// ✅ FIX: while (!stop) { doWork(); }   // re-reads the volatile each iteration
"Why did the tests not catch this, and how do you write one that would?"

Because the test started the worker, set the flag within a few milliseconds, and the loop was still running in the interpreter, which reloads the field every iteration.

To trigger C2 the loop must complete around 100,000 iterations before the flag is set, so the test needs to let the worker spin for a second or two, or the whole test class must run with -XX:CompileThreshold lowered via a JVM argument in the build.

The honest test is a jcstress test, or a JUnit test that spins the worker for two seconds, sets the flag, and asserts termination within 100 milliseconds. It is slow, so I tag it as a soak test and run it nightly.

"What does the compiled loop actually look like?"

With -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly and the hsdis plugin, the original loop compiles to a single load of the field before the loop label, a compare, and then a tight loop containing only the body and an unconditional jump back, with no memory access to the flag at all. After adding volatile, the load moves inside the loop, and on x86 it is still a plain mov from the object's field offset, so the cost is one L1 cache hit per iteration. That is the whole difference: one instruction, in or out of the loop.

loop in assemblyruns offline
# illustrative output
plain field:     mov  0x10(%rsi),%r10d     ; load once, BEFORE the loop
                 test %r10d,%r10d
         L1:     ... doWork() body ...
                 jmp  L1                   ; no read of the flag
volatile field:  L1: mov 0x10(%rsi),%r10d  ; load inside the loop
                 test %r10d,%r10d ; je exit ; ... ; jmp L1
"Would Thread.interrupt() be a better shutdown signal here?"

Usually yes. The interrupt flag is managed by the virtual machine, so its visibility is guaranteed by the memory model's interrupt rule without me declaring anything.

It also wakes a thread blocked in sleep, wait, join, a BlockingQueue operation, or an interruptible channel, which a boolean cannot do.

The loop becomes while (!Thread.currentThread().isInterrupted()), and any catch of InterruptedException must restore the flag with Thread.currentThread().interrupt() before continuing, which is the mistake people make. Executors use interrupts for shutdownNow(), so a worker that honours interrupts also plays well with pools.

Q52. "Walk me through the VarHandle access modes: plain, opaque, acquire/release and volatile. What does each promise, and how do the AtomicLong methods map onto them?"

Reveal answer

The real test Whether you can choose a weaker mode deliberately and explain what you gave up.

Strong answer java.lang.invoke.VarHandle, added in JDK 9, is a typed handle to a field, static field or array element that lets me choose the memory ordering of each access. There are four strengths.

Plain, get and set, is an ordinary field access with no guarantees beyond what the compiler wants; bitwise atomicity is not even promised for long and double.

Opaque, getOpaque and setOpaque, promises that the access really happens, is bitwise atomic, and that all opaque accesses to that one variable are seen in a single coherent order, so a write becomes visible eventually and cannot be hoisted out of a loop; it says nothing about ordering with other variables.

That is the right mode for a stop flag or a progress counter read by a monitor thread.

Acquire/release, getAcquire and setRelease, adds one-directional ordering: everything the writer did before setRelease is visible to a reader after a matching getAcquire, but a release does not stop later accesses from moving above it.

That is publication at its cheapest, and it is what the JDK's queues use internally. Volatile, getVolatile and setVolatile, is the full sequentially consistent mode, identical to the volatile keyword: the write is a full fence on x86.

There are also explicit fences, VarHandle.loadLoadFence(), storeStoreFence(), acquireFence(), releaseFence() and fullFence(), for cases where the access I want to order is a plain array write. The atomic classes expose the same set: AtomicLong.setPlain, setOpaque, setRelease, set for volatile, and getPlain, getOpaque, getAcquire, get for reads.

Read-modify-write operations come in strengths too:

  • Volatile: compareAndSet and getAndAdd.
  • Witnessed value: compareAndExchange returns the value it saw.
  • Weaker ordering: compareAndExchangeAcquire and compareAndExchangeRelease.
  • No ordering: weakCompareAndSetPlain may fail spuriously, which is useful inside a retry loop.
the four VarHandle access modes, from weakest to strongestruns offline
class Buffer {
    private static final VarHandle SEQ;
    static {
        try { SEQ = MethodHandles.lookup()
                .findVarHandle(Buffer.class, "sequence", long.class); }
        catch (ReflectiveOperationException e) { throw new ExceptionInInitializerError(e); }
    }
    private long sequence;

    void modes() {
        // PLAIN — no ordering, no atomicity guarantees beyond the access itself.
        // Identical to a normal field read/write. The compiler may reorder freely.
        long a = (long) SEQ.get(this);
        SEQ.set(this, 1L);

        // OPAQUE — atomic and guaranteed to make progress (the write WILL become
        // visible eventually; the read is not hoisted out of a loop). No ordering
        // with respect to OTHER variables. Use for a progress/stop flag where you
        // need visibility but not a barrier.
        long b = (long) SEQ.getOpaque(this);
        SEQ.setOpaque(this, 2L);   // ❌ TRAP: does not publish earlier writes to other variables

        // ACQUIRE / RELEASE — one-directional ordering, and the sweet spot for
        // most lock-free code. A release-store is not reordered with EARLIER
        // writes; an acquire-load is not reordered with LATER reads.
        // Cheaper than volatile: no StoreLoad barrier.
        long c = (long) SEQ.getAcquire(this);
        SEQ.setRelease(this, 3L);   // ✅ FIX for publication: pair it with getAcquire

        // VOLATILE — full sequential consistency, including StoreLoad.
        // The strongest and the most expensive.
        long d = (long) SEQ.getVolatile(this);
        SEQ.setVolatile(this, 4L);

        // Plus the atomic updates:
        SEQ.compareAndSet(this, 4L, 5L);
        SEQ.getAndAdd(this, 1L);
    }
}

Release/acquire is where the real wins are. A single-producer queue needs the producer's write to be a release and the consumer's read an acquire — which orders the data against the index without paying for the StoreLoad barrier that volatile forces on every write.

Picture it a producer handing a payload to a consumer through a flag, first with opaque access (broken), then with release/acquire (correct).

The setup: the flag is written with setOpaque and the payload is a plain field.

opaque flag, plain payloadruns offline
class Handoff {
    int data;                       // plain payload
    int ready;                      // flag, accessed through the VarHandle READY
    void producer() {
        data = 42;
        READY.setOpaque(this, 1);   // ❌ TRAP: opaque orders nothing relative to 'data'
    }
    void consumer() {
        if ((int) READY.getOpaque(this) == 1) {
            System.out.println(data);   // may print 0
        }
    }
}

Make the invisible visible: this table lists what each mode promises, which is the hidden contract.

What each access mode promises
ModeAtomic and not hoistedOrders earlier writes before itTotal order with other volatiles
Plain (get/set)NoNoNo
OpaqueYes, one coherent order per variableNoNo
Acquire/releaseYesYes, for a matching release/acquire pairNo
VolatileYesYesYes

The trace: the interleaving the opaque version allows.

thread interleavingruns offline
step  Producer                     Consumer
1     data = 42           (plain)
2     READY.setOpaque(1)
3                                  READY.getOpaque() -> 1   ✓ flag seen
4                                  read data -> 0           ✗ allowed: no edge from step 1 to step 4

What you see: a jcstress-style outcome count where the stale payload shows up.

outcome table, opaque versionruns offline
# illustrative output
outcome (ready, data)   count        meaning
0, 0                    41,200,000   flag not yet seen
1, 42                   18,700,000   correct
1, 0                           312   ✗ flag seen, payload stale

Why: opaque only guarantees the flag itself behaves coherently; it creates no happens-before edge to the payload.

The fix: write the flag with release and read it with acquire.

release/acquire flagruns offline
data = 42;
READY.setRelease(this, 1);                 // ✅ FIX: everything above is published first
// reader:
if ((int) READY.getAcquire(this) == 1) {
    System.out.println(data);              // Result: always 42
}

What you see now: the same outcome table with the bad row gone.

outcome table, release/acquire versionruns offline
# illustrative output
outcome (ready, data)   count        meaning
0, 0                    40,900,000   flag not yet seen
1, 42                   19,100,000   correct
1, 0                             0   ✓ forbidden outcome never observed

Land it I start with volatile, prove with a profiler that the fence matters, and only then step down to release/acquire or opaque with a jcstress test guarding the step.

Likely follow-ups
"Show me how you obtain and use a VarHandle."

I look it up once in a static initialiser and keep it in a static final so the compiler can inline the access:

private volatile long tail;
private static final VarHandle TAIL;
static {
  try {
    TAIL = MethodHandles.lookup()
        .findVarHandle(Ring.class, "tail", long.class);
  } catch (ReflectiveOperationException e) {
    throw new ExceptionInInitializerError(e);
  }
}
// producer:  TAIL.setRelease(this, t + 1);
// consumer:  long t = (long) TAIL.getAcquire(this);

The field is declared volatile so a plain access somewhere else does not accidentally weaken it. Array elements use MethodHandles.arrayElementVarHandle(long[].class) and take the array and index as arguments.

"What does release/acquire cost compared with volatile on each architecture?"

On x86, a release store and a volatile store differ by one instruction: the volatile store is followed by a lock addl full fence, roughly 20 to 40 cycles and a store-buffer drain, while the release store is a plain mov, because total store order already provides release semantics.

Loads are plain in both modes.

On AArch64, release and volatile stores both compile to stlr, and acquire and volatile loads both compile to ldar; the difference is that a volatile store followed by a volatile load needs an extra barrier to prevent the store-load reorder, which release/acquire does not.

So the saving is real on x86 for writers and small on ARM, and it is only measurable inside a tight producer loop.

"When is opaque enough and when is it dangerous?"

Opaque is enough when the variable stands alone: a stop flag, a statistics counter that a monitoring thread samples, a progress indicator. It guarantees the read really happens and the write really lands, in a coherent per-variable order.

It is dangerous the moment the variable is a signal about other data, such as "the buffer is ready", because opaque gives no ordering between the flag and the buffer, and the reader can see the flag before the buffer contents.

The rule I use is: if the reader will go on to read anything else after seeing the value, I need at least acquire on the read and release on the write.

"Why does weakCompareAndSet exist if it can fail for no reason?"

On architectures that implement compare-and-swap with load-linked and store-conditional pairs, older ARM and PowerPC among them, a store-conditional can fail because of an unrelated cache event, and the strong version has to loop internally to hide that.

If my code is already in a retry loop, which every CAS-based update is, the internal loop is wasted work, so the weak version lets me use a single attempt per iteration. On x86 the two compile to the same lock cmpxchg.

The plain variant additionally drops the memory ordering, which is right for updating a counter whose value nobody reads for publication. AtomicLong.getAndAdd compiles to lock xadd on x86, which is why it beats a CAS loop for counters.

Q53 · Design. "Design a lock-free queue between exactly one producer thread and exactly one consumer thread, tuned for a hot path. I want to hear which memory modes you use and why."

Reveal answer

Strong answer Requirements: one producer, one consumer, bounded capacity, no locks, no allocation per element, offer and poll in the low tens of nanoseconds, and correctness on AArch64 as well as x86. Assumptions: the single-producer single-consumer constraint is enforced by ownership, not checked at runtime.

Design: a power-of-two array, Object[] buffer of size 2k, with two long indices that only ever increase, head owned by the consumer and tail owned by the producer; the slot for an index is index & (capacity - 1), so no modulo and no wraparound handling for two hundred years at a billion elements a second.

Each index is written only by its owner and read by the other side, so plain stores are safe for the owner's own cached copy and I need exactly one ordering per direction.

The producer writes the element into the slot with a plain array store, then publishes with TAIL.setRelease(this, t + 1); the release guarantees the element store is visible before the new tail.

The consumer reads TAIL.getAcquire(this), and if it is ahead of its head, reads the slot with a plain load, nulls it, and publishes HEAD.setRelease(this, h + 1) so the producer knows the slot is free.

Each side keeps a cached copy of the other's index and only re-reads with acquire when the cached value says full or empty, which turns most operations into no cross-core traffic at all.

The two indices and the two cached copies live on separate 64-byte cache lines, either with padding fields or with @Contended and -XX:-RestrictContended, because otherwise every producer write invalidates the consumer's line.

Batching: the consumer drains up to N elements per acquire, and the producer can publish once per batch.

Trade-offs: the queue is unbounded in index arithmetic but bounded in slots; nulling slots costs a store but lets the garbage collector reclaim elements; there is no blocking, so callers spin or back off.

What I would not do: compare-and-swap on both ends, which is the multi-producer design and costs a lock cmpxchg per operation for no benefit here; use ArrayBlockingQueue, which takes a lock; or use volatile for both indices, which puts a full fence in the producer.

Picture it an eight-slot ring with its two indices, the single release/acquire edge per element, and the cache-line layout that keeps the two cores apart.

The setup: offer and poll, with one owner per index.

SPSC offer and pollruns offline
boolean offer(Object e) {
    long t = tail;                          // plain: only the producer writes tail
    if (t - cachedHead >= buffer.length) {  // looks full: refresh with acquire
        cachedHead = (long) HEAD.getAcquire(this);
        if (t - cachedHead >= buffer.length) return false;
    }
    buffer[(int) (t & mask)] = e;           // plain store of the element
    TAIL.setRelease(this, t + 1);           // ✅ publish: one release
    return true;
}
Object poll() {
    long h = head;                          // plain: only the consumer writes head
    if (h >= cachedTail) {                  // looks empty: refresh with acquire
        cachedTail = (long) TAIL.getAcquire(this);
        if (h >= cachedTail) return null;
    }
    int i = (int) (h & mask);
    Object e = buffer[i];                   // plain load, safe after the acquire
    buffer[i] = null;                       // let the GC reclaim it
    HEAD.setRelease(this, h + 1);           // tell the producer the slot is free
    return e;
}

Make the invisible visible: the ring, with the indices counting up forever and the mask folding them onto slots.

memory pictureruns offline
capacity 8, mask 7           slot = index & mask
slot:     0    1    2    3    4    5    6    7
        [ A ][ B ][ C ][ . ][ . ][ . ][ . ][ . ]
          ^head=0       ^tail=3        size = tail - head = 3
consumer polls A, B  -> head=2, slots 0 and 1 nulled      size = 1
producer reaches index 8 -> slot 0 again (8 & 7); full when tail - head == 8

line 0: [ head | cachedTail | padding ........ ]   written by the consumer only
line 1: [ tail | cachedHead | padding ........ ]   written by the producer only

The trace: the one edge that makes the element visible.

call traceruns offline
Producer                                Consumer
buffer[t & mask] = e      plain store
TAIL.setRelease(t + 1)    --release--+
                                     +-> TAIL.getAcquire() -> t + 1     acquire
                                         e = buffer[h & mask]           ✓ sees e
(if the edge were missing)               tail seen, slot still null     ✗ reordering allowed

Why: the release store orders the element write before the new tail, and the acquire load orders the tail read before the element read, so each direction needs exactly one edge.

Land it Single ownership of each index turns the whole queue into one release per publish and one acquire per observe, and everything else is cache-line hygiene.

Likely follow-ups
"Change the requirement: now there are eight producers. What changes?"

The tail is no longer singly owned, so producers must claim a slot with TAIL.compareAndSet(this, t, t + 1) or, better, getAndAdd, which is a single lock xadd on x86 and avoids the retry loop.

But claiming a slot and filling it are now two steps, so the consumer cannot trust the tail alone; each slot needs its own sequence number, written with release after the element, and the consumer reads the slot's sequence with acquire and waits until it matches.

That is the Disruptor and JCTools MpscArrayQueue design. The consumer side stays single-owned and unchanged. Throughput per producer drops because eight cores now bounce the tail's cache line, so I would also batch claims: getAndAdd(this, 16) once and fill sixteen slots.

"What would you cut under time pressure?"

I would cut the whole implementation and use JCTools SpscArrayQueue, which is exactly this design, battle-tested and jcstress-verified, and costs one dependency.

If a dependency is not allowed, I would cut the cached index copies and the batching and ship the plain release/acquire version with padding, since it is correct and already several times faster than a lock.

I would keep the power-of-two mask and the padding because they are a few lines each.

I would not cut the jcstress test that checks the consumer never sees a null element after observing the tail advance, because it is the only thing standing between me and the Graviton bug in Q49.

"Why release/acquire instead of volatile? Prove it is still correct."

The correctness argument needs exactly one edge per direction. Producer: element store, then release store of tail. Consumer: acquire load of tail, then element load.

The memory model treats a release write that is observed by an acquire read as synchronizes-with, so the element store happens-before the element load. The reverse direction is the same with head.

Volatile would additionally order the producer's tail store before its own subsequent loads, which the producer never needs, because it only reads head with acquire when the queue looks full and a stale head only makes it think the queue is fuller than it is, which is safe.

So volatile adds a full fence on x86 for a guarantee no code path depends on.

"How does the consumer wait when the queue is empty?"

It depends on latency versus CPU budget. For the lowest latency it spins with Thread.onSpinWait(), which emits the x86 pause instruction so the core does not saturate its pipeline; that costs a whole core.

A middle ground spins a few hundred iterations, then yields, then parks for a microsecond with LockSupport.parkNanos, which is the JCTools WaitStrategy idea.

For a thread-per-core design with many queues I would give the consumer a list of queues and let it round-robin rather than block on one.

Whatever the strategy, the producer never needs to wake the consumer, because there is no lock and no condition; that is what keeps the producer path allocation-free and fence-free.

Q54. "What is false sharing, how bad can it get, how do you detect it, and where does the JDK itself guard against it?"

Reveal answer

The real test Whether you can explain the cache coherence mechanism, quantify the cliff, and name the annotation and its flag.

Strong answer A processor cache moves memory in lines of 64 bytes on every mainstream x86 and AArch64 chip.

The coherence protocol, MESI or a variant, allows only one core to hold a line in the modified state at a time; when another core writes to the same line it has to take ownership, which invalidates the first core's copy and costs a round trip through the shared cache, roughly 50 to 100 nanoseconds.

False sharing is when two threads write to different variables that happen to sit in the same line. Neither thread reads the other's variable, so there is no logical sharing, but the hardware bounces the line back and forth on every write.

Two counters in adjacent fields, each incremented by its own core, run at perhaps a tenth of the speed they would have alone, and the effect scales badly: with eight writers to one line the throughput can fall thirty to fifty times, which shows up as a cliff when a workload moves to a machine with more cores.

Detection is by experiment or by hardware counters. The experiment is to add 64 bytes of padding around the suspect field and re-measure; if throughput jumps, that was it.

The counter approach on Linux is perf c2c record followed by perf c2c report, which lists cache lines with high "HITM" counts, meaning loads that hit a line modified in another core's cache, along with the offsets and the code addresses touching them.

There are two fixes in Java:

  • Manual padding: six or seven unused long fields on either side of the hot field, arranged so the compiler cannot remove them.
  • @jdk.internal.vm.annotation.Contended: HotSpot pads the field or the whole class to ContendedPaddingWidth, 128 bytes by default.

Outside the JDK the annotation is ignored unless I run with -XX:-RestrictContended and compile with --add-exports java.base/jdk.internal.vm.annotation=ALL-UNNAMED. The JDK uses it on java.lang.Thread for the thread-local random fields, on ForkJoinPool's work queues, on Striped64.Cell which underlies LongAdder, and on ConcurrentHashMap.CounterCell.

false sharing, and the padding that fixes itruns offline
// A cache line is 64 bytes. Two fields that are independent to your program
// but adjacent in memory live on ONE line — so a write by core A invalidates
// core B's copy, even though B only touches the other field.
// The result is a ping-pong of cache-line ownership: correct, and very slow.

class Counters {
    volatile long producerCount;    // ❌ TRAP: same 64-byte line...
    volatile long consumerCount;    // ...as this one
}
// Result: two threads, no shared data logically, and throughput collapses by 5-10x.

// ✅ FIX 1 — @Contended. The JVM inserts padding for you.
class Counters {
    @jdk.internal.vm.annotation.Contended volatile long producerCount;
    @jdk.internal.vm.annotation.Contended volatile long consumerCount;
}
// Requires -XX:-RestrictContended for application classes.

// ✅ FIX 2 — manual padding, which is what the JDK did before @Contended.
class PaddedCounter {
    volatile long value;
    long p1, p2, p3, p4, p5, p6, p7;    // 7 * 8 = 56 bytes -> next field is a new line
}

// WHERE THE JDK GUARDS AGAINST IT ITSELF:
//   java.util.concurrent.atomic.Striped64  (the base of LongAdder) —
//     its Cell class is annotated @Contended, which is precisely why LongAdder
//     beats AtomicLong under contention.
//   ConcurrentHashMap's CounterCell, and ForkJoinPool's work queues.
detecting it rather than guessingruns offline
# The signature: high CPU, low instructions-per-cycle, and a huge number of
# cache-coherence events. perf shows it directly on Linux:
perf stat -e cache-misses,cache-references,LLC-load-misses -p <pid>

# The specific counter for cache-line ping-pong on Intel:
perf c2c record -p <pid>      # then:
perf c2c report               # names the exact cache line and the two offsets

# In a JMH benchmark, the giveaway is that adding a thread makes total
# throughput go DOWN rather than up.

perf c2c is the tool worth naming — it reports the specific cache line being contended and the field offsets sharing it, which turns "maybe false sharing" into a definite answer with the two field names attached.

Picture it two counters sharing one 64-byte cache line, the ownership ping-pong between two cores, and the throughput before and after padding.

The setup: the Counters class in the code below, with producerCount and consumerCount declared next to each other and each written by its own thread.

Make the invisible visible: the two fields land inside the same line.

memory pictureruns offline
one 64-byte cache line (bytes 0-63)
| header 12 B | pad 4 | producerCount 8 B | consumerCount 8 B | neighbouring data ... |
                        ^ Core A writes     ^ Core B writes     (offsets illustrative)

The trace: what the coherence protocol does on every write.

cache-line ping-pongruns offline
step  Core A (producer thread)                    Core B (consumer thread)
1     writes producerCount: line Modified in A
2                                                 writes consumerCount: A's copy -> Invalid
3     writes producerCount: B's copy -> Invalid   ✗ line travels back (about 50-100 ns)
4                                                 writes consumerCount: line travels again   ✗

What you see: a two-thread JMH run with adjacent fields.

JMH, adjacent fieldsruns offline
# illustrative output
Benchmark                  Mode  Cnt    Score   Unit
Counters.adjacent (2 thr)  thrpt   5     95.3  ops/us

Why: the unit of transfer is the line, not the field, so unrelated writes still fight over ownership.

The fix: @Contended or manual padding, exactly as in the code above.

What you see now: the same benchmark with padded fields.

JMH, padded fieldsruns offline
# illustrative output
Benchmark                  Mode  Cnt    Score   Unit
Counters.padded   (2 thr)  thrpt   5    610.8  ops/us

Land it If a per-thread structure gets slower when I add cores, I check the cache line before I check the algorithm.

Likely follow-ups
"Why 128 bytes of padding when the line is 64?"

Because modern Intel cores have an adjacent-line prefetcher that treats two consecutive 64-byte lines as a 128-byte pair and pulls in the neighbour on a miss, so two hot fields 64 bytes apart can still contend through the prefetcher.

Padding to 128 bytes on both sides is the conservative choice and is what ContendedPaddingWidth defaults to. On AArch64 the line is 64 bytes on most cores but some server chips use 128, so the same default covers them.

The cost is memory: a padded object carries about 256 bytes of dead space, which is why I only pad a handful of hot objects and never elements of a large array.

"How do you keep the compiler or the garbage collector from defeating manual padding?"

HotSpot lays out fields by size and may reorder them, so seven padding longs declared after the hot field may not land after it in memory.

The reliable trick, used by JCTools and the Disruptor, is inheritance: put the padding fields in a superclass, the hot field in a subclass, and more padding in a further subclass, because HotSpot keeps superclass fields before subclass fields.

Reading and writing the padding in a dummy method prevents dead-field elimination, which C2 does not currently do for instance fields but a future one could.

Compact object headers in JDK 25 and later shrink the header from 12 to 8 bytes and shift all offsets, so I re-verify the layout with the JOL tool after any JDK upgrade.

"Where does false sharing hide in ordinary application code?"

The classic hiding places are an array of per-thread counters where thread i writes counts[i], which packs eight longs into one line, and a small object with a hot mutable field next to a hot read-only field, where readers of the read-only field are slowed by writers of the other. Thread pools that write a per-worker statistics object allocated in a loop are another, because consecutive allocations in one thread's allocation buffer are adjacent in memory. The array case is fixed by spacing indices sixteen apart or using LongAdder; the object case by moving the mutable field into its own padded object.

"What does the perf c2c output actually show you?"

The report has two tables. The first ranks cache lines by the number of shared-modified hits, with the physical address and the count.

The second, for each line, breaks it down by offset within the line, the symbol and source line of the load or store, the thread and the core.

False sharing shows up as one line with several distinct offsets, each written from a different thread and none read by the others.

For Java, the symbol resolution needs a perf map, which I produce with -XX:+UnlockDiagnosticVMOptions -XX:+DumpPerfMapAtExit or jcmd <pid> Compiler.perfmap, so the table names compiled methods rather than raw addresses.

perf c2c report, schematicruns offline
# illustrative output, simplified
Shared cache line 0x7f3a2c001040   HITM 18,230
  offset 0x00   writer thread: producer   Counters.producerCount
  offset 0x08   writer thread: consumer   Counters.consumerCount
two offsets, two writers, no reader of the other's field  -> false sharing

Q55 · Scenario. "A ring buffer between a producer thread and a consumer thread delivers a steady 200 nanoseconds per element on a 16-core box. We moved it to a 96-core machine and the latency tripled and became spiky. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. The symptom is a two-thread structure getting slower with more cores, which the algorithm cannot explain, so the cause is in how the two threads share hardware. The two usual suspects are false sharing of the head and tail indices and NUMA, non-uniform memory access, where the two threads land on different processor sockets and every cache-line transfer crosses the interconnect.
  2. Evidence: lscpu for the socket and NUMA layout; perf c2c record -p <pid> for a few seconds and perf c2c report to see whether one cache line carries both indices with high shared-modified counts; perf stat -e node-load-misses,node-loads or the numastat counters for cross-node traffic; and a run with both threads pinned to two cores on the same socket using taskset, which separates the NUMA effect from the layout effect in one experiment.
  3. Ranked causes: head and tail, or their cached copies, sharing a 64-byte line, which was tolerable when the two cores shared an L2 and is expensive when they share only an L3 or nothing; the two threads scheduled on different sockets, so every line transfer is a remote hop of 100 to 200 nanoseconds; the buffer array itself allocated on one socket's memory while the consumer runs on the other; and the operating system migrating threads between cores, which explains the spikes.
  4. Fix: pad head, tail and the cached indices onto separate lines with the inheritance-padding pattern or @Contended with -XX:-RestrictContended; pin the producer and consumer to two sibling cores on one socket with taskset or a thread-affinity library; allocate the buffer from the consumer's thread on that socket, or run the process with numactl --cpunodebind=0 --membind=0; and batch publications so fewer line transfers happen per element.
  5. Prevention: a JMH benchmark of the queue run on the target machine class before promotion, with the -prof perfnorm profiler recording cache misses per operation; a layout check with JOL in a unit test asserting the index fields are at least 128 bytes apart; and a deployment note that this service pins its hot threads.

Picture it the producer and consumer placed on two sockets, what that costs per element, and the experiment that separates the NUMA effect from the layout effect.

Make the invisible visible: where the two threads and the buffer sit.

thread placementruns offline
# illustrative output
$ lscpu | grep -i numa
NUMA node(s):        2
NUMA node0 CPU(s):   0-47
NUMA node1 CPU(s):   48-95

socket 0 (node0)                                  socket 1 (node1)
 core 3:  producer     <---- interconnect ---->    core 70: consumer
 buffer[] allocated here                           each line transfer: 100-200 ns

The trace: the arithmetic behind the tripled latency.

cost per elementruns offline
16-core box, both threads share a cache:   about 200 ns per element
96-core box, threads on different sockets:
  element line crosses the link   +  up to 200 ns
  index line crosses the link     +  up to 200 ns
  total                           ~  600 ns      matches "tripled"

What you see: three runs of the same benchmark, which isolate the cause.

taskset experimentruns offline
# illustrative output
run                                      ns/element   p99 ns
unpinned, 96 cores                              610     2400
pinned same socket (taskset -c 2,3)             210      260
pinned different sockets (taskset -c 2,50)      600      700

The fix: pin both threads to one socket and keep the memory there.

pinningruns offline
numactl --cpunodebind=0 --membind=0 java -jar service.jar   # whole process on node 0
taskset -c 2,3 java -jar service.jar                        # or just two sibling cores

What you see now: the same table after pinning plus padded indices.

after the fixruns offline
# illustrative output
run                                      ns/element   p99 ns
pinned same socket + padded indices             205      240

Land it A bigger machine spreads two threads further apart in the cache hierarchy, so a structure that was quietly sharing a line pays the full price of the distance.

Likely follow-ups
"You padded the indices and pinned the threads and latency is still spiky. What next?"

Then the spikes come from something other than the queue.

I would look at garbage collection first with -Xlog:gc*,safepoint, because a young collection pauses both threads and a 96-core box often gets a much larger default heap and therefore longer pauses; a fixed young size or ZGC removes that.

Second, safepoints unrelated to garbage collection, such as biased-lock revocation on old JDKs or JIT deoptimisation, which the safepoint log shows. Third, the operating system: transparent huge page compaction and CPU frequency scaling both create spikes, and perf sched shows involuntary context switches.

Fourth, the elements themselves: if each element is a freshly allocated object, allocation-buffer refills and card-marking traffic differ on the larger machine.

"How does NUMA change the cost of a cache-line transfer, with numbers?"

Within one socket, two cores sharing a line go through the shared last-level cache, typically 40 to 80 nanoseconds per transfer on current server parts.

Across sockets the line has to travel over the interconnect, whether UPI on Intel or Infinity Fabric on AMD, and the cost is 100 to 200 nanoseconds and more variable.

A queue element costs at least two transfers, the element line and the index line, so a remote placement adds a few hundred nanoseconds per element, which matches "tripled" from 200 to 600.

On AMD parts with multiple core complexes even one socket has an L3 per complex, so pinning to the same complex matters as well as the same socket.

"Would the JDK's own queues have had this problem?"

ArrayBlockingQueue would have hidden it under lock cost, which is why it was slower to begin with. ConcurrentLinkedQueue allocates a node per element and its head and tail are already on separate lines by luck of object layout, but it has no padding guarantee. LinkedTransferQueue similarly.

None of the JDK queues pad, because the JDK does not want to spend 256 bytes per queue. The specialised libraries do: JCTools pads every index, and the Disruptor pads its sequences.

So the JDK queues are correct and reasonably fast, but a hand-off measured in nanoseconds is exactly the case where a padded library queue earns its place.

"How would you reproduce this on a laptop without a 96-core box?"

I can reproduce the false-sharing half, not the NUMA half.

A JMH benchmark with two threads, one writing the queue's head and one its tail, run twice, once with the fields adjacent and once padded, shows the ratio on any multi-core laptop; on a typical laptop the padded version is three to ten times faster.

Apple silicon is useful here because its AArch64 cores also show the ordering effects. For NUMA I would rent one hour on a two-socket cloud instance, which is cheaper than guessing.

The evidence I want from either run is the per-operation cache-miss count from -prof perfnorm, because it changes by an order of magnitude and does not depend on the exact machine.

Q56 · Scenario. "All tests pass on our x86 CI machines, but a customer running our library on AWS Graviton (ARM) sees occasionally corrupted records. Nothing is platform-specific in the code. Where do you start?"

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: a data race that is benign on one CPU family and harmful on another. x86 has a strong memory model called total store order, where stores become visible in program order and only a store followed by a load can be reordered; AArch64 is weakly ordered, where independent stores and loads can be reordered freely unless the code asks for ordering. Code with a missing happens-before edge can therefore be correct by accident on x86 for years.
  2. Evidence: I ask for the corruption's shape. A record with some fields from the new version and some from the old, or a reader that sees a non-null reference to an object whose fields are still default, is the fingerprint of unsafe publication. I look for plain-field handoffs between threads: a field written in one thread and read in another with no volatile, lock, or concurrent collection in between, and especially objects handed over through a plain array or a plain field of a shared object.
  3. Ranked causes: an object published through a plain field after construction, so the reference becomes visible before the constructor's stores; a producer writing a payload and then a plain "ready" flag, with the reader trusting the flag; a lazily-built cache entry stored in a plain map or array.
  4. Fix: give each handoff an edge. Make the publishing field volatile, or use a VarHandle with setRelease on the writer and getAcquire on the reader, or make the published object's fields final so the freeze rule protects them. Then reproduce on ARM with a jcstress test that models the handoff; a forbidden outcome appearing on the ARM run and not on x86 is the proof.
  5. Prevention: run the concurrency test suite on both architectures in CI, since ARM is now common in clouds and on developer laptops, and review every plain-field handoff in code review as a race until proven otherwise.

Picture it a half-built record that a reader on AArch64 can see through a plain field, and why x86 hides it.

The setup: a record published through a plain field.

unsafe publicationruns offline
class Record { int id; String name; }        // fields are not final
class Holder {
    Record current;                          // ❌ TRAP: plain field, no happens-before edge
    void publish() { Record r = new Record(); r.id = 7; r.name = "a"; current = r; }
    void read()    { Record r = current; if (r != null) use(r.id, r.name); }
}

Make the invisible visible: the order in which stores can become visible on each CPU family.

store visibility orderruns offline
program order of the writer:   (1) r.id = 7   (2) r.name = "a"   (3) current = r
x86 (total store order):       visible as 1, 2, 3   -> a reader that sees (3) also sees 1, 2   ✓
AArch64 (weak ordering):       may become visible as 3, 1, 2                                   ✗

The trace: the interleaving on AArch64.

thread interleavingruns offline
step  Writer                       Reader
1     r.id = 7 (still buffered)
2     current = r  (visible)
3                                  r = current        -> non-null
4                                  read r.id          -> 0   ✗ stale
5     r.id = 7 becomes visible

What you see: the symptom the customer reports.

log lineruns offline
# illustrative output
WARN  record id=0 name=null   (expected id=7 name=a)    only on Graviton, about once per million reads

Why: the JMM promises ordering only through volatile, locks or final fields, and x86 had been supplying it for free.

The fix: give the handoff an edge.

safe publicationruns offline
volatile Record current;                    // ✅ FIX: volatile write/read is the edge
// or: final int id; final String name;     // ✅ FIX: freeze rule protects the fields
// or: CURRENT.setRelease(this, r);  /  (Record) CURRENT.getAcquire(this)

What you see now: the same log after the fix.

log lineruns offline
# illustrative output
(no half-built records; jcstress on aarch64: forbidden outcome count = 0)

Land it x86 was silently giving you ordering the language never promised; ARM takes it away, and the fix is to write the ordering into the code with volatile, release/acquire, or final.

Likely follow-ups
"You added volatile to the obvious field and the customer still sees corruption. What next?"

Then there is a second handoff, or the volatile is on the wrong side.

A volatile flag protects only the writes that happened before the flag write in the writer and the reads after the flag read in the reader; a reader that reads the payload first and checks the flag afterwards is still racy.

I would instrument the customer's build with a jcstress-style probe or, more practically, add assertions that detect a half-built record and log the stack, and I would grep for every field the reader touches that is not covered by the flag's ordering.

Often the culprit is a lazily initialised field inside the published object, written after publication.

reader checks the flag too lateruns offline
Record r = holder.record;        // ❌ TRAP: payload read BEFORE the volatile flag
if (holder.ready) use(r);        // r may already be stale; read the flag first, then the payload
"Why does the JIT not add the ordering for you on ARM?"

Because the compiler implements the Java Memory Model, not the strongest hardware model, and the JMM says a plain access has no ordering with respect to other threads. The compiler emits ordinary loads and stores for plain fields on every platform; on x86 the hardware happens to keep them in order, on ARM it does not. Emitting fences everywhere would make every field access cost what a volatile costs, which is why the language makes you ask for ordering explicitly.

"Which JDK tools help prove it?"

jcstress is the primary tool: it runs a small actor-based test millions of times and reports which outcomes appeared; a forbidden outcome is a proof of the race. On the production side, I would use a JFR recording with jdk.JavaMonitorEnter and thread-park events to see which handoffs are actually synchronised, and the absence of any event around the suspect handoff is itself a hint. There is no runtime race detector for Java equivalent to ThreadSanitizer, which is why the test-based proof matters.

Q57 · Scenario. "Under load, a service's CPU pins at 100 percent and a thread dump shows many threads inside ConcurrentHashMap.computeIfAbsent, none of them making progress. There is no lock in our code. Diagnose."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: threads spinning or blocked inside computeIfAbsent. That method holds a lock on the map's bin (the bucket) for the duration of the mapping function, so a slow or recursive mapping function serialises every thread that hashes into the same bin, and in the recursive case can deadlock or throw.
  2. Evidence: the thread dump stacks show what the mapping function is doing under the bin lock. If the function itself calls computeIfAbsent on the same map, for example a memoised recursive computation, that is the recursive-update case: modern JDKs throw IllegalStateException: Recursive update when they detect it, but under contention the detection can be missed and threads spin, which was the reported hang in older versions. If the function does I/O or a heavy computation, the bin is locked for that long and other keys in the same bin wait.
  3. Ranked causes: recursive computeIfAbsent on the same map; a mapping function that blocks on a remote call; many hot keys colliding in one bin because of a poor hash.
  4. Fix: never compute inside the map. Use the get-then-putIfAbsent pattern: v = map.get(k); if (v == null) { v = compute(k); prev = map.putIfAbsent(k, v); if (prev != null) v = prev; }, which may compute twice under a race but never holds the bin lock during the computation. Or store a CompletableFuture as the value, so the map insert is instant and callers wait on the future outside the lock, which also de-duplicates the work. For memoised recursion, compute the value outside and insert the result.
  5. Prevention: a code-review rule that mapping functions passed to compute* methods must be cheap, pure and non-recursive, and a load test that includes hot keys.

Picture it a memoised recursion that calls computeIfAbsent inside computeIfAbsent on the same map, and the bin lock it holds.

The setup: the classic memoised Fibonacci.

recursive computeIfAbsentruns offline
static final Map<Integer, Long> cache = new ConcurrentHashMap<>();
static long fib(int n) {
    if (n < 2) return n;
    return cache.computeIfAbsent(n,       // ❌ TRAP: bin lock held while the lambda runs
        k -> fib(k - 1) + fib(k - 2));    // ...and the lambda updates the same map
}

Make the invisible visible: the lock the map takes behind the scenes.

bin lock pictureruns offline
table[5]  --> bin 5 (locked by worker-1)  --> node(n=20) --> ...
worker-1: inside computeIfAbsent(20)  holds bin 5, runs lambda -> fib(19) -> computeIfAbsent(19)
worker-2: computeIfAbsent(36), hashes to bin 5  -> waits for worker-1
if fib(19) also maps to bin 5, worker-1 needs the lock it already holds in a half-updated bin

What you see: the thread dump, with the map frame twice in one stack.

thread dumpruns offline
# illustrative output (line numbers vary by JDK)
"worker-1" #21 RUNNABLE
  at java.base/java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1708)
  at Memo.lambda$fib$0(Memo.java:7)
  at java.base/java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1708)
  at Memo.fib(Memo.java:6)

Why: the mapping function runs while the bin is locked, so it must be short and must not touch the same map.

The fix: compute outside the map, then insert.

get, compute, putIfAbsentruns offline
static long fib(int n) {
    if (n < 2) return n;
    Long v = cache.get(n);
    if (v == null) {
        v = fib(n - 1) + fib(n - 2);             // ✅ FIX: no lock held here
        Long prev = cache.putIfAbsent(n, v);
        if (prev != null) v = prev;              // another thread won: use its value
    }
    return v;
}

What you see now: a dump where the stacks are short and the map is only entered briefly.

thread dumpruns offline
# illustrative output
"worker-1" #21 RUNNABLE
  at java.base/java.util.concurrent.ConcurrentHashMap.putIfAbsent(ConcurrentHashMap.java:1541)
  at Memo.fib(Memo.java:10)

Land it computeIfAbsent runs your function under the bin lock, so it must be fast and must never touch the same map; anything slower goes through a future stored in the map.

Likely follow-ups
"You switched to the future pattern and CPU is still pinned. What next?"

Then the spinning is elsewhere, and I go back to the flame graph rather than the thread dump. Common second causes: a HashMap, not a concurrent one, mutated from several threads, which can create a cycle in a bin and make get loop forever; or a hot key whose future never completes because the computation threw and the failure was not propagated, so every caller waits and retries in a loop. The flame graph shows the first as HashMap.getNode at the top with no callees, and the second as callers looping around join.

flame graph, shared HashMapruns offline
# illustrative output
100% cpu  java.util.HashMap.getNode      <- top frame, no callees
          Cache.lookup
          RequestHandler.handle           ✗ plain HashMap mutated from several threads: bin cycle, get loops
"Why is computing twice in the putIfAbsent pattern acceptable?"

Because under a race two threads compute the same value and one result is discarded, which costs one wasted computation and no correctness problem as long as the computation is pure. The alternative, holding a lock during the computation, costs every other thread's progress. If the computation is expensive or has side effects such as a network call, the future pattern gives exactly-once execution without the lock, which is why it is the general answer and putIfAbsent is the cheap one.

"Would a Caffeine cache have this problem?"

Caffeine's get(key, mappingFunction) also runs the function under a per-key lock on the underlying map, so a blocking function still serialises callers for that key, but only that key, and it documents that recursion is forbidden. Its AsyncCache variant stores futures and is the right choice for loaders that do I/O. So the library does not remove the rule, it just makes the future pattern one method call.

Q58 · Design. "Design a single-producer, single-consumer queue in Java that avoids locks and passes tens of millions of items per second between two threads."

Reveal answer

Strong answer Assumptions: exactly one producer thread and one consumer thread, fixed capacity, and the goal is throughput with low latency rather than fairness.

Design: a ring buffer, an Object[] whose length is a power of two so an index maps to a slot with a bitmask instead of a modulo.

Two long counters, head (next slot the consumer reads) and tail (next slot the producer writes), each written by exactly one thread. Because each counter has one writer, no compare-and-set is needed anywhere; ordering is all that matters.

The producer writes the element into the slot with a plain store, then publishes by storing tail with VarHandle.setRelease, which guarantees the element store is visible before the new tail.

The consumer reads tail with getAcquire, reads the slot, then advances head with setRelease; the producer checks head with getAcquire to know whether the ring is full.

Both counters are padded so that head, tail and the array header are on separate 64-byte cache lines, otherwise every push and pop bounces the same line between the two cores and throughput collapses.

Two refinements: each side caches the other's counter locally and only re-reads it when its cached value says the queue is full or empty, cutting cross-core reads by an order of magnitude; and the consumer can drain in batches.

This is the design of Agrona's and JCTools' SPSC queues, and it moves 50–100 million items per second on ordinary hardware.

What I would not do: use compare-and-set on both ends, which is the multi-producer design and costs a cache-line round trip per operation; use volatile everywhere, which adds full fences on x86 the release/acquire pair does not need; or let the queue grow, because an unbounded queue is a memory leak with a delay.

Picture it the four states of the ring as head and tail advance, and the field layout that keeps the two indices on separate lines.

The setup: padding by inheritance, so the JVM cannot reorder the padding away from the hot fields.

padded indicesruns offline
abstract class Pad0 { long p01, p02, p03, p04, p05, p06, p07; }      // 56 B (use 15 for 128 B)
abstract class HeadField extends Pad0 { long head; }                 // consumer writes
abstract class Pad1 extends HeadField { long p11, p12, p13, p14, p15, p16, p17; }
abstract class TailField extends Pad1 { long tail; }                 // producer writes
public final class SpscQueue extends TailField {
    // ✅ FIX: superclass fields are laid out before subclass fields,
    // so head and tail end up at least 64 bytes apart.
}

Make the invisible visible: head and tail for a ring of capacity 4.

ring statesruns offline
capacity 4, mask 3
head tail  tail-head  state
  0    0       0      empty    poll() -> null
  0    3       3      three elements
  0    4       4      full     offer() -> false   (tail - head == capacity)
  2    4       2      slots 0 and 1 are free again; next write is index 4 -> slot 0

The trace: one element, with only the two owners writing.

call traceruns offline
offer(x): t=4, slot=4&3=0, buffer[0]=x, TAIL.setRelease(5)       producer writes tail only
poll():   h=2, TAIL.getAcquire()=5 > h, e=buffer[2], HEAD.setRelease(3)   consumer writes head only
neither side ever writes the other's index  ✓ no CAS needed

Land it One writer per counter means release/acquire is enough; the rest of the design is keeping the two counters off each other's cache lines.

Likely follow-ups
"Requirement change: several producers. What changes?"

tail now has multiple writers, so claiming a slot needs a compare-and-set or a getAndAdd on the tail counter, and the consumer can no longer trust that a slot below tail is filled, because a producer may have claimed it and not yet written it. The standard answer is a per-slot sequence number the consumer waits on, which is the LMAX Disruptor or JCTools MPSC design. Throughput drops to the tens of millions and latency gains a tail under contention; if the producers can be given one SPSC queue each and the consumer polls them round-robin, that is often faster than a true MPSC queue.

"What would you cut under time pressure?"

The cached-counter refinement and batch draining, keeping the ring, the release/acquire pair and the padding, which is a hundred lines and gets most of the throughput. I would not cut the padding, because without it the queue is slower than ArrayBlockingQueue on a busy machine, and I would not cut the jcstress test for the handoff.

"How does the consumer wait when the queue is empty?"

It depends on the latency budget. For the lowest latency it busy-spins with Thread.onSpinWait(), which burns a core but reacts in nanoseconds. A middle ground spins a few hundred times, then yields, then parks with LockSupport.parkNanos in a backoff, and the producer unparks it only when the consumer has signalled that it is parked, using an extra flag so the unpark is not called on every push. For anything not latency-critical, a plain BlockingQueue is the right tool and this design is over-engineering.

backoff ladderruns offline
Object e;
int spins = 0;
while ((e = queue.poll()) == null) {
    if (spins < 200)      { Thread.onSpinWait(); spins++; }    // lowest latency, burns a core
    else if (spins < 300) { Thread.yield(); spins++; }
    else                  { LockSupport.parkNanos(1_000); }    // back off, give the core back
}

Q59 · Design. "Design the mechanism by which a service hot-reloads its configuration so that every request sees one consistent version and nothing is ever seen half-updated."

Reveal answer

Strong answer Requirements: readers on many threads, reloads every few minutes, no locks on the read path, and consistency within a request.

Design: the configuration is an immutable graph, a top-level record whose components are records, lists made with List.copyOf, and maps made with Map.copyOf, so once built nothing in it can change.

The loader builds a complete new graph off to the side, validates it, and publishes it by a single reference swap into an AtomicReference<Config> (or a volatile field).

The swap is the only synchronisation: the write is a release, the read is an acquire, and because every field in the graph is final, the freeze rule guarantees a reader that sees the new reference sees a fully built object.

Each request reads the reference once at its start and carries that Config object through its work, in a ScopedValue on JDK 25 or as a parameter, so the request never mixes two versions even if a reload happens mid-request.

Versioning: each snapshot carries a version number and a load timestamp, logged on publish and exposed in a health endpoint, so an incident can say which version a request saw.

Caches derived from configuration are keyed by that version or rebuilt inside the new snapshot before it is published, never invalidated in place.

Trade-offs: a full rebuild per reload costs memory for two graphs briefly; listeners that want to react to changes must diff old and new, which is deliberate.

What I would not do: mutate the live object's fields in place, which readers could see half-updated; use a lock on the read path; or hold configuration in a ThreadLocal, which pins each thread to whatever version it first saw.

Picture it a reference swap that leaves each request on one config version, next to the mutate-in-place bug it replaces.

The setup: a mutable config updated field by field.

mutable configruns offline
class Config { int timeoutMs; int retries; }          // ❌ TRAP: mutable, shared
Config live = new Config();
void reload(Config n) { live.timeoutMs = n.timeoutMs; live.retries = n.retries; }
void handle() { use(live.timeoutMs, live.retries); }   // can see new timeout with old retries

The trace: a request reading in the middle of a reload.

thread interleavingruns offline
step  Reload thread                Request thread
1     live.timeoutMs = 5000
2                                  reads timeoutMs -> 5000   (new)
3                                  reads retries   -> 3      (old)   ✗ mixed version
4     live.retries = 1

The fix: an immutable graph published through one reference.

immutable snapshotruns offline
record Config(int timeoutMs, int retries, int version) {}   // ✅ FIX: nothing can change
final AtomicReference<Config> ref = new AtomicReference<>(new Config(2000, 3, 7));
void reload(Config n) { ref.set(n); }                        // the only synchronisation
void handle() { Config c = ref.get(); use(c.timeoutMs(), c.retries()); }  // read once

Make the invisible visible: who holds which version across a swap.

reference pictureruns offline
before:  ref --> Config v7  <-- request A (holds v7)
after:   ref --> Config v8      request A still sees v7  ✓   request B (starts now) sees v8  ✓
         Config v7 is garbage once request A finishes

What you see now: a log where every request names one version.

log linesruns offline
# illustrative output
request r-17 config v7 timeout=2000 retries=3
request r-18 config v8 timeout=5000 retries=1      reload happened between r-17 and r-18

Land it Immutable graph plus one atomic reference swap plus one read per request is the whole design; every other approach is a race with a nicer name.

Likely follow-ups
"Requirement change: some config values must change instantly for in-flight requests, for example a kill switch."

Then that value is not part of the snapshot; it is a separate AtomicBoolean read at the point of use, with the understanding that it is the one thing that can change mid-request. I would keep the list of such values very short and document that they are read live. Mixing the two models in one object is what produces the half-updated view the design exists to prevent.

live kill switchruns offline
static final AtomicBoolean KILL = new AtomicBoolean(false);   // read live, never part of the snapshot
void handle() {
    if (KILL.get()) throw new ServiceUnavailable();           // changes mid-request, by design
    Config c = ref.get();                                     // everything else: one snapshot
}
"What would you cut under time pressure?"

The per-request ScopedValue plumbing, which is the invasive part; reading the reference at the top of each handler and passing it down is enough. I would not cut immutability or the single reference swap, because they are the correctness of the design and cost nothing.

"How do you make sure no code keeps an old snapshot forever?"

A leaked reference to an old snapshot is a memory leak of one config graph per reload. I would check with a heap histogram after a few reloads that the count of the top-level record class is one or two, not fifty, and I would make the snapshot's own caches bounded. Long-lived components that need configuration should hold the AtomicReference, not a Config, and read it when they act.

jcmd GC.class_histogramruns offline
# illustrative output, after ten reloads
 num   #instances   #bytes  class name
  41:           2       64  Config        ✓ one or two live
  41:          50     1600  Config        ✗ fifty means something holds old snapshots

Q60. "Why is LongAdder faster than AtomicLong under contention, what does it give up, and when should you not use it?"

Reveal answer

Strong answer AtomicLong.incrementAndGet is a single compare-and-set on one memory word.

When thirty-two threads increment the same word, every operation drags that cache line between cores, and failed compare-and-sets retry, so throughput flattens at a few tens of millions per second regardless of core count and can fall as cores are added.

LongAdder starts as one word and, on the first contention it detects, spreads the updates over an array of cells, each padded with @Contended to its own cache line; each thread hashes to a cell using a per-thread probe value and increments that cell, so threads rarely touch the same line.

The total is the sum of the base and all cells, computed on demand by sum().

What it gives up is a consistent read: sum() is not atomic, so it can miss updates in flight and there is no incrementAndGet that returns an exact value, which means it cannot be used as a sequence generator or for compare-and-set logic.

It also costs memory, up to one cell per core, each 128 bytes with padding, which matters if you have a counter per key in a large map.

When not to use it:

  • You need the returned value.
  • Contention is low, where AtomicLong is just as fast and smaller.
  • The counters are numerous.

The same design underlies LongAccumulator and ConcurrentHashMap's size counting, and it is the technique the striped-counter design questions expect you to describe.

why LongAdder beats AtomicLong, and what it gives upruns offline
// AtomicLong — ONE memory location. Every thread CASes the same cache line.
// Under contention, most CAS attempts fail and retry: the loop spins, and
// throughput falls as threads are added.
AtomicLong counter = new AtomicLong();
counter.incrementAndGet();          // ❌ TRAP under contention: compareAndSet in a loop until it wins

// LongAdder — an ARRAY of cells, one per contending thread (roughly), each
// @Contended so they sit on separate cache lines. Threads hash to different
// cells and almost never collide.
LongAdder counter = new LongAdder();
counter.increment();                // ✅ FIX: CAS on this thread's own cell
long total = counter.sum();         // adds the cells up, on demand

// WHAT IT GIVES UP — and this is the whole trade:
//
// 1. sum() is NOT ATOMIC. It walks the cells while other threads are still
//    incrementing, so the result is a value that may never have existed at
//    any single instant. Fine for a metric, wrong for a limit check.
//
// 2. There is no compound operation. AtomicLong has incrementAndGet,
//    getAndSet and compareAndSet; LongAdder has increment and sum. You cannot
//    ask "increment and tell me the new value" atomically.
//
// 3. More memory: an array of padded cells rather than one long.

// SO: DO NOT use LongAdder when the current value drives a decision.
if (activeRequests.incrementAndGet() > LIMIT) reject();   // MUST be AtomicLong
metrics.requestCount.increment();                          // LongAdder is right

The rule falls out of point 1: LongAdder for counters you only report, AtomicLong for counters you make decisions on — because a rate limiter built on a non-atomic sum will admit more than its limit under exactly the load it exists to control.

Picture it one shared counter word against a striped set of cells, and the check-then-act race that a non-atomic sum() allows.

Make the invisible visible: where the writes land.

memory pictureruns offline
AtomicLong                         LongAdder (after contention is detected)
 [ value ]  <- all 32 threads       base  [ 10 ]
   one cache line                   cells [ c0 ][ c1 ][ c2 ][ c3 ]   each on its own line
                                    thread T7 -> probe hash -> c3
                                    sum() = base + c0 + c1 + c2 + c3

The setup: an admission check built on sum().

limit with LongAdderruns offline
LongAdder inFlight = new LongAdder();
boolean tryAdmit() {
    if (inFlight.sum() >= LIMIT) return false;   // ❌ TRAP: snapshot, not atomic with the increment
    inFlight.increment();
    return true;
}

The trace: sum() walks the cells while a writer keeps going (base 10, c0 5, c1 7, true total 22).

sum() while writers runruns offline
step  sum() thread                 writer thread
1     reads base -> 10
2     reads c0   -> 5
3                                  c0++  (c0 = 6)       true total now 23
4     reads c1   -> 7
5     returns 22                                         ✗ missed the update at step 3

What you see: more requests admitted than the limit.

consoleruns offline
# illustrative output
LIMIT=100  threads=64
peak admitted requests: 117      ✗

The fix: decisions go through an exact atomic.

limit with AtomicLongruns offline
AtomicLong inFlight = new AtomicLong();
boolean tryAdmit() {
    if (inFlight.incrementAndGet() > LIMIT) {   // ✅ FIX: exact value returned atomically
        inFlight.decrementAndGet();
        return false;
    }
    return true;
}

What you see now: the same run.

consoleruns offline
# illustrative output
LIMIT=100  threads=64
peak admitted requests: 100      ✓

Land it LongAdder trades an exact instantaneous value for contention-free writes, so use it for statistics and never for sequences.

Likely follow-ups
"How would you record per-request latency at high throughput without contention?"

Not with a counter but with a histogram, and the same striping idea applies: each thread records into its own HdrHistogram instance, and a reader thread periodically merges them, so the hot path writes to thread-local memory with no atomics at all. Micrometer's timers do a version of this internally. The trade-off is again read consistency: a merged snapshot lags by one merge interval, which is fine for dashboards and SLO reporting, which are what latency histograms are for.

"Does the padding really matter in practice?"

Yes, measurably: without it two adjacent cells share a 64-byte line and updates from two cores contend exactly as if they were one counter. The JDK's Striped64 base class annotates the cell class with @jdk.internal.vm.annotation.Contended, which the JVM honours for its own classes by default; for user classes you must run with -XX:-RestrictContended or pad by hand with unused long fields.

"Why not just use a ThreadLocal counter and sum them?"

You can, and it is even cheaper on the write side, but you then own the problems LongAdder solves: enumerating all threads' values for the sum, handling threads that exit with unsummed values, and, with virtual threads, having a counter per virtual thread, which can be millions. LongAdder bounds the cell count by the core count and does the summing for you.

Drill · Object layout, allocation & the collectors

This group tests whether you can describe what an object physically is in memory, how it gets allocated in a handful of instructions, and what each collector does with it afterwards, precisely enough to predict a pause from a log line.

Q61. "Draw me the layout of a Java object in memory on a 64-bit JVM. What is in the header, why is a heap above 32 GB a problem, and what changed with compact object headers?"

Reveal answer

The real test Whether you know the header is two words with specific bit fields, that compressed pointers are the reason behind the 32 GB rule, and that you can measure a layout rather than guess it.

Strong answer An object starts with a header, then its fields, then padding so the whole thing is a multiple of 8 bytes. The classic header is 12 bytes. The first 8 bytes are the mark word.

It holds the identity hash code once one has been computed, which takes 31 bits, the object's age in 4 bits, meaning how many young collections it has survived, and 2 lock bits that say whether the object is unlocked, thin-locked by a thread, or inflated to a full monitor.

The next 4 bytes are the compressed class pointer, an offset into the compressed class space that says which class this object is. Then come the fields.

The JVM reorders them: longs and doubles first, then ints, then shorts and chars, then bytes and booleans, then references, so that each field sits at its natural alignment with the least padding. References are normally 4 bytes because of compressed oops.

An oop is an ordinary object pointer, and compressing it means storing a 32-bit number instead of a 64-bit address. Below a 4 GB heap the number is the address itself.

Up to 32 GB the JVM stores the address divided by 8, which works because every object is 8-byte aligned, and shifts it back on every load.

Above 32 GB the trick runs out, so pointers become 8 bytes, every reference field and every array of references doubles in size, and a 40 GB heap holds less than a 31 GB heap did.

-XX:ObjectAlignmentInBytes=16 stretches the trick to 64 GB, but every object is now padded to 16 bytes, so small objects waste space.

Compact object headers, JEP 519 as a product feature in JDK 25 behind -XX:+UseCompactObjectHeaders and on by default in JDK 27 through JEP 534, squeeze the class pointer into the mark word and shrink the header from 12 to 8 bytes.

A plain Integer goes from 16 to 16 bytes, because padding still applies, but an object with one int and one reference drops from 24 to 16, and across a real heap that is typically a 10 to 20 percent saving.

The way to know instead of guess is the JOL library, Java Object Layout: ClassLayout.parseClass(Order.class).toPrintable() prints each field's offset and the total instance size.

object layout, measured rather than assumedruns offline
class Point { int x; int y; }        // ❌ TRAP: "two ints, so 8 bytes"? No.

// Use JOL (Java Object Layout) to see the truth:
System.out.println(ClassLayout.parseClass(Point.class).toPrintable());
// Result: 24 bytes, see the JOL output in the next block
what JOL prints on a 64-bit JVM with compressed oopsruns offline
Point object internals:
OFF  SZ   TYPE DESCRIPTION               VALUE
  0   8        (object header: mark)     // identity hash, GC age, lock state
  8   4        (object header: class)    // COMPRESSED class pointer (4, not 8)
 12   4    int Point.x
 16   4    int Point.y
 20   4        (object alignment gap)    // padded to a multiple of 8
Instance size: 24 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total

// So 8 bytes of data cost 24 bytes of heap. The header is the fixed overhead
// on EVERY object, which is why a million small objects is rarely the right shape.

// WHY 32 GB IS A CLIFF: with compressed oops the JVM stores 32-bit references
// and shifts by 3 (objects are 8-byte aligned), addressing 2^32 * 8 = 32 GB.
// Above that, references become 8 bytes:
//   -Xmx31g  -> compressed oops, ~24 bytes/object
//   -Xmx33g  -> 64-bit oops, every reference doubles; effective capacity DROPS
// A 33 GB heap can hold LESS live data than a 31 GB one.

// JDK 24+ shrinks the header itself:
//   -XX:+UseCompactObjectHeaders   // 16-byte header -> 8, saving ~4-8 bytes/object

The 32 GB cliff is the number to remember. Going from 31 GB to 33 GB makes every reference twice as wide, so the heap grows by 2 GB and the amount of live data it can hold falls — which is why heaps are conventionally sized just under the boundary, or moved well past it to 64 GB+ where the extra space outweighs the loss.

Picture it the byte map of Point with the classic and the compact header, the mark word fields, and how a compressed oop becomes an address.

Make the invisible visible: the same object laid out byte by byte.

memory pictureruns offline
classic header (12 B):  | mark 8 | klass 4 | x 4 | y 4 | gap 4 |   = 24 B
compact header (8 B):   | header 8 | x 4 | y 4 |                   = 16 B   (no gap)

mark word, 64-bit, unlocked (simplified):  hash 31 bits | age 4 bits | lock 2 bits | unused

The trace: how a 32-bit reference turns into an address.

compressed oop decoderuns offline
stored 32-bit value      0x00000018
address = value << 3     0x000000C0      ✓ heap up to 2^32 * 8 = 32 GB
-XX:ObjectAlignmentInBytes=16: value << 4  -> 64 GB, but every object pads to 16 B
above the limit: the JVM stores full 8-byte addresses   ✗ every reference doubles

What you see: the same class as JOL prints it with compact headers switched on.

JOL, compact headersruns offline
# illustrative output  (-XX:+UseCompactObjectHeaders)
OFF  SZ   TYPE DESCRIPTION
  0   8        (object header)
  8   4    int Point.x
 12   4    int Point.y
Instance size: 16 bytes

Why: the header shrinks by 4 bytes, which removes the padding gap here.

Land it The header is where the JVM keeps its own bookkeeping, and every byte you save there is multiplied by every object on the heap, which is why the 32 GB boundary and compact headers both matter more than they look.

Likely follow-ups
"What happens to the mark word when I call hashCode() on an object that is currently locked?"

The mark word can hold either the hash or the lock state, not both in the same bits.

If the object is thin-locked, meaning the mark word points at a lock record on the owning thread's stack, and someone calls the identity hashCode(), the JVM has to inflate the lock into a full ObjectMonitor, which is a separate native structure that has room for the displaced mark word including the hash.

That inflation is a one-way trip for the lifetime of that lock, and it is slower than a thin lock. So a class used both as a monitor and as a key in an IdentityHashMap is a small performance smell.

Since JDK 21 the lightweight locking mode stores lock ownership in a per-thread lock stack rather than in the mark word, which reduces this interaction; as of Aug 2026 it is the default mode.

"How would you check whether compressed oops are actually on in a running service?"

The cheapest check is at startup: -Xlog:gc+heap+coops=info prints a line like Heap address: 0x00000000c0000000, size: 1024 MB, Compressed Oops mode: Zero based, Oop shift amount: 3. A shift of 3 means addresses are divided by 8, and mode 32-bit means no shift was needed because the heap fits under 4 GB. On a live process I would run jcmd <pid> VM.flags and look for -XX:+UseCompressedOops and -XX:+UseCompressedClassPointers; if I see -XX:-UseCompressedOops the JVM turned it off because the heap was too large. I can also confirm from JOL output on the same JVM, because a reference field shows as 4 bytes when compression is on and 8 when it is off.

coops checkruns offline
# illustrative output
$ jcmd 4242 VM.flags | tr ' ' '\n' | grep -i compressed
-XX:+UseCompressedOops          ✓ on
-XX:+UseCompressedClassPointers
(a heap above 32 GB shows -XX:-UseCompressedOops)
"Why does new Object() take 16 bytes, and how big is new int[0]?"

With the classic header, Object has a 12-byte header and no fields, and objects must be 8-byte aligned, so it is padded to 16.

With compact headers it is 8 bytes of header and 8 of padding, still 16, which is why compact headers help objects with fields more than empty ones. An array has one extra header field, a 4-byte length.

So int[0] is 12 bytes of header plus 4 bytes of length, 16 bytes total, and the same with compact headers because 8 plus 4 rounds up to 16.

A byte[1] is also 16, and it stays 16 up to 4 elements, which is why storing a handful of bytes in a fresh array per record is so expensive relative to the data.

sizes, classic and compact headersruns offline
object          classic header         compact header
new Object()    12 + 4 pad   = 16      8 + 8 pad       = 16
new int[0]      12 + 4 len   = 16      8 + 4 len + 4   = 16
"Does field reordering mean I cannot control false sharing between fields?"

Mostly yes, and that is deliberate. The JVM groups fields by size to save padding, and it also keeps a superclass's fields before a subclass's, so you can shape layout somewhat through inheritance, but you cannot force two fields apart within one class by declaration order.

The supported tool for hot counters that are written by different threads is @jdk.internal.vm.annotation.Contended, which pads the field or class to a cache line, 128 bytes by default. It only takes effect for JDK classes unless you pass -XX:-RestrictContended. LongAdder and ConcurrentHashMap use it internally.

For application code the practical answer is to put each hot field in its own small object or in a separate cell of a padded array and to verify with JOL that the offsets are where you think they are.

Q62 · Scenario. "A team moved a G1 service from an 8 GB heap to a 40 GB heap on the same flags because they had bigger machines. Throughput dropped and GC time went up. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom decoded: a bigger heap should reduce collection frequency, so more GC time means either each object got bigger, or the collector is doing more work per byte. The number 40 GB is the clue. It is above 32 GB, the limit for compressed oops, ordinary object pointers stored as 32-bit numbers. Above that limit every reference becomes 8 bytes.
  2. Evidence: -Xlog:gc+heap+coops=info at startup, or jcmd <pid> VM.flags on the running process, will show -XX:-UseCompressedOops, meaning the JVM silently turned compression off. A JOL dump of a core domain class on both JVMs shows reference fields at 8 bytes instead of 4. jcmd <pid> GC.class_histogram shows the same instance counts but larger totals for reference-heavy classes such as HashMap$Node and Object[].
  3. Causes, ranked: first, loss of compressed oops, which grows the live set by 20 to 40 percent for pointer-heavy data and doubles the bytes G1 must copy and scan per object. Second, G1 region size: with a 40 GB heap and the target of about 2048 regions, regions become 16 or 32 MB, which changes what counts as humongous and makes the remembered sets, G1's per-region lists of incoming pointers, coarser. Third, the same MaxGCPauseMillis now sizes a proportionally larger young generation, so each young pause copies more. Fourth, NUMA effects on a larger box if -XX:+UseNUMA is off.
  4. Fix: measure the live set first from the after-GC heap size in the log. If it fits, set -Xmx31g and keep compressed oops. If it genuinely needs more, either -XX:ObjectAlignmentInBytes=16, which keeps 32-bit references up to 64 GB at the cost of 16-byte padding, or move to generational ZGC, which never uses compressed oops but is designed for large heaps and pays no per-reference copy cost in pauses. I would also turn on compact object headers with -XX:+UseCompactObjectHeaders on JDK 25 or later to claw back 4 bytes per object.
  5. Prevention: treat 31 GB as a hard step in any sizing policy, and gate heap changes on a load test that reports allocation rate and GC time, not only on whether the service starts.

Picture it the same HashMap$Node with 4-byte and 8-byte references, and the flags and histogram that show the switch.

Make the invisible visible: the node, byte by byte, on the 8 GB and the 40 GB JVM.

memory pictureruns offline
8 GB heap, compressed oops:     | header 12 | hash 4 | key 4 | value 4 | next 4 |        = 28 -> 32 B
40 GB heap, 64-bit references:  | header 12 | hash 4 | key 8 | value 8 | next 8 |        = 40 B   (+25%)

What you see: the flags and the class histogram on the 40 GB process.

jcmd outputruns offline
# illustrative output
$ jcmd 4242 VM.flags | tr ' ' '\n' | grep Compressed
-XX:-UseCompressedOops                  ✗ silently turned off
-XX:+UseCompressedClassPointers

 num   #instances        #bytes  class name   (120 million entries)
   1:   120000000    4800000000  java.util.HashMap$Node     40 B each

Why: above 32 GB the 32-bit reference trick no longer reaches the whole heap, so every reference field doubles.

The fix: stay under the limit if the live set fits.

flagsruns offline
-Xmx31g                      # ✅ FIX: compressed oops stay on
-XX:+UseCompactObjectHeaders # optional on JDK 25+, 12 -> 8 byte header

What you see now: the same output after the change.

jcmd outputruns offline
# illustrative output
-XX:+UseCompressedOops                  ✓
 num   #instances        #bytes  class name
   1:   120000000    3840000000  java.util.HashMap$Node     32 B each

Land it A 40 GB heap can hold less than a 31 GB one, so the decision is never "more memory is free" but "stay under 32 GB, accept 16-byte alignment, or change collector".

Likely follow-ups
"You set -Xmx31g, compressed oops are back, but throughput is still worse than on 8 GB. What next?"

Then the pointer size was not the only cost. I would compare the two GC logs phase by phase with -Xlog:gc+phases=debug.

If Object Copy grew, the young generation is now much larger and each pause copies more survivors; I would cap it with -XX:G1MaxNewSizePercent or accept it.

If Merge Heap Roots or Scan Heap Roots grew, the remembered sets got expensive because the larger old generation has more cross-region pointers; that is a data-shape problem, typically a big cache of small objects, and moving that cache off-heap or to a flatter structure is the real fix.

I would also check -Xlog:gc+cpu for real time much larger than user plus system time, which means the container is CPU-throttled or the box is swapping, because a 40 GB heap on a node without 40 GB of free RAM pages to disk.

gc+phases comparisonruns offline
# illustrative output, one pause on each JVM
                        8 GB      31 GB
Object Copy             9.1 ms    41.7 ms    ✗ larger young generation, more survivors
Merge Heap Roots        0.8 ms     0.9 ms    ✓ remembered sets are not the problem here
"How exactly does the 16-byte alignment trick extend the limit, and what does it cost?"

A compressed oop is the object address shifted right by the alignment's power of two.

With 8-byte alignment the low 3 bits of every address are always zero, so a 32-bit number times 8 covers 32 GB. With 16-byte alignment the low 4 bits are zero, so the same 32 bits cover 64 GB. The cost is that every object is padded to a multiple of 16 bytes.

A 24-byte object becomes 32, a 40-byte object becomes 48. On a typical heap of small objects that is 5 to 15 percent more space, so a 40 GB heap with 16-byte alignment holds about what a 35 GB heap would with 8-byte alignment.

It is a reasonable middle option for heaps between 32 and about 48 GB; beyond that, ZGC with its 64-bit pointers is usually the better trade.

"Would ZGC have avoided this?"

ZGC never uses compressed oops, so an 8 GB ZGC heap already pays the 8-byte reference cost and the move to 40 GB would not change per-object size at all.

What ZGC avoids is the pause cost of copying: it relocates objects concurrently, so pause time does not scale with heap size.

The trade is CPU: concurrent marking and relocation run alongside the application, and ZGC needs headroom, typically 15 to 30 percent above the live set, or it hits allocation stalls.

So for a service that truly needs 40 GB of live data and cares about latency, generational ZGC is the right home. For one that could fit in 31 GB, G1 with compressed oops is cheaper in both memory and CPU.

Q63. "How does new actually allocate memory, why is it so fast, and what number in a GC log tells you how often young collections will happen?"

Reveal answer

Strong answer Almost every allocation goes through a TLAB, a thread-local allocation buffer. Each thread owns a private chunk of eden, the part of the young generation where new objects start life.

Allocating an object is then bump-the-pointer: the JIT-compiled code reads the thread's current TLAB top, adds the object size, checks the result is below the TLAB end, writes the new top back, and fills in the header.

There is no lock and no shared counter, because no other thread can touch this buffer.

The compiled fast path is about ten machine instructions, which is why allocating a short-lived object in Java is cheaper than a malloc call in C.

When the object does not fit, the slow path runs and takes one of three routes:

  1. Retire and refill: the thread retires the current TLAB, wasting whatever tail is left, and takes a new one from eden with a single atomic operation on the shared eden top.
  2. Outside the TLAB: if the object is large compared with the buffer, it is allocated directly in eden.
  3. Collect: if eden itself has no room, the thread requests a young collection.

TLAB size is adaptive: the JVM watches each thread's allocation rate and resizes so that a thread gets about 50 refills per collection, aiming to keep waste under -XX:TLABWasteTargetPercent=1.

-Xlog:gc+tlab=trace shows refills and waste per thread; the JFR events jdk.ObjectAllocationInNewTLAB and jdk.ObjectAllocationOutsideTLAB, and since JDK 16 the cheaper jdk.ObjectAllocationSample, tell me which code allocates. The number that matters is the allocation rate.

If eden is 1 GB and the service allocates 500 MB per second, a young collection happens every two seconds no matter what else I tune.

Young pauses are proportional to survivors, not to eden size, so the lever for fewer pauses is a larger eden or a lower allocation rate, and the lever for shorter pauses is fewer objects surviving.

why allocation is fast, and the number that tells you the rateruns offline
// Allocation is a POINTER BUMP in a thread-local buffer, not a malloc.
// Each thread owns a TLAB (Thread-Local Allocation Buffer) carved out of Eden.
//
//   ptr = tlab.top;
//   if (ptr + size <= tlab.end) { tlab.top = ptr + size; return ptr; }  // ~10 cycles
//   else slowPath();     // get a new TLAB, or allocate directly in Eden
//
// No lock, no free list, no contention — which is why `new` in Java is often
// faster than malloc in C, and why "avoid allocation" advice is frequently wrong.

// The cost is not the allocation. It is the COLLECTION, which is proportional
// to what SURVIVES, not to what was allocated. Short-lived garbage is nearly free.
reading the allocation rate out of a GC logruns offline
[15.234s][info][gc] GC(42) Pause Young (Normal) (G1 Evacuation Pause) 2048M->256M(4096M) 12.456ms
[16.891s][info][gc] GC(43) Pause Young (Normal) (G1 Evacuation Pause) 2048M->260M(4096M) 11.203ms
                                                  |      |     |        |
                                                  |      |     |        +-- pause
                                                  |      |     +-- total heap
                                                  |      +-- occupancy AFTER
                                                  +-- occupancy BEFORE

// ALLOCATION RATE = (heap before this GC - heap after the previous GC) / interval
//                 = (2048 - 256) MB / (16.891 - 15.234) s
//                 = 1792 MB / 1.657 s
//                 ~= 1.08 GB/sec

// PROMOTION RATE = how much survives each cycle = 260 - 256 = 4 MB per GC.
// That is the number that decides whether you will get a full GC: allocation
// rate drives young GC FREQUENCY, promotion rate drives OLD GEN GROWTH.

// A rising after-value across cycles (256 -> 260 -> 271 -> 290...) with no
// plateau is the signature of a leak; a flat one is a healthy service
// whatever the allocation rate is.

Read the two rates separately. A 1 GB/sec allocation rate with 4 MB promoted per cycle is a perfectly healthy service — the garbage dies in Eden and costs almost nothing. It is the promotion rate, not the allocation rate, that predicts full collections.

Picture it eden carved into per-thread buffers, the pointer bump that allocates in them, and how allocation rate sets the young-collection interval.

Make the invisible visible: who owns which part of eden.

memory pictureruns offline
Eden (1 GB)
| T1 TLAB [used=====.....] | T2 TLAB [used==.......] | T3 TLAB [used=========] | free eden ........
                top^   end^
each thread bumps only its own top; a refill takes the next free slice with one atomic operation

The trace: the fast path and the slow path for a 32-byte object.

allocation traceruns offline
tlab.top = 0x1000  tlab.end = 0x2000   size = 0x20
0x1000 + 0x20 = 0x1020 <= 0x2000   ✓ top = 0x1020, return 0x1000     (no lock)
tlab.top = 0x1FF0, size = 0x20:  0x2010 > 0x2000   ✗ slow path: retire TLAB or allocate outside it

What you see: allocation rate against eden size gives the young-collection interval.

young GC intervalruns offline
eden    allocation rate   young GC every
1 GB    500 MB/s          2 s
1 GB    1 GB/s            1 s
2 GB    500 MB/s          4 s     bigger eden, fewer pauses; each pause still costs only the survivors

Land it Allocation is cheap because it is private; the price is paid later in young collections, whose frequency is allocation rate divided by eden size and whose length is the size of what survives.

Likely follow-ups
"Where does the object's memory get zeroed, and does escape analysis change any of this?"

Java guarantees fields start at zero or null, so the memory has to be zeroed. HotSpot zeroes at allocation time inside the fast path, using vectorised stores for larger objects, rather than pre-zeroing eden after each collection, because touching memory twice is more expensive than once.

Escape analysis is the JIT's proof that an object never leaves the compiled method, and when it succeeds the object is scalar-replaced: its fields become local variables in registers and the allocation disappears entirely, so no TLAB space and no zeroing happen.

That is why a small builder or iterator in a hot loop can be free at C2 tier and expensive in the interpreter. -XX:+PrintEscapeAnalysis with diagnostic options unlocked, or the JFR allocation sample showing the site vanish after warm-up, confirms it.

"What does high TLAB waste look like and what causes it?"

In -Xlog:gc+tlab=trace each thread reports its refill count and a waste percentage; the summary line reports the total. Healthy is around 1 percent. High waste comes from three shapes.

Many threads that each allocate a little, such as a large pool of mostly idle threads, each holding a TLAB they barely use, so most of eden is reserved and empty when the collection comes.

A thread that allocates objects just under the TLAB size, so every allocation leaves a large unusable tail. Or a very small eden with a very large -XX:TLABSize that someone set by hand.

The fix is usually to let the adaptive sizing work by removing manual TLAB flags, and for the idle-pool case to reduce thread count or accept it, since each idle TLAB is at most a few hundred kilobytes.

"How would you find the code responsible for a 2 GB per second allocation rate?"

I would record a JFR profile: jcmd <pid> JFR.start duration=60s filename=alloc.jfr settings=profile. Then jfr print --events jdk.ObjectAllocationSample alloc.jfr, or better, open it in JDK Mission Control and use the Memory tab, which groups samples by allocating stack trace weighted by bytes.

The top three frames usually account for most of the rate; typical culprits are string formatting in log statements that are below the enabled level, boxing in a stream over primitives, and per-request byte[] buffers that should be pooled or sized once.

The point of the sampling event is that it is cheap enough to run in production continuously, unlike the older per-TLAB events that fire on every refill.

"Do virtual threads change TLAB behaviour?"

Virtual threads do not own TLABs. A TLAB belongs to the carrier thread, the platform thread from the scheduler's ForkJoinPool that is running the virtual thread at that moment.

So one million virtual threads share the TLABs of a few dozen carriers, and there is no explosion of half-used buffers.

What virtual threads do add is allocation: each time one parks, its stack frames are copied into a jdk.internal.vm.StackChunk object on the heap, and when it resumes they are copied back lazily.

A service with a high park-and-unpark rate therefore sees a higher allocation rate than the same code on platform threads, which shows up directly as more frequent young collections, and that is the number to watch when migrating.

Q64 · Design. "Design the collector choice and heap layout for an in-memory cache node with 64 GB of RAM. The live set is about 45 GB of long-lived byte arrays behind a key index, and the p99 latency goal is 20 ms."

Reveal answer

The real test Whether you reach for "keep the bulk data out of the collector's way" rather than trying to tune a 56 GB Java heap into a 20 ms pause goal.

Strong answer Requirements and assumptions: 45 GB of live data that changes slowly, a 20 ms p99 including everything, 64 GB of RAM of which the operating system and the JVM's own native memory need at least 4 to 6 GB, and a value shape that is mostly large opaque byte arrays with a comparatively small index of keys pointing to them.

Design: I would split the data by what the collector needs to know about it. The byte arrays are bulk data that the garbage collector gains nothing from managing; it only pays to mark and copy them.

So I would store values off-heap, either in java.nio.ByteBuffer.allocateDirect slabs or, on JDK 22 or later, in java.lang.foreign.MemorySegment slabs allocated from an Arena.ofShared(), with my own slab allocator handing out slices and tracking free space. About 50 GB of RAM goes to those slabs.

The index, keys mapped to slab offsets and lengths, stays on a Java heap that I keep under 32 GB so compressed oops apply; for a few hundred million entries that is 4 to 8 GB, so I would set -Xmx12g and run G1 with the default -XX:MaxGCPauseMillis=200 lowered to 10, which G1 can meet on a 12 GB heap with a small live set.

Compact object headers on JDK 25 or later make the index entries smaller still.

Trade-offs: the alternative of generational ZGC with -Xmx56g holding everything on-heap also meets 20 ms, because ZGC pauses are sub-millisecond regardless of heap size.

But 45 GB live in 56 GB is only 20 percent headroom, and ZGC under allocation pressure with thin headroom produces allocation stalls that show up exactly as p99 spikes, and it burns two or more cores on concurrent work permanently.

Off-heap costs me code: a serialiser, an allocator, and fragmentation handling. It buys me a heap the collector can handle trivially and a memory footprint that does not include per-object headers for 45 GB of data.

What I would not do:

  • Parallel GC, because a full compaction of 45 GB is a pause measured in tens of seconds.
  • G1 at 56 GB, which loses compressed oops and makes mixed collections of a 45 GB old generation long and unpredictable.
  • Unsafe for the off-heap layer, since its memory-access methods are deprecated for removal as of JDK 24.

Picture it where the 64 GB goes, and the path of one read from the on-heap index to the off-heap slab.

Make the invisible visible: the memory split.

memory pictureruns offline
64 GB machine
slabs (off-heap)     50 GB   [ 45 GB live + about 5 GB free-list slack ]
heap (-Xmx12g)       12 GB   [ index live 4-8 GB, young generation, headroom ]
OS + JVM native      the rest   (see the budget in the answer)
on-heap ZGC at 56 GB: 56 - 45 = 11 GB headroom, about 20%    ✗ thin

The trace: one read.

read pathruns offline
get("user:42")
 1. heap index:  "user:42" -> (slab 3, offset 0x4A000, length 8192)          small objects, G1 copes
 2. off-heap:    slab 3 [ .... | 8192 value bytes | .... ]                  no GC object per value
 3. return a slice (MemorySegment.asSlice or a ByteBuffer view) or copy out  ✓ nothing for the GC to mark

What you see: what each choice puts in front of the collector.

What the collector has to handle
DesignHeap to managePause shape
Split: index on heap, bytes off-heap12 GB, small live setG1 young pauses of a few ms
Everything on heap, G1 at 56 GB45 GB live, no compressed oopsLong and unpredictable mixed collections
Everything on heap, generational ZGC45 GB live in 56 GBSub-ms pauses, but allocation stalls with thin headroom

Land it Give the collector only the objects it can help with, keep that heap under 32 GB, and put the bulk bytes where no collector ever walks them.

Likely follow-ups
"The requirement changes: values are now small graphs of objects that the cache must deserialise on every read. Does the design survive?"

Partly. Off-heap still holds the serialised bytes, but now every read deserialises into short-lived heap objects, so the allocation rate jumps and young collections become the cost centre.

With G1 on a 12 GB heap that is fine as long as those objects die young, which they do if callers do not cache them; the young pause is proportional to survivors, not to allocation.

What I would add is a measurement of deserialisation cost against a second design: keep the hot subset as live objects on a larger heap with generational ZGC, so hot reads skip deserialisation.

The decision rests on hit ratio and object count: if the hot set is a few gigabytes, a 20 GB ZGC heap with the hot objects live plus off-heap for the cold tail is the better shape.

"What would you cut under time pressure?"

I would cut my own slab allocator and use an existing one.

Netty's PooledByteBufAllocator is a mature off-heap allocator with size classes and arenas, and it is a single dependency; Chronicle Map or a similar off-heap map is another route if I can accept its serialisation model.

I would also cut the split design in the first release and ship generational ZGC with -Xmx56g, -XX:SoftMaxHeapSize=50g and -XX:ConcGCThreads=4, with an alert on the Allocation Stall log line, because it meets the latency goal with no new code and gives me a working baseline.

The off-heap store then becomes the second iteration, justified by measured memory and CPU numbers rather than by theory.

"How would you prove the design meets 20 ms before going to production?"

A load test that reproduces the write rate, because writes are what create garbage and fragmentation, run for at least several hours so that G1 goes through complete concurrent mark cycles and my slab allocator goes through reuse. I would record with JFR continuously and read three things: the jdk.GCPhasePause event distribution, which must stay well under 20 ms at p99.9; -Xlog:safepoint to make sure time-to-safepoint is not the hidden pause; and RSS from the container against the 64 GB limit, with -XX:NativeMemoryTracking=summary confirming that the off-heap slabs are where the memory went. I would also inject one full GC with jcmd <pid> GC.run to know the worst case, which on a 12 GB heap should be a few hundred milliseconds.

"Why keep the index heap at 12 GB rather than as small as possible?"

Because G1 needs room to work.

With the index live set at, say, 6 GB, a 12 GB heap gives it two things: a young generation of a few gigabytes for the churn from reads and writes, and enough free old regions that mixed collections have somewhere to evacuate into.

Squeeze the heap to 8 GB and that unravels. The young generation shrinks. Young collections happen more often. More index entries get promoted before they die. The collector spends its time on mixed collections.

Squeeze further and you get to-space exhaustion, and a full GC.

The rule of thumb for G1 is two to three times the live set. So 12 GB for 4 to 6 GB live is the low end of comfortable — and it still leaves 50 GB for the slabs.

Q65. "Why does a generational collector need a write barrier at all, what is a card table, and how do G1's remembered sets differ from Parallel's card table?"

Reveal answer

Strong answer The generational hypothesis says most objects die young, so it pays to collect the young generation on its own, often, without touching the old generation. The problem is correctness: a young object may be referenced only from an old object.

If the young collection ignores the old generation, it would free that object and leave a dangling pointer. Scanning all of old to find such pointers would defeat the purpose. So the JVM tracks old-to-young pointers as they are created.

Every time compiled code stores a reference into a field, it also runs a few extra instructions, the write barrier.

In Parallel GC the barrier is a card table: the heap is divided into 512-byte cards, there is one byte per card, and the barrier marks the card containing the written field as dirty.

A young collection then scans only the dirty cards of the old generation as extra roots. That barrier is two or three instructions and unconditional, which is why Parallel has the best raw throughput.

G1 needs more, because it collects any set of regions, not only young ones, so it needs to know for each region which other regions point into it. That structure is the remembered set, one per region, holding the cards that contain pointers into this region.

G1's barrier is heavier: it filters out stores that stay within the same region and null stores, then marks the card and enqueues it on a dirty card queue.

Concurrent refinement threads drain those queues in the background and update the remembered sets, so that at pause time G1 can scan only the cards that point into the regions it chose to collect.

There is also a second barrier used during concurrent marking, the SATB barrier, which records the old value of an overwritten reference so that marking sees a consistent snapshot.

JEP 475 in JDK 24 moved the barrier expansion late in the C2 pipeline, which reduced compile-time cost and improved code quality, and JEP 522 in JDK 26 made the G1 barrier cheaper again, which is the main reason G1 throughput has been closing the gap with Parallel; verify the exact mechanism on the JEP page if asked.

Picture it an old object pointing at a young one, the dirty card that records it, and what each collector does with that record.

The setup: the store that creates the old-to-young pointer.

old-to-young storeruns offline
Cache old = ...;                    // already promoted to the old generation
old.latest = new Entry();           // young object reachable ONLY through 'old'

Make the invisible visible: the card table around the store.

card table pictureruns offline
old generation, 512-byte cards:   c5   c6  [c7*]  c8
                                              ^ the store dirties this card
barrier (Parallel):  card_table[field_addr >> 9] = dirty      two or three instructions
young GC roots = thread stacks + dirty old cards

The trace: a young collection without and with the barrier.

collection traceruns offline
without barrier: young GC scans stacks only -> Entry unreachable -> freed -> old.latest dangles   ✗
with barrier:    card c7 is dirty -> scanned -> old.latest found -> Entry copied and kept          ✓

What you see: the two designs side by side.

Parallel against G1
ParallelG1
BarrierMark the cardFilter same-region and null stores, mark the card, enqueue it
StructureOne card tableCard table plus a remembered set per region
Who updates itThe store itselfConcurrent refinement threads
Pause workScan dirty old cardsScan only cards pointing into the chosen regions

Land it The barrier is the tax every reference store pays so that young collections do not have to read the old generation, and G1 pays a higher tax than Parallel to buy the freedom to collect any region.

Likely follow-ups
"What kind of code pays the most for the G1 barrier, and how would you see it?"

Code that stores references at a high rate into long-lived structures: building a large HashMap or a graph of objects that lives in old, updating a cache, or copying reference arrays with System.arraycopy, which must apply the barrier per element.

Primitive stores pay nothing, so a tight loop over long[] is unaffected. To see it I would compare the same benchmark under -XX:+UseParallelGC and G1 with JMH; a gap of 5 to 15 percent on reference-heavy code is typical, and less on JDK 26 or later.

In production the sign is a high rate of concurrent refinement work, visible in -Xlog:gc+refine=debug, and long Merge Heap Roots or Scan Heap Roots phases in pauses, both caused by many cross-region pointers.

"What happens if concurrent refinement cannot keep up?"

The dirty card queues grow. G1 responds in stages. It starts more refinement threads up to -XX:G1ConcRefinementThreads, which defaults to the parallel GC thread count.

If the queues still exceed a threshold, application threads are made to process cards themselves when they enqueue, which slows the mutator directly. Whatever is still queued at the next pause is processed inside the pause in the Merge Heap Roots phase, which lengthens it.

So a sudden spike in pause time after a burst of writes into old-generation structures is often refinement backlog rather than more live data. The log shows it as a large Merge Heap Roots phase with a small Object Copy phase.

refinement backlogruns offline
# illustrative output, one pause after a burst of writes
[gc,phases] GC(87)   Merge Heap Roots: 310.2ms   ✗ queued cards processed inside the pause
[gc,phases] GC(87)   Object Copy: 9.8ms          small copy: not a live-data problem
"How do ZGC and Shenandoah avoid this whole mechanism?"

They are not region-evacuating in pauses, so they do not need to know precisely where incoming pointers are before a pause.

Instead they use load barriers: every reference load checks metadata bits in the pointer, ZGC's coloured pointers, and if the object has moved or is not yet marked, the loading thread fixes the pointer itself.

That converts the "find every pointer into this region" problem into "fix each pointer lazily when it is used".

Generational ZGC, the default since JDK 23, does add a store barrier to track old-to-young pointers, because it collects young separately, but it still relies on load barriers for relocation.

The cost model flips: no card scanning in pauses, but a small charge on every reference load rather than on every store.

Q66 · Scenario. "A G1 service logs humongous allocation warnings and runs young collections every few seconds while the heap graph shows only 30 percent used. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom decoded: G1 divides the heap into regions, 1 to 32 MB each by the classic rule, chosen so there are about 2048 of them. An object of at least half a region is humongous and is allocated directly in the old generation as a run of contiguous regions, never in the young generation. A heap that is 30 percent full but collecting constantly suggests G1 keeps starting collections for a reason other than eden being full, and humongous allocation is exactly that reason: each one can trigger a young collection or a concurrent cycle to free space.
  2. Evidence: the log line Pause Young (Concurrent Start) (G1 Humongous Allocation) is the smoking gun. -Xlog:gc+humongous=debug lists each humongous allocation with its size. -Xlog:gc+heap=debug shows the humongous region count after each collection; if it stays high, they are also surviving. jcmd <pid> GC.heap_info prints the region size so I know the threshold. A JFR allocation profile then names the site.
  3. Causes, ranked: a byte[] or char[] buffer per request that is above half a region, typically reading a whole response body or a file into one array, or a ByteArrayOutputStream that doubles its buffer past the threshold; a large ArrayList or HashMap table being resized, whose backing array is one object; a heap on a small container where regions are 1 MB, so anything over 512 KB counts; a serialisation library that materialises a whole document as one array.
  4. Fix: first the cheap one, raise the region size with -XX:G1HeapRegionSize=16m so the threshold becomes 8 MB and most of these objects become ordinary. Then the real one: stream instead of buffering, read in fixed chunks of 64 KB, and size collections up front so they do not resize. Humongous objects that die quickly are reclaimed at the next young collection through eager reclaim, so making them short-lived helps even before the code fix.
  5. Prevention: an alert on the count of humongous allocations from JFR's jdk.ObjectAllocationSample filtered by size above the region threshold, and a code review rule that any array sized from external input has an upper bound.

Picture it a 3 MB array landing in a 2 MB-region heap, and the young collections it triggers.

The setup: one array per request.

whole body in one arrayruns offline
byte[] body = in.readAllBytes();    // ❌ TRAP: 3 MB array, bigger than half a 2 MB region

Make the invisible visible: the regions, with the threshold.

region pictureruns offline
4 GB heap, region size 2 MB, humongous threshold = 1 MB
idx:   0    1    2    3    4     5     6    7
      [E ] [E ] [S ] [O ] [HS ] [HC ] [O ] [ . ]
E eden  S survivor  O old  HS humongous start  HC humongous continues
3 MB array -> HS + HC = 4 MB, 1 MB wasted; allocated straight into old, never in eden

What you see: the log line with the cause in brackets.

GC logruns offline
# illustrative output
[12.345s][info][gc] GC(31) Pause Young (Concurrent Start) (G1 Humongous Allocation) 1210M->980M(4096M) 9.8ms

Why: G1 treats a humongous allocation as a reason to start collecting, even while the heap is mostly free.

The fix: stream in fixed chunks and keep objects below the threshold.

chunked readruns offline
byte[] buf = new byte[64 * 1024];                  // ✅ FIX: far below 1 MB
int n;
while ((n = in.read(buf)) != -1) sink.write(buf, 0, n);

What you see now: ordinary evacuation pauses.

GC logruns offline
# illustrative output
[40.101s][info][gc] GC(12) Pause Young (Normal) (G1 Evacuation Pause) 1620M->210M(4096M) 8.1ms

Land it G1 is collecting for space it cannot use, and the durable fix is to stop creating single objects the size of a region rather than to give the collector bigger regions.

Likely follow-ups
"You raised the region size to 32 MB and the warnings stopped, but now old-generation occupancy climbs between concurrent cycles and pauses got longer. What next?"

Two things happened. First, the objects that used to be humongous now live in eden and survivor space and get copied like everything else, so young pauses grew with the survivor bytes; that is expected and usually fine.

Second, with 32 MB regions a heap of a few gigabytes has very few regions, so G1's choices become coarse: a single mixed collection evacuates a large fraction of the heap and eden sizing steps in big jumps.

I would look at whether the copying is the cost, in the Object Copy phase, and if so shorten the life of those buffers so they die in eden.

If the coarse region granularity is the cost, I would step back to 8 or 16 MB regions and fix the allocation site instead, because the region size was only a bridge.

"Why does G1 put humongous objects straight into old, and what does that cost?"

Copying a 20 MB array during a young collection is expensive and pointless if the array is going to live for a while, and eden regions are not contiguous, so a large object could not fit in one anyway.

So G1 allocates humongous objects in a dedicated run of contiguous free regions and marks them as old.

The costs: the space after the object in its last region is wasted, so a 17 MB object in 16 MB regions takes 32 MB; the object is never moved, so a heap with many of them fragments; and freeing it depends on either eager reclaim at a young collection, which only works if nothing references it, or on a concurrent cycle.

Since a humongous allocation counts toward old occupancy, it also drives the heap toward the initiating occupancy threshold faster than the live set justifies.

"Would ZGC have this problem?"

ZGC has large pages of its own, but it handles big objects differently: objects above 4 MB go into large pages sized exactly to the object, and the collector does not have a "half a region" rule that changes behaviour discontinuously.

Large objects are never relocated, which is the same as G1, but they do not trigger a collection by themselves; ZGC starts cycles from allocation rate and occupancy. So the symptom of frequent collections at 30 percent occupancy would not appear.

The wasted-tail and fragmentation effects are smaller because pages are sized to fit. It would not, however, remove the underlying cost of allocating and zeroing 20 MB per request, which stays on the allocation rate either way.

Q67. "Explain G1 from regions up: what kinds of collection it runs, when concurrent marking starts, how it meets a pause goal, and what its failure mode is."

Reveal answer

The real test Whether you can name the two collection types and the marking cycle as separate things with separate triggers, and say plainly that the pause goal is met by sizing eden, not by magic.

Strong answer G1 divides the heap into equal regions, 1 to 32 MB by the classic rule, sized so there are about 2048.

A region is eden, survivor, old, or humongous at any moment, and roles change as regions are freed and reused, so the young generation is a set of regions rather than a fixed area. G1 runs two kinds of collection.

A young-only collection evacuates all eden and survivor regions, copying live objects into fresh survivor regions or promoting them to old, and it is the normal, frequent pause.

A mixed collection evacuates the young regions plus a chosen set of old regions with the most garbage; that is where the name garbage-first comes from. Mixed collections need to know how much of each old region is live, which is what concurrent marking provides.

Marking starts when old occupancy crosses the initiating heap occupancy percent, -XX:InitiatingHeapOccupancyPercent, 45 by default, and since JDK 9 adaptive by default so that G1 learns how long marking takes and starts it early enough.

It begins with a young pause marked Concurrent Start, marks concurrently using snapshot-at-the-beginning so that objects live at the start are treated as live even if references change, then pauses briefly for Remark and Cleanup.

After that G1 schedules a few mixed collections, adding old regions whose live fraction is below -XX:G1MixedGCLiveThresholdPercent=85, until the reclaimable garbage falls under -XX:G1HeapWastePercent=5.

The pause goal, -XX:MaxGCPauseMillis=200 by default, is met by sizing: G1 measures how long copying takes per region and chooses how many eden regions to allow before the next collection so that the predicted pause fits.

A low goal therefore means a small eden and frequent collections, not free short pauses.

The failure mode is evacuation failure, logged as To-space exhausted: G1 ran out of free regions to copy into during a pause, has to leave objects in place, and if the heap cannot recover it falls back to a stop-the-world Pause Full (G1 Compaction Pause), a full compaction of the heap that takes seconds on a large heap. -XX:G1ReservePercent=10 keeps regions back to make that rare.

Picture it regions changing roles across a young pause and a mixed pause, and the log line sequence of one full marking cycle.

Make the invisible visible: a mixed collection choosing old regions by live fraction.

region pictureruns offline
before:  [E][E][E][S][O live 90%][O live 20%][O live 15%][O live 88%][F][F]
mixed pause: copy E + S + the two regions below the 85% live threshold
after:   [F][F][F][S'][O live 90%][F][F][O live 88%][F][F]       F = free region

The trace: the log sequence of one cycle.

GC log sequenceruns offline
# illustrative output
GC(10) Pause Young (Normal) (G1 Evacuation Pause)
GC(11) Pause Young (Concurrent Start) (G1 Evacuation Pause)     old crossed IHOP
GC(11) Concurrent Mark Cycle                                    runs beside the application
GC(12) Pause Remark
GC(12) Pause Cleanup
GC(13) Pause Young (Prepare Mixed) (G1 Evacuation Pause)
GC(14) Pause Young (Mixed) (G1 Evacuation Pause)                reclaim old regions

What you see: the failure when marking is too late.

GC log, failureruns offline
# illustrative output
GC(31) Pause Young (Concurrent Start) (G1 Evacuation Pause)
GC(32) Pause Young (Normal) (G1 Evacuation Pause)                 ✗ no Remark yet
GC(33) To-space exhausted                                          ✗
GC(34) Pause Full (G1 Compaction Pause) 15800M->9100M(16384M) 812ms   ✗ stop-the-world

Land it G1 meets its pause goal by controlling how much it copies per pause and relies on marking finishing before the heap fills; when either assumption breaks, the answer is a full GC, and every G1 tuning question is about keeping those two assumptions true.

Likely follow-ups
"What does snapshot-at-the-beginning actually record, and what is the cost of getting it wrong?"

At the start of marking G1 logically takes a snapshot: every object reachable at that instant is considered live for this cycle.

While the application keeps running it may overwrite a reference, and the object that was pointed to might be missed by the marker even though it was live at the snapshot.

To prevent that, the SATB write barrier stores the old value of every overwritten reference into a thread-local buffer, and the marker treats those old values as roots. New objects allocated during marking are considered live by default.

The cost of getting it wrong is that a live object gets freed, which is a crash; the cost of the design is floating garbage, objects that died during the cycle but are kept until the next one, which is why old occupancy right after a cycle overstates the live set.

"Which flags would you touch first on a G1 service, and which never?"

First, -Xmx and -Xms, because most G1 problems are a heap too small for the live set. Second, -XX:MaxGCPauseMillis, understanding that lowering it shrinks eden.

Third, -XX:InitiatingHeapOccupancyPercent only if adaptive IHOP is starting marking too late, which the log shows as marking cycles ending just before full GCs. Fourth, -XX:G1HeapRegionSize for humongous problems.

Almost never: -Xmn or -XX:NewRatio, because fixing the young size disables the pause-goal adaptation that is G1's main feature, and -XX:ParallelGCThreads above the container's CPU quota, which makes pauses longer through contention.

And I would remove any leftover flags from an older collector, since G1 ignores some silently.

"How would you tell from a log that marking is starting too late?"

I would look at the sequence of events with timestamps. Healthy is Concurrent Mark Cycle finishing, a few Pause Young (Mixed) lines, and then occupancy dropping well before the next cycle.

Too late looks like a Concurrent Start, then young pauses with rising occupancy, then To-space exhausted or Pause Full before Remark ever appears, meaning the heap filled while marking was still running.

-Xlog:gc+ihop=debug prints the adaptive threshold and the predicted marking time, so I can see the value it chose. The fixes are either more heap, which gives marking time, or a lower fixed IHOP such as 35, or a faster cycle with more -XX:ConcGCThreads.

gc+ihopruns offline
# illustrative output
healthy:  Concurrent Start -> Remark -> Cleanup -> Pause Young (Mixed) ... occupancy drops
too late: Concurrent Start -> Pause Young ... occupancy rising -> To-space exhausted -> Pause Full
                                                                  ✗ Remark never appeared
"When does G1 promote an object, and why does promoting too early hurt?"

An object is copied between survivor regions on each young collection and its age in the mark word goes up by one. When the age reaches the tenuring threshold, at most -XX:MaxTenuringThreshold=15 and computed adaptively from survivor space, it is promoted to an old region.

If survivor space overflows in a collection, objects are promoted regardless of age; the log shows this as survivor regions at their cap.

Premature promotion means objects that would have died in the next second now sit in old, inflate occupancy, trigger marking sooner, and can only be freed by a mixed collection, which costs far more per byte than a young one.

So a small young generation from an aggressive pause goal quietly moves work from cheap young pauses to expensive mixed ones.

Q68 · Scenario. "A G1 service with a 16 GB heap shows p99 pauses of 800 ms. MaxGCPauseMillis is set to 50. The team's question is why the collector is ignoring the goal. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom decoded: the goal is a target for young and mixed pauses that G1 meets by sizing eden. It is not a limit, and it does not apply to full collections, to remark pauses with heavy reference processing, or to time spent reaching a safepoint. So the first question is which kind of pause is 800 ms, not why the goal is ignored.
  2. Evidence: the GC log with -Xlog:gc*,gc+phases=debug,safepoint:file=gc.log:time,uptime,level,tags. I read the 800 ms lines. If they say Pause Full (G1 Compaction Pause) or carry To-space exhausted, the heap ran out of room. If they are Pause Young with a huge Object Copy phase, survivors are large. If they are Pause Remark, it is reference processing or class unloading. If the safepoint log shows Reaching safepoint taking hundreds of milliseconds, the pause is not GC at all but a thread that will not stop, typically a long counted loop or a large array copy.
  3. Causes, ranked: first, the goal of 50 ms itself: G1 shrank eden to meet it, young collections became very frequent, objects were promoted before they died, old filled, marking started too late and the service hit to-space exhaustion and full GCs. Second, humongous allocations driving old occupancy. Third, a live set close to 16 GB, so there is no room to evacuate. Fourth, time-to-safepoint from a loop the JIT compiled without a safepoint poll. Fifth, CPU throttling in the container, visible in -Xlog:gc+cpu as real time far above user plus system time.
  4. Fix: put the goal back near the default, 200 ms, or at most 100, so eden can grow; that alone often removes the full GCs. Give the heap room, aiming for two to three times the live set measured from occupancy after a mixed collection. If marking finishes too late, set -XX:InitiatingHeapOccupancyPercent=35. For safepoint delays, -XX:+UseCountedLoopSafepoints is on by default since JDK 10, so I would look for the specific loop with -Xlog:safepoint plus a thread dump at the moment.
  5. Prevention: alert on full GC count and on To-space exhausted, not on average pause, and run any pause-goal change through a load test with the log open.

Picture it the chain from a 50 ms goal to an 800 ms full GC, and the log lines at each end of it.

The trace: what the small eden sets in motion.

causal chainruns offline
MaxGCPauseMillis=50  -> eden shrinks to about 400 MB
allocation 1 GB/s    -> young GC every 0.4 s                         ✗ frequent
objects age out      -> promoted before they die -> old fills        ✗
marking starts late  -> heap fills during marking -> to-space exhausted ✗
fallback             -> Pause Full 800 ms

What you see: the log, with after-GC occupancy creeping up until the full collection.

GC logruns offline
# illustrative output
GC(501) Pause Young (Normal) (G1 Evacuation Pause) 9800M->9400M(16384M) 48ms
GC(502) Pause Young (Normal) (G1 Evacuation Pause) 9810M->9470M(16384M) 49ms
GC(503) Pause Young (Normal) (G1 Evacuation Pause) 9900M->9560M(16384M) 49ms
GC(690) Pause Full (G1 Compaction Pause) 16300M->9100M(16384M) 812.4ms        ✗

Why: the goal is met by shrinking eden, and a tiny eden turns short-lived garbage into promoted garbage.

The fix: relax the goal and give the heap room.

flagsruns offline
-XX:MaxGCPauseMillis=200     # ✅ FIX: eden can grow
-Xmx24g                      # two to three times the live set

What you see now: the same log shape.

GC logruns offline
# illustrative output
GC(120) Pause Young (Normal) (G1 Evacuation Pause) 9600M->7100M(24576M) 142ms
GC(121) Pause Young (Normal) (G1 Evacuation Pause) 9650M->7140M(24576M) 139ms     ✓ plateau, no full GC

Land it An aggressive pause goal causes long pauses by starving the young generation, so the fix is usually to relax the goal and enlarge the heap, after first proving which pause type the 800 ms actually is.

Likely follow-ups
"You raised the goal to 200 ms and the heap to 24 GB, full GCs stopped, but there are still 400 ms remark pauses. What next?"

Remark is where G1 finishes marking and processes references and does class unloading. Four hundred milliseconds there points at one of three things.

A large number of java.lang.ref objects, typically weak or soft references from a cache or from a framework's proxies; -Xlog:gc+ref=debug prints counts per reference type and the time spent, and -XX:+ParallelRefProcEnabled is already on by default since JDK 17.

Class unloading with a huge number of loaded classes, which -Xlog:class+unload and jcmd <pid> VM.classloader_stats confirm, common with code that generates classes per request. Or a very large system dictionary from thousands of class loaders.

The fix follows the finding: replace the reference-heavy cache with a bounded one such as Caffeine, or stop the class generation churn.

"How do you tell a GC pause from a safepoint delay in the log?"

With -Xlog:safepoint every safepoint prints a line like Safepoint "G1CollectForAllocation", Time since last: 2 s, Reaching safepoint: 380 ms, At safepoint: 40 ms, Total: 420 ms.

The GC line for the same event reports only the 40 ms, because the collector measures from when all threads have stopped. The 380 ms of reaching is the time-to-safepoint, during which threads that have already stopped wait for the last one.

That last thread is usually in a compiled loop without a poll, in a long JNI call, or in a large System.arraycopy.

So if an observability tool reports 420 ms stalls but the GC log says 40 ms, I trust the safepoint log and go looking for the slow thread rather than tuning the collector.

safepoint against GC logruns offline
# illustrative output
safepoint: Safepoint "G1CollectForAllocation", Reaching safepoint: 380 ms, At safepoint: 40 ms, Total: 420 ms
gc:        GC(77) Pause Young (Normal) (G1 Evacuation Pause) 40ms        <- only the 40 ms
the other 380 ms: one thread that would not stop (counted loop, JNI, big arraycopy)
"Why did lowering the goal make things worse rather than simply failing to be met?"

Because G1 obeys the goal by cutting the number of eden regions it allows. To fit 50 ms it might allow 400 MB of eden on a service that allocates 1 GB per second, so young collections run more than twice a second.

Each one copies whatever is still alive, and an object that lives for a second now survives two or three collections instead of dying in eden, so it ages, gets copied repeatedly, and is promoted.

Old occupancy rises faster than the real live set, concurrent marking starts more often and each cycle has less time before the heap fills. The end state is to-space exhaustion, which is the exact opposite of the 50 ms the team asked for.

G1's own diagnostics show this: the eden size in each pause line is small and the promotion rate is high.

"What would generational ZGC have done with the same workload?"

ZGC has no equivalent knob because its pauses do not depend on the amount copied; they are sub-millisecond, and all copying happens concurrently. With a 16 GB heap and the same allocation rate it would run young collections concurrently and old collections rarely.

The risk moves elsewhere: if the allocation rate outruns the concurrent collector, threads see allocation stalls, logged as Allocation Stall, which look like latency spikes of tens to hundreds of milliseconds. That needs headroom and CPU rather than a pause goal.

So switching to ZGC is a legitimate answer for a 50 ms p99 requirement, provided the service has spare cores and the heap is sized with 20 to 30 percent above the live set.

Q69. "How does ZGC achieve sub-millisecond pauses on a 100 GB heap? Explain coloured pointers, load barriers, what generational ZGC changed, and what ZGC costs you."

Reveal answer

Strong answer ZGC's central idea is that the collector does almost all of its work while the application runs, and the application helps by fixing pointers as it uses them.

A ZGC reference is a 64-bit value in which a few bits are metadata rather than address; these are the coloured pointers.

The colours record whether the object has been marked in the current cycle, whether its pointer has been remapped after a move, and whether it is only reachable through a finaliser.

Every load of a reference from the heap passes through a load barrier, a few instructions the JIT inserts that test the colour bits against the current "good" colour. If they match, nothing happens, which is the fast path.

If they do not, the thread takes a slow path: during marking it marks the object, during relocation it copies the object to its new place or looks up the forwarding table, then writes the corrected pointer back so the next load is fast.

Because every thread heals pointers as it goes, the collector never needs to stop the world to find and update references. The cycle is mark concurrently, pick regions to relocate, relocate concurrently, and remap lazily during the next mark.

The three pauses that remain, at the start of marking, the end of marking and the start of relocation, only synchronise threads and flip the colour, so they are well under a millisecond and do not grow with heap size; ZGC supports heaps up to 16 TB. Generational ZGC, opt-in in JDK 21 and the only mode since JDK 24, adds a young and old generation so that short-lived objects are collected cheaply and often, which cut CPU use and let ZGC sustain much higher allocation rates; it adds a store barrier to track old-to-young pointers.

The costs:

  • No compressed oops, so references are 8 bytes.
  • Load barrier on every reference load, a few percent of throughput.
  • Concurrent GC threads that compete with the application for CPU, set by -XX:ConcGCThreads.
  • Headroom: if allocation outruns the collector, a thread blocks in an allocation stall until space is freed.

-XX:SoftMaxHeapSize tells ZGC to try to stay under a lower figure while keeping -Xmx as the hard limit.

Picture it the load barrier's two paths, a ZGC cycle against the application timeline, and the one log line that says the heap is too small.

The trace: what every reference load does.

load barrierruns offline
p = field                                   load a reference from the heap
colour of p == current good colour  ->  ✓ fast path: use p
otherwise                           ->  ✗ slow path: mark, or relocate / look up forwarding table
                                        write the corrected pointer back, so the next load is fast

Make the invisible visible: the three short pauses between long concurrent phases.

cycle timelineruns offline
application  ====|=========================|=====================|========
GC pauses         ^ mark start (<1 ms)       ^ mark end (<1 ms)    ^ relocate start (<1 ms)
concurrent work:  [ mark ............... ]  [ select ][ relocate ........ ]

What you see: the line that means the collector lost the race.

GC logruns offline
# illustrative output
[88.120s][info][gc] Allocation Stall (http-nio-8080-exec-7) 12.345ms

Why: allocation outran the concurrent collector, so the thread waited for space.

The fix: add headroom or concurrent threads.

sizingruns offline
live set 14 GB   ->  -Xmx20g   (about 30% headroom)     # ✅ FIX
-XX:ConcGCThreads=4                                      # if stalls persist

What you see now: no stall lines during the same spike.

GC logruns offline
# illustrative output
(no "Allocation Stall" lines in the log during the spike)      ✓

Land it ZGC trades a small tax on every reference load and some spare cores for pauses that no longer depend on heap size, which is the right trade when latency and heap are both large and the wrong one when the box is small and CPU-bound.

Likely follow-ups
"How can ZGC keep metadata bits in the pointer when the CPU needs a real address?"

On x86-64, ZGC maps the same physical heap memory at several virtual addresses, one per colour, using multi-mapping, so a pointer with any colour set is itself a valid address into the same memory.

The hardware dereferences it directly; there is no masking on the load path. On AArch64 the same effect is achieved with hardware top-byte-ignore.

Since JDK 21 generational ZGC moved to a scheme where the colour bits sit in the low part of the pointer and the load barrier shifts them out, which needs no multi-mapping and frees address space.

The observable effect is that tools that report virtual memory, such as ps or the container's virtual size, show a figure several times the heap under ZGC, and that is expected rather than a leak; RSS is the number to watch.

"What are ZGC's sizing rules and which log line tells you the heap is too small?"

ZGC needs room to allocate into while a cycle runs, so the rule of thumb is a maximum heap 20 to 30 percent above the live set, more for a high allocation rate. It uncommits unused memory after -XX:ZUncommitDelay=300 seconds unless -Xms equals -Xmx.

The line that says the heap is too small is Allocation Stall (thread-name) 12.345ms in -Xlog:gc: a thread waited for the collector. Occasional stalls under a millisecond during a spike are tolerable; regular stalls mean either more heap, more -XX:ConcGCThreads, or a lower allocation rate.

The periodic Garbage Collection (Allocation Rate) lines show why each cycle started, and -Xlog:gc+heap shows capacity, used and the reserved headroom at each phase.

headroom pictureruns offline
heap 20 GB:  [ live 14 GB ][ headroom 6 GB, about 30% ]    allocation fits while the cycle runs   ✓
heap 15 GB:  [ live 14 GB ][ 1 GB ]                        allocation outruns the cycle           ✗
                                                           Allocation Stall (thread) 12.345ms
"Does ZGC ever do a full stop-the-world collection?"

No. ZGC has no fallback full compaction like G1's Pause Full.

When it cannot keep up, the failure mode is allocation stalls, which are per-thread waits rather than a global pause, and in the worst case an OutOfMemoryError after the collector has finished a cycle and still found no room.

That is a deliberate design choice: latency stays predictable, and pressure shows as throughput loss on the stalled threads.

It also means System.gc() triggers a concurrent cycle rather than a stop-the-world one unless -XX:+ExplicitGCInvokesConcurrent is off, and that a memory leak on ZGC shows as ever-longer cycles and rising stalls before the final error.

"When would you choose G1 over ZGC even for a latency-sensitive service?"

When the heap is under about 8 GB and the container has two or fewer cores.

There, G1 young pauses are already 5 to 20 ms, compressed oops save a good fraction of memory, and ZGC's concurrent threads would take a large share of the little CPU available, causing the stalls it was meant to avoid.

Also when throughput per core is the cost driver, such as a batch-like service running many replicas, because ZGC's barrier and concurrent work cost a few percent. And when the JDK is older than 21, because pre-generational ZGC handled high allocation rates poorly.

As of Aug 2026 with JDK 25 or 27, for a heap over 16 GB with four or more cores and a p99 goal under 20 ms, I default to generational ZGC.

Q70 · Design. "Design the memory budget for a JVM service in a Kubernetes container with a 4 GB limit. Tell me the numbers, the flags, and how you would verify the budget holds."

Reveal answer

The real test Whether you know the container limit covers everything the process touches, not the heap, and can name the non-heap parts with sizes.

Strong answer Requirements and assumptions: a 4 GB memory limit enforced by the kernel's cgroup, which counts the whole process resident set including native memory and part of the page cache; a typical request-serving service with a modest live set, a few hundred threads, some HTTP client buffers, and a wish to never be OOMKilled, which is a hard kill with no heap dump.

Design: I would budget from the outside in. Heap gets 55 to 65 percent, so -XX:MaxRAMPercentage=60 gives about 2.4 GB, and I would set -XX:InitialRAMPercentage=60 too so the heap is committed up front and there is no surprise growth after a traffic spike.

Metaspace, where class metadata lives, gets a ceiling with -XX:MaxMetaspaceSize=256m, and the compressed class space inside it defaults to 1 GB reserved but only what is used is committed.

  • Code cache, where JIT-compiled machine code goes: reserves 240 MB by default; I would leave it, since a service rarely commits more than 100 MB.
  • Thread stacks: 1 MB reserved each with -Xss1m and committed only as used, so 300 platform threads cost roughly 100 to 300 MB.
  • Direct buffers: an explicit -XX:MaxDirectMemorySize=256m, because the default is equal to the heap maximum and that is a budget nobody wrote down.

GC overhead for G1, meaning remembered sets and card tables, is 5 to 10 percent of heap, about 200 MB. The C2 compiler's working memory spikes to tens of megabytes during heavy compilation.

Add the glibc allocator's arenas, which I would cap with MALLOC_ARENA_MAX=2, and the page cache for any files the service reads, which the cgroup also charges.

That sums to roughly 2.4 GB heap plus 1.1 to 1.3 GB of everything else, leaving 300 to 400 MB of margin.

Trade-offs: a larger heap means more frequent OOMKills under native pressure; a smaller heap means more GC. Verification: -XX:NativeMemoryTracking=summary in staging, then jcmd <pid> VM.native_memory summary under load to read committed bytes per category and compare with RSS. In production I alert on container RSS above 85 percent of the limit and on the heap's after-GC occupancy, and I set -XX:+ExitOnOutOfMemoryError with -XX:+HeapDumpOnOutOfMemoryError so a heap failure is a clean restart with evidence.

What I would not do: set -Xmx at 80 percent of the limit; leave MaxDirectMemorySize at its default; or rely on -XX:MaxRAMPercentage's default of 25, which wastes three quarters of the container.

Picture it the 4 GB limit as a budget table, and the native memory tracking output that proves it.

Make the invisible visible: where each megabyte of the limit is spent.

Illustrative 4 GB budget
TenantSetting or sourceBudget
Heap-XX:MaxRAMPercentage=60about 2,450 MB
Metaspace-XX:MaxMetaspaceSize=256mup to 256 MB
Code cachedefault reserve 240 MBabout 100 MB committed
Thread stacks300 threads at -Xss1m100 to 300 MB
Direct buffers-XX:MaxDirectMemorySize=256mup to 256 MB
GC structures and compilerremembered sets, card table, C2about 250 MB
Arenas, libraries, page cacheMALLOC_ARENA_MAX=2100 to 250 MB
Marginwhat is left300 to 400 MB

What you see: native memory tracking under load.

jcmd VM.native_memory summaryruns offline
# illustrative output
Total: reserved=4514MB, committed=3108MB
-   Java Heap   (reserved=2458MB, committed=2458MB)
-   Class       (reserved=1100MB, committed=80MB)
-   Thread      (reserved=310MB,  committed=310MB)
-   Code        (reserved=240MB,  committed=70MB)
-   GC          (reserved=150MB,  committed=150MB)
-   Other       (reserved=256MB,  committed=40MB)       direct buffers

Why: the cgroup limit counts everything the process touches, so only the sum of these lines against RSS shows whether the budget holds.

Land it The heap is one tenant of the container, and the budget is only real once native memory tracking in staging has shown where the other gigabyte actually goes.

Likely follow-ups
"The requirement changes: the service moves to virtual threads and now runs 50,000 concurrent requests. What in the budget changes?"

Thread stacks stop being the concern and heap becomes it.

A virtual thread's stack lives on the heap as jdk.internal.vm.StackChunk objects, typically a few hundred bytes to a few kilobytes per parked thread, so 50,000 parked requests cost tens to a couple of hundred megabytes of heap, not of native stack.

The carrier pool is small, one platform thread per core, so the native thread budget falls.

What rises is the allocation rate from copying frames on park and unpark, and any per-request buffers that used to be bounded by the thread pool size are now bounded by nothing; 50,000 concurrent 64 KB read buffers is 3.2 GB. So I would move about 10 percent of the native budget into the heap, and I would add a Semaphore around any per-request native or buffer allocation to keep concurrency honest.

"What would you cut under time pressure?"

I would ship with three flags and one alert. -XX:MaxRAMPercentage=60, -XX:MaxDirectMemorySize=256m, and -XX:+ExitOnOutOfMemoryError, plus an alert on container RSS above 85 percent.

I would skip the metaspace cap, since class metadata in a normal service plateaus on its own, the glibc arena setting, and the initial heap percentage. I would postpone native memory tracking until the first time RSS drifts.

The reasoning is that the two ways this service dies without a trace are an unbounded direct buffer budget and an unbounded heap, and the two flags remove both; everything else is refinement I can do after the first week of RSS graphs.

"Why does RSS keep growing slowly even when NMT says every category is flat?"

NMT only sees memory the JVM allocated through its own tracked paths. Three things it misses.

Native libraries allocating with malloc directly, such as a JDBC driver's native part or a compression library; glibc fragmentation, where freed memory is not returned to the kernel and arenas grow, which MALLOC_ARENA_MAX=2 or switching to jemalloc via LD_PRELOAD addresses; and memory-mapped files, whose pages count toward RSS when touched.

The way to attribute it is pmap -x <pid> or /proc/<pid>/smaps summed by mapping, compared against NMT's committed total; the difference is what NMT cannot see.

If the untracked part grows steadily, I would suspect a native resource that is closed only by a finaliser or cleaner, such as java.util.zip.Inflater instances never explicitly ended.

RSS against NMTruns offline
# illustrative output
RSS (VmRSS in /proc/<pid>/status)      3,420 MB
NMT committed total                    2,610 MB
untracked difference                     810 MB    ✗ malloc in native libraries, glibc arenas, mapped files
"How is the container limit different from the node's memory from the JVM's point of view?"

Since JDK 10 the JVM reads the cgroup limit rather than the host's RAM, so MaxRAMPercentage applies to the 4 GB limit.

If no limit is set, it applies to the node's memory and a 25 percent default on a 128 GB node produces a 32 GB heap that the scheduler never agreed to.

The limit also determines what Runtime.availableProcessors() reports through the CPU quota, which sets the number of GC threads and the size of the common ForkJoinPool.

One trap: a CPU limit of 1 or fewer cores, or a memory limit under about 1.8 GB, made the JVM pick Serial GC before JDK 27; as of Aug 2026, JEP 523 in JDK 27 makes G1 the default in all environments, so behaviour on small containers changes with that upgrade and should be checked.

Drill · GC incidents, native memory & heap design

This group tests whether you can take a memory incident from the first alert to a fix, including the memory the heap graph never shows you, and then design a heap and off-heap layout that avoids the incident next time.

Q71 · Scenario. "A service on generational ZGC logs Allocation Stall lines and its p99 latency spikes to 200 ms, while average GC CPU looks low. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom decoded: ZGC never pauses the world for long, so a 200 ms spike is not a GC pause. An allocation stall means a thread wanted to allocate, the heap had no free space, and the thread had to wait for the concurrent collector to free some. The stall is the latency spike, one thread at a time, which is why average GC CPU can look fine.
  2. Evidence: -Xlog:gc,gc+heap,gc+cpu. The stall line itself, Allocation Stall (http-worker-12) 187.4ms, gives the thread and duration. The cycle lines show why each collection started; Garbage Collection (Allocation Stall) or (Allocation Rate) back to back means the collector is running flat out. The heap lines show capacity, used at mark start and used at relocate end; if used is near capacity at every phase there is no headroom. -Xlog:gc+cpu compares real time to user plus system time, and if real is much larger the collector's threads are not getting CPU. jcmd <pid> VM.flags tells me ConcGCThreads and the heap size.
  3. Causes, ranked: an allocation rate that a concurrent cycle cannot outrun, either because the heap has too little headroom above the live set or because the rate spiked; too few concurrent GC threads, since ZGC defaults to about a quarter of the available processors and on a 2-core container that is one thread; a CPU-throttled container where the cgroup quota starves the collector precisely when the application is busiest; a burst of large allocations; or a live set that has grown, so the same heap now has less room.
  4. Fix: give headroom first, with -Xmx raised so that the live set is at most 70 to 80 percent, and -XX:SoftMaxHeapSize set to where I want it to sit normally. Then -XX:ConcGCThreads raised to roughly a third of the cores if CPU allows. Then make the collector start earlier on spikes with -XX:ZAllocationSpikeTolerance above its default of 2. If the container is throttled, raise the CPU limit or lower the request concurrency. Last, reduce the allocation rate at the source using a JFR allocation profile.
  5. Prevention: an alert on the count of stall lines per minute, which is the earliest signal, and a load test that records the allocation rate and cycle duration together so headroom is sized from data.

Land it On ZGC the latency risk is not the pause but the thread that waits for space, so the fix is headroom and collector CPU, in that order, before any application change.

Likely follow-ups
"You doubled the heap and raised ConcGCThreads, and stalls still happen every few minutes. What next?"

Then the pattern is periodic, and something periodic is allocating a burst the collector cannot pre-empt. I would line up the stall timestamps with the application's own logs and with the young cycle starts.

Typical periodic culprits are a scheduled job that materialises a large result set, a cache refresh that rebuilds a big map, or a metrics exporter serialising everything at once. The JFR event jdk.ObjectAllocationSample over the stall window names the stack.

If the burst is legitimate I would smooth it, for example by paging the job, or pre-trigger a cycle before it with System.gc(), which on ZGC starts a concurrent cycle.

I would also check -Xlog:gc+heap for uncommit: if the heap was uncommitted during a quiet period, the burst pays to recommit, which is fixed by setting -Xms equal to -Xmx or -XX:-ZUncommit.

"How does ZGC decide when to start a cycle, and which of those triggers is the one you want to see?"

ZGC starts a collection for several reasons and prints the reason in the log. Allocation Rate means it predicted, from recent allocation and cycle time, that the heap would fill before a cycle could finish, and started early; that is the healthy, normal trigger.

Warmup fires the first cycles at 10, 20 and 30 percent heap use to gather timing data. Proactive runs when the heap has grown since the last cycle and the system is idle. Timer fires if -XX:ZCollectionInterval is set.

High Usage means used memory crossed 95 percent. Allocation Stall means a thread already blocked, which is the one I never want to see. A healthy log is dominated by Allocation Rate with generous margin between used and capacity at each cycle's end.

"How much CPU does ZGC actually take, and how do you measure it?"

Concurrent marking and relocation run on ConcGCThreads workers, and the load barrier adds a few percent to application threads.

Under a steady 1 GB per second allocation rate on a 16 GB heap I would expect one to two cores busy on collection most of the time.

The measurement is -Xlog:gc+cpu, which prints user, system and real seconds per cycle, so user time divided by cycle wall time is the number of cores the collector used. JFR's jdk.GCCPUTime and the thread CPU view in Mission Control show the ZWorker threads directly.

In a container I would compare that against the CPU quota, because a collector that needs 1.5 cores in a 2-core pod leaves half a core for the application and stalls follow.

"Would switching back to G1 remove the spikes?"

It would replace them with a different shape. G1 would run young pauses proportional to survivors, perhaps 10 to 30 ms on a 16 GB heap, at a steady rhythm, and it needs no concurrent CPU except during marking.

If the service's p99 goal is 50 ms or above and the container is CPU-tight, G1 is the more forgiving choice. If the goal is under 10 ms, G1 cannot meet it on that heap and I would stay on ZGC and fix headroom.

The decision is about where I want the cost: G1 spends it as short, predictable pauses on every thread; ZGC spends it as concurrent CPU and, when starved, as stalls on the unlucky thread.

Q72. "Show me how you would turn on GC logging in production, and then read me a G1 young pause line and tell me what the other line types mean."

Reveal answer

The real test Whether you can write the unified logging flag from memory with rotation and decorations, and then decode a real line without a tool.

Strong answer Since JDK 9 all JVM logging goes through unified logging with the -Xlog flag, whose syntax is tags, then output, then decorators, then output options, separated by colons. The line I would put on every service is:

-Xlog:gc*:file=/var/log/app/gc.log:time,uptime,level,tags:filecount=5,filesize=50m

gc* selects every tag that starts with gc at info level, which is cheap enough to leave on permanently.

The rest of the line adds context. time adds a wall-clock timestamp, uptime gives seconds since start, and filecount with filesize rotates five files of 50 MB.

For a specific investigation I add two more: gc+phases=debug for the phase breakdown, and safepoint for time-to-safepoint.

A normal G1 young pause line reads:

[2026-08-28T10:15:02.123+0000][1234.567s][info][gc] GC(42) Pause Young (Normal) (G1 Evacuation Pause) 1024M->312M(2048M) 12.345ms

Take it apart field by field. GC(42) is the collection's sequence number, shared by every line belonging to that collection.

Normal is the young collection type. The alternatives are Concurrent Start, which begins a marking cycle, and Prepare Mixed and Mixed, which include old regions.

The cause in the second bracket says why it ran, and there are three you will meet:

  • G1 Evacuation Pause — eden filled.
  • G1 Humongous Allocation — a large object needed room.
  • Metadata GC Threshold — metaspace hit its limit.

Then heap before, heap after, and total committed: 1024 MB down to 312 MB in a 2 GB heap. That 312 MB is the number that approximates the live set. The time at the end is the stop-the-world duration.

Four other line types are worth recognising on sight:

  • Concurrent Mark Cycle brackets the whole concurrent marking, with its duration.
  • Pause Remark and Pause Cleanup are the short pauses that end it.
  • To-space exhausted, next to a young pause, means evacuation failed for lack of free regions.
  • Pause Full (G1 Compaction Pause) is the stop-the-world full collection. This is the line I alert on.

With phases at debug level, each pause expands into Pre Evacuate Collection Set, Merge Heap Roots, Evacuate Collection Set (containing Ext Root Scanning, Object Copy and Termination), then Post Evacuate Collection Set. The biggest phase tells me what to fix.

For trend analysis over days I would load the file into GCeasy, or Microsoft's open-source GCToolkit, rather than read it by hand.

Land it The after-GC heap figure and the pause cause are the two fields that answer most incidents, and the log costs so little that not having it on is a choice to be blind.

Likely follow-ups
"Which phase would be large for which problem?"

Object Copy dominating means many survivors, so either the young generation is too small for the object lifetimes or a large batch of data was live at that moment; the fix is a larger heap or eden, or shorter object lifetimes.

Ext Root Scanning large means many roots, typically thousands of threads with deep stacks or a huge number of loaded classes. Merge Heap Roots or Scan Heap Roots large means many cross-region pointers or a refinement backlog from heavy writes into old structures.

Termination large means uneven work between GC threads, often because ParallelGCThreads exceeds the CPU quota. Other large usually means reference processing or JNI weak handle work, which -Xlog:gc+ref=debug breaks down. Reading the phase that dominates is faster than any heuristic.

"How would you see whether the JVM was starved of CPU during a pause?"

Each pause with -Xlog:gc+cpu prints User=0.08s Sys=0.01s Real=0.04s. With eight parallel GC threads and a 40 ms pause I expect user time around 0.3 seconds.

If user plus system is close to real, the GC threads were running one at a time, so the container has fewer cores than ParallelGCThreads or the cgroup quota throttled the process.

If real is much larger than the total, the threads were waiting entirely, which means the machine was swapping or the process was throttled hard. The cgroup's own counter, nr_throttled in cpu.stat, confirms it.

Pauses that are long only at busy hours with this signature are a CPU limit problem, not a collector problem.

"What changed in GC logging that trips people migrating from JDK 8?"

Everything before JDK 9 used -XX:+PrintGCDetails, -XX:+PrintGCDateStamps and -Xloggc:file. Those are gone; -Xloggc is still accepted as an alias but the print flags fail the JVM start with "Unrecognized VM option" on recent releases, which has crashed more than one deployment.

Rotation moved from -XX:+UseGCLogFileRotation to the filecount and filesize output options. The line format changed, so old log parsers break; GCeasy and GCToolkit read both. And the tags changed meaning: gc alone gives one line per collection, while gc* gives all sub-tags.

On JDK 17 or later I would also add -Xlog:gc+init once at startup, which prints the collector, heap size, region size and thread counts the JVM actually chose.

Q73 · Design. "You inherit three services on a single JDK 25 build: a nightly batch job on 8 GB, a request API on 6 GB with a 30 ms p99 goal, and a 96 GB in-memory index with a 5 ms goal. Choose a collector for each and defend the choices."

Reveal answer

Strong answer Requirements and assumptions: three different goals, throughput for the batch, moderate latency on a small heap, and strict latency on a huge heap; one JDK build, which I will assume is a vendor build that ships all four collectors, and note that Oracle's build does not include Shenandoah.

Design: for the batch job, Parallel GC with -XX:+UseParallelGC. It uses a plain card table and the cheapest write barrier, compacts the old generation with all cores in one stop-the-world pass, and nobody is waiting on a request while it does.

On 8 GB a full collection takes one or two seconds, which is invisible in a job measured in minutes, and the throughput gain over G1 is typically 5 to 15 percent on allocation-heavy code. For the request API on 6 GB, G1 with defaults.

Its young pauses on a heap that size are 5 to 20 ms, well inside 30 ms; compressed oops keep memory down; it does not need spare cores. I would only revisit it if the log shows mixed collections drifting past the goal.

For the 96 GB index with a 5 ms goal, generational ZGC with -XX:+UseZGC. G1 cannot meet 5 ms while copying regions from a 96 GB heap, and it has lost compressed oops anyway above 32 GB, so ZGC's 8-byte references cost nothing extra.

ZGC's pauses stay sub-millisecond at that size; I would size -Xmx at least 25 percent above the live set, set -XX:ConcGCThreads to a third of the cores, and alert on Allocation Stall.

Shenandoah would be my second choice for the third service on a vendor that ships it; its mechanism is similar, load-reference barriers with a forwarding pointer rather than coloured pointers, and JEP 521 in JDK 25 gave it a generational mode, but ZGC is the one in every build and the more widely operated.

Trade-offs: Parallel gives up latency; G1 gives up some throughput for predictable pauses; ZGC gives up throughput per core and memory density for latency independent of heap size. As of Aug 2026 the JDK 27 change, JEP 523, makes G1 the default in all environments, which only matters for the smallest containers where Serial used to be chosen.

What I would not do: one collector for all three for the sake of uniform flags, or ZGC on the 6 GB API in a two-core pod, where the collector's threads would compete with request threads.

Land it Parallel when nobody is waiting, G1 when the heap is modest and the goal is tens of milliseconds, ZGC when the heap is large or the goal is single-digit, and the log decides the borderline cases.

Likely follow-ups
"The requirement changes: the request API must now run in 1 GB containers with one core, thousands of replicas. Does G1 still hold?"

On JDK 25 the JVM would pick Serial GC in that container, because the ergonomics choose Serial when there are fewer than two processors or under about 1.8 GB. That is a defensible choice: Serial has no per-thread GC overhead, the smallest footprint, and on a 600 MB heap its young pauses are a few milliseconds.

G1 on one core cannot run its concurrent refinement or marking without stealing the only core, so its advantage disappears. I would keep the default, verify it with -Xlog:gc+init, and budget for the full-GC case, a few hundred milliseconds on that heap.

When moving to JDK 27, where JEP 523 makes G1 the default everywhere, I would test both and likely pin -XX:+UseSerialGC explicitly for that footprint.

"What would you cut under time pressure?"

I would cut the per-service analysis and apply one rule: G1 with defaults on every service, plus GC logging and an alert on full GCs and pause p99.

G1 is the safe middle: the batch job loses a little throughput, the API is fine, and the 96 GB index would run but miss its 5 ms goal.

Then I would spend the remaining time only on the index, which is the one service where the default clearly fails, and switch it to generational ZGC with a headroom rule and a stall alert.

Parallel for the batch is an optimisation I can do in the next iteration by comparing job wall time under both collectors in a single afternoon.

"How do you decide between Shenandoah and ZGC when both are available?"

Their goals are the same and their pause profiles are both sub-millisecond, so it comes down to three practical points. Availability: ZGC is in every JDK build, Shenandoah is in Red Hat, Temurin, Corretto and others but not in Oracle's.

Memory: ZGC has no compressed oops and reserves extra virtual address space, Shenandoah keeps compressed oops on heaps under 32 GB, so on a 16 GB heap Shenandoah is denser.

Maturity of the generational mode: ZGC's has been default since JDK 23, Shenandoah's arrived as a product feature in JDK 25 with JEP 521.

For a heap over 32 GB I would pick ZGC; between 8 and 32 GB on a vendor that ships it, I would benchmark both, and I would expect Shenandoah to win on footprint and ZGC on operator familiarity.

"When is Parallel GC the wrong choice even for a batch job?"

When the heap is large enough that a full compaction becomes the job's critical path.

Parallel's full collection is proportional to the live set and runs stop-the-world; on a 60 GB heap with 40 GB live it can take 30 seconds or more, and if the job's data structure grows so that full collections happen every minute the job spends most of its time compacting.

At that point G1 with its incremental mixed collections, or ZGC, finishes sooner despite lower raw throughput.

The other case is a batch job that also serves a health endpoint or heartbeats to a coordinator such as Kafka's consumer group, because a 30-second pause gets it evicted.

The signal in the log is Pause Full lines whose total exceeds a few percent of runtime.

Q74 · Scenario. "Native memory on a service grows about 100 MB a day while the heap stays flat, and the pod gets OOMKilled roughly weekly. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom decoded: the heap is flat, so this is not a Java object leak and a heap dump will not show it. Resident memory outside the heap is growing, and the kernel kills the container when the total crosses the limit. The 100 MB per day steadiness suggests something allocated per unit of work and never released, not a startup effect.
  2. Evidence: restart with -XX:NativeMemoryTracking=summary, take jcmd <pid> VM.native_memory baseline after warm-up, then a day later jcmd <pid> VM.native_memory summary.diff, which prints the growth per category. Alongside it, RSS from the container and pmap -x <pid> sorted by size, because NMT only sees JVM-tracked memory and the gap between RSS and NMT's committed total is the untracked part. jcmd <pid> VM.native_memory also shows the thread count under the Thread category and the buffer pool figures are on the java.nio:type=BufferPool,name=direct MBean.
  3. Causes, ranked by how often I have seen them: direct ByteBuffer memory retained by references that never die, or by Netty's pooled allocator holding chunks, showing under NMT's Other or Internal category; glibc malloc arenas, where a process with many threads gets up to eight arenas per core, each able to grow to 64 MB, and fragmentation keeps them from shrinking, which shows as untracked RSS; thread leaks, where a pool per request or a client library spawns threads that never end, visible as a rising Thread category and thread count; java.util.zip.Inflater or Deflater instances created per request and never closed with end(), whose zlib buffers are freed only when a cleaner runs, which on a flat heap is rarely; metaspace growth from generated classes; and code cache growth from repeated deoptimisation and recompilation.
  4. Fix: whatever the diff names. For arenas, set MALLOC_ARENA_MAX=2 in the container environment or preload jemalloc with LD_PRELOAD; for zip, use try-with-resources on the stream or call end(); for direct buffers, bound them with -XX:MaxDirectMemorySize so the failure becomes an OutOfMemoryError with a stack rather than a kill, and fix the retention; for threads, find the creator in a thread dump by name pattern.
  5. Prevention: NMT summary on permanently in staging, an alert on RSS slope rather than on RSS level, and a memory budget document that names every native consumer.

Land it A flat heap with rising RSS is a native problem, and the diff between two native memory tracking snapshots is the one piece of evidence that turns a weekly kill into a named class.

Likely follow-ups
"NMT's diff shows every category flat, but RSS still grows 100 MB a day. What next?"

Then the growth is in memory the JVM does not track: native code called through JNI or the foreign function API, the C library's own heap, or memory-mapped files. I would take pmap -x <pid> twice a day apart and diff by mapping.

Growing anonymous mappings of 64 MB each are glibc arenas; the fix is MALLOC_ARENA_MAX=2 or jemalloc, and jemalloc's profiling with MALLOC_CONF=prof:true can attribute native allocations to call stacks. Growing file-backed mappings are mapped files someone keeps opening; the cgroup charges touched pages.

If it is a native library, I would look at what the service calls natively: a JDBC driver with a native part, a compression or crypto library, or an image codec, and check whether it requires an explicit close that a code path skips.

"Why does the glibc arena problem hit Java services specifically?"

glibc gives each thread that calls malloc an arena, up to eight times the number of cores, to reduce lock contention.

Each arena grows in 64 MB chunks on 64-bit and rarely gives memory back, because freed blocks in the middle of a chunk cannot be returned to the kernel.

A JVM has hundreds of threads and many native callers: the JIT compiler threads, GC threads, and any code touching zlib, direct buffers or JNI. So it creates many arenas that each fragment slowly.

The effect is RSS that grows for weeks and plateaus far above what NMT reports.

Capping arenas at two costs a little contention on native allocation, which a JVM barely does on its hot path, and jemalloc's design with size classes avoids the fragmentation altogether; Netty's documentation and several JDK bug reports describe the same remedy.

"How would you prove it is the Inflater leak in particular?"

Two ways.

A heap dump or jcmd <pid> GC.class_histogram shows the count of java.util.zip.Inflater instances; if there are tens of thousands alive, each holding a native zlib stream of about 32 KB plus window, that is the leak, even though the Java objects themselves are tiny and the heap looks fine.

A JFR recording with the jdk.ObjectAllocationSample event filtered to that class names the allocation site, typically a GZIPInputStream created per request and never closed.

The confirmation is that calling System.gc() drops RSS noticeably, because the cleaners run and free the native buffers, which is a demonstration and not a fix. The fix is try-with-resources on the stream, and for pooled use, an explicit end() in a finally block.

"What does the NMT summary cost, and would you leave it on in production?"

The summary mode adds a header of a couple of words to each tracked allocation and a small counter update, typically 1 to 3 percent of native allocation throughput and a few megabytes of memory; the JVM itself is not allocating natively on the request path, so the effect on request latency is usually unmeasurable.

Detail mode records call stacks and costs noticeably more. I leave summary on in staging always and enable it in production for a specific investigation, because it must be set at startup; it cannot be turned on later with jcmd.

Once on, jcmd <pid> VM.native_memory summary scale=MB is safe to run at any time and takes milliseconds.

Q75. "What lives in metaspace, when does the JVM unload a class, and separately, when would you use a soft, weak or phantom reference, or a Cleaner?"

Reveal answer

Strong answer Metaspace is native memory, outside the heap, where the JVM keeps class metadata: the method bytecode, the constant pool, field and method tables, and the runtime data the interpreter and JIT need.

Inside it the compressed class space holds the Klass structures that compressed class pointers index into, reserved at -XX:CompressedClassSpaceSize=1g by default.

Metaspace has no fixed limit unless -XX:MaxMetaspaceSize is set; it grows in chunks from the operating system, and since the elastic metaspace work in JDK 16 it also returns memory.

Metadata is freed only by class unloading, and a class is unloaded only when its class loader becomes unreachable, together with every class it loaded and every instance of those classes.

The application class loader never becomes unreachable, so the JDK and application classes stay forever; unloading matters for frameworks that create loaders per plugin, per deployment or per generated class, such as lambda proxies and hidden classes, which use their own loaders precisely so they can be unloaded.

-Xlog:class+unload prints each unloaded class, and a metaspace exhaustion appears as OutOfMemoryError: Metaspace or, for the class space specifically, Compressed class space. Reference types are the second half.

A SoftReference is cleared when memory is tight, by policy -XX:SoftRefLRUPolicyMSPerMB=1000, meaning one second of survival per megabyte of free heap since last use; it is a memory-sensitive cache, and I use it rarely because clearing happens in bulk right before a full GC, which is the worst moment.

A WeakReference is cleared as soon as the object is otherwise unreachable, at the next collection that notices; it is right for canonicalising maps such as WeakHashMap keys and listener lists where the referent's owner decides its life.

A PhantomReference never returns its referent, and is enqueued after the object is unreachable, so it is a signal that an object is gone; that is what java.lang.ref.Cleaner is built on.

Cleaner.create().register(obj, runnable) runs the action once the object is unreachable, on a dedicated thread, and the action must not reference the object.

It replaces finalize(), which is deprecated for removal since JDK 18 and can be disabled with --finalization=disabled, because a finaliser resurrects the object, runs on a single JDK thread, and delays freeing by at least two collections.

I use a Cleaner only as a safety net behind an explicit close(), never as the primary release path.

Land it Metaspace is freed by loader, not by class, and a reference type is a statement about who decides an object's lifetime; the collector should be the backup, never the owner.

Likely follow-ups
"Why can a single retained object keep 50 MB of metaspace alive?"

Because every object holds a reference to its class, every class holds a reference to its loader, and a loader holds every class it loaded.

If a plugin's class loader loaded 5,000 classes and one instance of one of those classes is still referenced, for example from a static cache in the application loader or from a thread-local on a pooled thread, then the loader is reachable, all 5,000 classes stay, and their metaspace cannot be freed.

A heap dump shows this as a chain from a GC root through the surviving object to ClassLoader, and the dominator tree attributes the loader's retained size.

This is the classic redeploy leak in application servers, and thread-locals, shutdown hooks, JDBC driver registration and logging frameworks are the usual anchors.

"What is the practical difference between a weak and a soft reference in a cache?"

A weakly referenced entry is gone at the next young collection if nothing else holds it, which on a busy service is seconds, so a weak cache barely caches anything; it is a canonicalisation map, not a cache.

A soft entry survives until the JVM decides memory is short, and the policy is time-since-last-access per megabyte of free heap, so on a large idle heap soft entries live for hours and on a full heap they are cleared all at once, which turns a cache miss storm into the same moment the collector is struggling.

Neither gives me a size bound or an eviction policy. So for a real cache I use Caffeine with a maximum size and let it hold strong references, and I use weak references only for keys whose identity is owned elsewhere.

"What are the rules for writing a correct Cleaner action?"

The action is a Runnable that must be a static nested class or a lambda that captures nothing from the object being cleaned, because if it captured the object the object could never become unreachable and the action would never run.

The usual pattern is a static class holding only the native handle or the resource to release. The cleaning action runs at most once, either when the object becomes phantom-reachable or when the code calls Cleanable.clean() from close(); the second call is a no-op.

It runs on the cleaner's own daemon thread, so it must be quick and must not throw. And it is a safety net: the JDK's DirectByteBuffer uses exactly this, but it also asks the caller to release explicitly through MemorySegment arenas in newer APIs.

"How would you spot a metaspace leak before it becomes an error?"

The metaspace metrics are on the java.lang:type=MemoryPool,name=Metaspace MBean, or in JFR's jdk.MetaspaceSummary event, and a sawtooth that never returns to its previous floor after each collection is the shape of a leak.

jcmd <pid> VM.classloader_stats lists every loader with its class count and metaspace bytes, so a growing count of loaders of one type, such as hundreds of DelegatingClassLoader from reflection or generated proxies from a framework, is the cause named directly.

-Xlog:class+load at info level shows what is being loaded continuously; a healthy service goes quiet after warm-up. I would alert on loaded class count still rising an hour after start.

Q76 · Design. "Design an off-heap storage layer with the foreign function and memory API: a store of variable-size records that several threads read and one thread writes, with a hard cap of 20 GB. Walk me through allocation, slicing, lifetime and safety."

Reveal answer

The real test Whether you know the Arena kinds and the closing rules well enough to design a lifetime discipline, not only that MemorySegment exists.

Strong answer Requirements and assumptions: JDK 22 or later so the API is final under JEP 454; records of a few hundred bytes to a few megabytes; reads from many threads and writes from one; a 20 GB cap that must be respected without relying on the garbage collector; and a need to free space when records are deleted.

Design: the store allocates a small number of large slabs, say 256 MB each, up to 80 slabs, from one Arena.ofShared(), because a shared arena's segments can be accessed from any thread, while Arena.ofConfined() restricts access to the creating thread and throws WrongThreadException otherwise.

I would not use Arena.ofAuto(), whose segments are freed by the garbage collector, because that reintroduces the unpredictability I am building the layer to avoid, and not Arena.global(), which can never be freed.

Each slab is one MemorySegment; the allocator is a slab allocator with size classes, for example 256 bytes doubling up to 4 MB, each class managing free lists of slices within slabs.

A record is written into a slice obtained by slab.asSlice(offset, size), and the index maps a key to slab number, offset and length as three primitives, never to a Java reference to the slice, so the heap holds no per-record objects.

Record layout is described with MemoryLayout.structLayout, a header of length and a version counter, and accessed through VarHandles from layout.varHandle(PathElement.groupElement("len")), which gives me typed, bounds-checked reads. Every access is bounds-checked against the segment's size, so an off-by-one is an IndexOutOfBoundsException and not a corrupted neighbour.

Concurrency: the single writer publishes a record by writing the bytes, then setting the version with a release write; readers read the version with an acquire read before and after copying and retry on change, which is a seqlock and needs no lock for readers.

Lifetime: the arena is owned by the store and closed only in the store's close(), which does a handshake with all threads and makes every segment invalid, so any late read throws IllegalStateException saying the arena is already closed; that is the safety property, a use-after-free becomes an exception rather than a crash.

Trade-offs: a shared arena's close is expensive because of the handshake, so I close once at shutdown, never per record; slab sizing wastes up to half a size class per record, which I would measure and tune; the seqlock favours readers and starves nobody because there is one writer.

What I would not do: one arena per record, because closing shared arenas per operation is far too slow; sun.misc.Unsafe, whose memory methods are deprecated for removal since JDK 24; or handing callers raw segments, since they could keep them past the store's life.

Land it One shared arena owned by the store, slices handed out by an allocator you control, and an index of offsets rather than references, so the collector sees nothing and every misuse is a checked exception.

Likely follow-ups
"The requirement changes: many writers instead of one. What in the design changes?"

The seqlock stops being enough, because two writers could interleave on the same record.

I would move to per-record ownership through the index: a writer claims a key with a compare-and-set on the index entry, writes into a freshly allocated slice, and then publishes the new offset with a single atomic store, so readers see either the old complete record or the new one.

The old slice is not freed immediately, since a reader may still be copying it; I would put it on a deferred free list drained after a grace period or an epoch counter that every reader increments on entry and exit.

The allocator needs per-writer free lists or a lock per size class to avoid contention. This is more code, so I would first ask whether writers can be funnelled through one thread or a queue, which keeps the original design.

"What would you cut under time pressure?"

The size-class allocator. I would start with a bump allocator per slab, appending records and never freeing, plus a compaction pass that copies live records into a fresh slab when a slab's dead fraction crosses 50 percent, and I would drop deletion below that threshold entirely.

That is a couple of hundred lines instead of a thousand, and it works well when records are updated rarely. I would also cut the MemoryLayout and VarHandle descriptions and use segment.get(ValueLayout.JAVA_INT, offset) directly with hand-computed offsets, which is less self-documenting but identical in safety.

I would not cut the single owned shared arena or the offset-based index, because those are the two decisions that make the layer safe.

"How do you keep the 20 GB cap honest, and what happens when it is hit?"

The store owns the arena, so it knows exactly how many slabs it has allocated; when the eightieth slab is in use and no free slice fits, the allocator returns failure and the store throws a capacity exception to the caller, which can evict or reject.

That is the whole point of an owned arena over direct buffers: no hidden global limit.

I would still set -XX:MaxDirectMemorySize in case some other component uses ByteBuffer.allocateDirect, and I would size the container for 20 GB of store plus the heap plus the usual native parts.

Native memory tracking shows the arena memory under the Other category, and I would expose the store's own slab count and used bytes as metrics, because those are the numbers the cap is defined in.

"How does this compare with just using direct ByteBuffers?"

Direct buffers work, and Netty's PooledByteBufAllocator is a ready-made slab allocator on top of them.

Their limits: a single buffer is capped at 2 GB by the int index, so slabs cannot be larger; freeing is by cleaner, so memory returns only when the buffer object is collected, unless I use Netty's explicit release counting; the total is bounded by MaxDirectMemorySize, which is a global limit shared with everything else; and the API has no layouts or typed handles, so structured records mean manual offset arithmetic.

Memory segments give me 64-bit sizes, explicit deterministic freeing through the arena, thread-confinement rules, and layouts. For a new store on JDK 22 or later I choose segments; for a store embedded in a Netty service I would use Netty's allocator and accept its model.

Q77 · Scenario. "A service does a full GC every 30 minutes and the log says the cause is Metadata GC Threshold. The heap is barely used. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom decoded: the collection was not started because the heap filled, but because metaspace, the native memory holding class metadata, reached its current high-water mark. The JVM then runs a collection so that class unloading can free metadata, raises the mark if not enough was freed, and continues. A collection every 30 minutes with that cause means classes are being loaded continuously, and either they are not becoming unloadable or the mark is set so low that it is reached constantly.
  2. Evidence: -Xlog:gc+metaspace prints the metaspace used, committed and the threshold at each collection, so I can see whether used drops after each collection, meaning classes do get unloaded, or ratchets upward, meaning they do not. -Xlog:class+load,class+unload shows what is being loaded and unloaded. jcmd <pid> VM.classloader_stats lists loaders with class counts, and jcmd <pid> VM.metaspace gives the detailed breakdown. The flags -XX:MetaspaceSize, which is the initial threshold and defaults to about 21 MB, and -XX:MaxMetaspaceSize come from jcmd <pid> VM.flags.
  3. Causes, ranked: class churn from generated code, such as a framework creating a new proxy class per request, a scripting or template engine compiling classes each time, or reflection's inflation creating GeneratedMethodAccessor classes for every hot method on JDKs before 18, each with its own loader so they are unloadable, which gives the pattern load, fill, collect, unload, repeat; a MetaspaceSize left at the default on a service that legitimately has 300 MB of classes, so the threshold is hit repeatedly during warm-up and afterwards every time it creeps; a genuine metaspace leak, where loaders are retained, which would end in an OutOfMemoryError: Metaspace rather than a stable cycle.
  4. Fix: for churn, stop generating classes per operation; cache the proxy, compile the template once, and on JDK 18 or later reflection uses method handles so the accessor churn is gone. For a low floor, set -XX:MetaspaceSize=256m so the first threshold sits above the steady-state class footprint, which removes the collections without changing anything else. For a leak, find the anchor in a heap dump's path to the loader.
  5. Prevention: an alert on class load rate after warm-up, and MetaspaceSize set from the measured steady state in every service's baseline flags.

Land it The heap is a bystander; the collector is being asked to do class unloading on a schedule, and the fix is either to stop making throwaway classes or to raise the threshold above the real class footprint.

Likely follow-ups
"You set MetaspaceSize=512m and the full GCs stopped, but three days later the service died with OutOfMemoryError: Compressed class space. What next?"

The threshold change hid a leak. Metaspace was ratcheting, and raising the floor only delayed the collection that would have shown that nothing gets unloaded.

The compressed class space is the 1 GB region for Klass structures, and it fills at a few hundred bytes to a kilobyte per class, so on the order of a million classes were created and retained.

I would take a heap dump on the next occurrence with -XX:+HeapDumpOnOutOfMemoryError, open the dominator tree, and look at the class loader instances: their count, their type and the path from a GC root to one of them.

The anchor is usually a static map or a thread-local holding an object from the generated class. Then I would stop generating classes at that site. Raising -XX:CompressedClassSpaceSize is not a fix, only a longer fuse.

"Which JDK changes reduced this class churn, and which frameworks still cause it?"

JDK 18, through JEP 416, reimplemented Method.invoke on method handles, which removed the GeneratedMethodAccessor classes that reflection used to spin after 15 calls per method; that was the most common metaspace churn in older services.

Lambdas and method references spin hidden classes once per call site, not per call, so they are a startup cost, not churn.

What still causes churn: dynamic proxies created per call with Proxy.newProxyInstance for a fresh interface set, bytecode generation libraries such as ByteBuddy or CGLIB used per object rather than per type, script engines and expression languages that compile each expression to a class, and serialisation frameworks that generate a class per encountered shape.

Each of these is fixed by caching the generated class keyed by its inputs.

"Why is the default MetaspaceSize so small, and what does raising it cost?"

The default of about 21 MB dates from when metaspace replaced the permanent generation in JDK 8 and was chosen to trigger an early collection so that a small application does not commit more metadata than it needs.

It is a threshold, not a reservation: raising it to 256 MB commits nothing extra, it only tells the JVM not to run a metadata-triggered collection until used metaspace passes that value.

The only cost is that unloadable classes linger longer before a collection frees them, which is invisible in almost every service.

The related but different flag, -XX:MaxMetaspaceSize, is a hard cap that turns a leak into an error, which I set in containers precisely so that a leak fails loudly with a stack trace rather than as an OOMKill.

Q78. "Where does off-heap memory come from in a normal Java service, why is it invisible to the heap metrics, and how do you see it?"

Reveal answer

Strong answer Off-heap means memory the process uses that the garbage collector does not manage. In a typical service it comes from five places.

Direct byte buffers, created by ByteBuffer.allocateDirect, are used by every NIO channel, by HTTP and database clients, and by Netty, because the kernel can read into and write from them without an extra copy.

The Java object is a tiny DirectByteBuffer on the heap holding the address; the bytes are native, freed by a Cleaner when the object is collected.

The total is capped by -XX:MaxDirectMemorySize, which defaults to the maximum heap size, and exceeding it throws OutOfMemoryError: Cannot reserve N bytes of direct buffer memory, after the JVM has tried a System.gc() to free stale buffers.

Memory-mapped files through FileChannel.map put file contents into the address space; the pages count toward the resident set as they are touched and are shared with the page cache. The foreign function and memory API's Arena allocations are native and freed when the arena closes.

Netty's PooledByteBufAllocator holds chunks of 4 MB by default in per-thread caches and arenas, so memory stays reserved after buffers are released, which looks like a leak but is a pool.

And the JVM's own native parts: metaspace, code cache, thread stacks, GC data structures, and the C library's heap. None of this appears in heap metrics because the heap metrics come from the collector's accounting of the Java heap, and these bytes were never in it.

What I see instead is a gap between the container's resident set size and the heap's committed size.

The tool that fills the gap is native memory tracking: start with -XX:NativeMemoryTracking=summary, then jcmd <pid> VM.native_memory summary prints reserved and committed bytes by category, with direct buffers and arenas under Other, class metadata under Class, stacks under Thread, and compiled code under Code.

The direct buffer pool specifically is on the java.nio:type=BufferPool,name=direct MBean, exposed by Micrometer as jvm.buffer.memory.used. Memory-mapped files are in neither; for those I read /proc/<pid>/smaps or pmap -x.

Land it The heap graph shows one tenant of the process; native memory tracking plus the buffer pool MBean plus the container's resident size are the three numbers that together account for what the kernel will kill you for.

Likely follow-ups
"Why does a direct buffer leak show up as a heap symptom sometimes?"

Because releasing direct memory depends on the collector noticing that the DirectByteBuffer object is unreachable. When the heap is large and quiet, young collections are rare, so unreachable buffer objects sit in eden holding their native memory.

The reservation code in java.nio.Bits handles the pressure by calling System.gc() and waiting briefly for the cleaners, which is why a service near its direct limit shows unexplained full collections; and if someone set -XX:+DisableExplicitGC, that rescue is gone and the error comes sooner.

The fix is not a bigger limit but explicit lifetime: reuse buffers from a pool, use Netty's reference counting with release(), or on JDK 22 or later allocate through an Arena that is closed deterministically.

"Which Arena kind would you use for what?"

Arena.ofConfined() for a segment used by one thread within one scope, such as a buffer for a native call inside a method, closed in a try-with-resources; it is the cheapest and safest because access from another thread throws.

Arena.ofShared() for memory read by many threads, such as a cache slab or a mapped file used across a pool; its close does a handshake with every thread and is expensive, so close it rarely.

Arena.ofAuto() when the lifetime genuinely matches an object's and I accept collector timing, similar to a direct buffer. Arena.global() for memory that lives as long as the process, such as a lookup table.

The rule is that the arena's owner is the code that knows the lifetime, and the segment is never passed further than the owner can see.

"Netty reports 800 MB of direct memory used but the buffer pool MBean shows 50 MB. Which is right?"

Both, measuring different things. By default Netty does not allocate its pooled chunks through the JDK's accounted ByteBuffer.allocateDirect path; it uses its own and tracks the total in PlatformDependent.usedDirectMemory(), bounded by -Dio.netty.maxDirectMemory, which defaults to the JVM's direct limit.

So the MBean only sees the JDK's own buffers. Netty's 800 MB includes chunks held in its pool that are free but not returned, so what the application actually holds may be far lower; its PooledByteBufAllocatorMetric gives chunk and active counts.

For the container budget the Netty number is the one to use, and if it is mostly idle pool I would reduce the arena count with -Dio.netty.allocator.numDirectArenas or the thread cache sizes.

"How do memory-mapped files interact with the container limit?"

A mapped file's pages are page cache, and the cgroup charges page cache to the container that touched it, so reading a 3 GB mapped index on a 4 GB pod counts against the limit.

The difference from anonymous memory is that clean file pages are reclaimable: under pressure the kernel drops them rather than killing the process, so the pod looks full but survives, and the cost is re-reading from disk.

Dirty pages from writes through a mapping must be written back first. The numbers are in the cgroup's memory.stat as file versus anon, and a pod that is OOMKilled with a large file share usually had a burst of dirty pages or anonymous growth alongside.

The practical rule is to count the working set of mapped files in the budget, and to prefer explicit reads with a bounded cache when the file is much bigger than the container.

Q79 · Scenario. "A pod keeps getting OOMKilled even though -Xmx is set to 60 percent of the container limit and the heap never goes above 80 percent full. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom decoded: the kernel killed the process because its total resident memory, heap plus everything else, crossed the cgroup limit. The heap staying under its own maximum says nothing about the rest. On a 4 GB limit with -Xmx2400m, the other 1.6 GB is the budget for metaspace, code cache, thread stacks, direct buffers, GC structures, the C library heap and page cache, and one of those has outgrown it. Also worth checking: whether -Xmx is really 60 percent, because -XX:MaxRAMPercentage and an explicit -Xmx together follow the explicit one, and a JAVA_TOOL_OPTIONS variable can override both silently.
  2. Evidence: kubectl describe pod shows the last termination reason as OOMKilled and the limit. jcmd <pid> VM.flags on a running replica confirms the effective heap and direct memory limits. With -XX:NativeMemoryTracking=summary enabled, jcmd <pid> VM.native_memory summary scale=MB gives committed bytes per category; the Thread category times count, the Class category for metaspace, Code for the JIT, GC for the collector's own structures, which for G1 are 5 to 10 percent of heap, and Other for direct buffers. The cgroup's memory.stat separates anonymous memory from page cache. The gap between RSS and NMT's total is untracked native memory.
  3. Causes, ranked: direct buffers, because MaxDirectMemorySize defaults to the heap maximum, so the process can legitimately use 2.4 GB of heap plus 2.4 GB of buffers, which exceeds the limit by design; a thread count in the thousands, each with a 1 MB reservation and typically a few hundred kilobytes committed; glibc arena fragmentation; metaspace and code cache growth in a service with heavy class generation; page cache from mapped files or heavy file reads, charged to the container; and a heap that is 80 percent used but 100 percent committed, since the kernel bills committed and touched pages, not used objects.
  4. Fix: write the budget explicitly and enforce it with flags: -XX:MaxRAMPercentage=55, -XX:MaxDirectMemorySize=256m, -XX:MaxMetaspaceSize=256m, -XX:ReservedCodeCacheSize=128m, -Xss512k if threads are many, MALLOC_ARENA_MAX=2, and -XX:+ExitOnOutOfMemoryError so that hitting one of those caps restarts cleanly with a Java error rather than a kill. Then fix whichever consumer NMT named.
  5. Prevention: NMT on in staging, an alert on RSS at 85 percent of the limit, and a rule that no service sets -Xmx without also setting the direct memory cap.

Land it The heap percentage was a guess about the rest of the process, and the fix is to replace the guess with caps on every native consumer so the JVM fails with a stack trace instead of the kernel failing it without one.

Likely follow-ups
"You capped direct memory and metaspace, NMT shows 3.2 GB committed in total, but the pod still dies at 4 GB. What next?"

The remaining 800 MB is outside NMT. I would read the cgroup's memory.stat inside the container: if file is large, it is page cache from files the service reads or maps, and I would check for a large mapped file or a logging setup that writes gigabytes locally; if anon exceeds NMT's total, it is untracked native allocation.

For untracked, pmap -x <pid> sorted by RSS shows 64 MB anonymous blocks for glibc arenas or a growing region from a native library.

I would also check for a second process in the container, such as a sidecar agent launched by the entrypoint, because the cgroup limit covers all processes in the pod's container.

And I would verify that -Xms is not larger than -Xmx through an override, which the JVM adjusts silently.

"Why does a heap that is 80 percent used still cost the full -Xmx in resident memory?"

Because the collector touches memory in ways that commit it.

G1 commits the whole heap up front if -Xms equals -Xmx, which many teams set to avoid resize pauses, and every eden region is written to as allocation cycles through it, so pages become resident even if the live set is small.

The used figure the heap graph shows is live plus garbage at that instant, while RSS is every page that has ever been written and not returned.

G1 does uncommit memory after a concurrent cycle on JDK 12 or later if the heap is above -Xms and idle, and ZGC uncommits after ZUncommitDelay, but a busy service never qualifies as idle.

So for the container budget I treat -Xmx as fully spent, whatever the graph shows.

"How would you pick between raising the container limit and lowering the heap?"

From the GC log. If after-GC occupancy is under half of -Xmx and pauses are fine, the heap is oversized and I would lower it, which is free.

If occupancy is 60 to 70 percent and the collector is busy, lowering it moves the failure from OOMKill to GC thrashing, and I need the memory, so the limit goes up.

The arithmetic is live set times two to three for G1 plus the measured native total plus 10 percent margin; if that exceeds the limit, the limit is wrong.

One warning: raising the limit changes MaxRAMPercentage's result too, so a service using the percentage grows its heap with the limit and the native budget does not improve. Explicit -Xmx avoids that coupling when I am trying to give room to the native side.

Q80 · Design. "Design the standard playbook your team uses to tell a memory leak from a large footprint from GC pressure across a fleet of JVM services, and the heap sizing rule that follows from it."

Reveal answer

Strong answer Requirements and assumptions: dozens of services on G1 and some on generational ZGC, on-call engineers who are not GC specialists, and a need to reach a named cause in under an hour with evidence that survives a restart.

Design: the playbook starts from one graph, the heap occupancy immediately after each collection, which I expose as the jvm.gc.live.data.size style metric from the GC notification or from JFR's jdk.GCHeapSummary with the after-GC value. Its shape decides the branch.

A staircase that climbs day over day and never returns to a floor is a leak. A flat line at a high level from startup onward is a large footprint, meaning the service simply holds a lot of live data.

A low, flat floor with a fast sawtooth above it and rising pause counts is GC pressure, meaning a high allocation rate of short-lived objects. Each branch has its fastest evidence.

For a leak: jcmd <pid> GC.class_histogram twice, an hour apart, and diff the instance counts; the class whose count grows with the staircase is the leaked type, and the heap dump from jcmd <pid> GC.heap_dump opened in Eclipse MAT's dominator tree gives the single object that retains it, usually a static collection or a cache without eviction.

For footprint: the same dominator tree read for the top three retainers, then the question of whether that data belongs on the heap at all or should move off-heap or to a store.

For pressure: a 60-second JFR recording with jdk.ObjectAllocationSample read by allocating stack, and the top frames are the fix.

The sizing rule follows: for G1, -Xmx at two to three times the after-GC floor, because it needs room to evacuate and to let objects die in eden; for generational ZGC, the floor plus at least 25 to 30 percent headroom, more when the allocation rate is high, because it must allocate while collecting; and never above 32 GB on G1 without an explicit decision about compressed oops.

Every service records -Xlog:gc* with rotation and sets -XX:+HeapDumpOnOutOfMemoryError to a persistent volume.

Trade-offs: a heap dump on a 30 GB service takes minutes and pauses the process, so the histogram comes first; JFR allocation sampling is cheap enough to leave on; the sizing rule wastes memory on services with very stable live sets, which is the price of headroom.

What I would not do: alert on heap usage percentage, which is meaningless between collections; size heaps from peak usage rather than after-GC usage; or let engineers tune collector flags before the branch has been identified.

Land it The after-GC floor is the one number that separates the three problems, and every other tool in the playbook exists to name the class or the stack behind the shape of that line.

Likely follow-ups
"The requirement changes: half the fleet moves to generational ZGC. Which parts of the playbook stop working?"

The shape reading still works, but the numbers shift. ZGC's after-cycle occupancy includes floating garbage from concurrent marking, so the floor reads higher than the true live set, and the sawtooth is gentler because collection is continuous.

The pressure branch changes its symptom: instead of rising pause counts I look for Allocation Stall lines and for cycles triggered by Allocation Rate running back to back. The class histogram and heap dump work unchanged.

The sizing rule changes from two to three times the floor to floor plus headroom, and the 32 GB rule disappears because ZGC has no compressed oops.

One addition: an alert on ZGC's concurrent CPU time from -Xlog:gc+cpu, because a collector that quietly consumes two cores is the ZGC form of pressure.

"What would you cut under time pressure?"

I would ship the graph, the histogram diff and the two flags, and cut the rest. The after-GC occupancy graph comes almost free from existing JVM metrics, and the two GC.class_histogram runs need no tooling beyond jcmd; between them they resolve most leaks and identify footprint.

The two flags, -Xlog:gc* to a rotated file and -XX:+HeapDumpOnOutOfMemoryError, make sure the next incident leaves evidence. I would postpone the JFR allocation workflow and the MAT training, because GC pressure is the least urgent branch: it costs latency rather than availability.

I would also postpone re-sizing every heap, and only apply the rule to services that had an incident.

"How do you tell a slow leak from a cache that is still warming up?"

By whether the staircase has a ceiling. A bounded cache climbs and then flattens once it reaches its maximum size, which for a Caffeine cache with maximumSize is predictable from the entry count, and its histogram shows the entry class count stabilising.

A leak climbs at a rate proportional to traffic and never flattens; two histograms a day apart show the class count still growing at the same rate.

If the service restarts before the ceiling would be reached, I compare the growth rate against the request count: a cache grows with distinct keys, which saturates, and a leak grows with total requests, which does not.

When it is ambiguous I force a full collection with jcmd <pid> GC.run before each histogram so both numbers are live objects only.

"Why after-GC occupancy rather than the usual heap-used metric that dashboards show?"

Heap used at an arbitrary instant is live objects plus whatever garbage has accumulated since the last collection, so it swings between the floor and -Xmx every few seconds and tells me only where in the cycle the sample landed.

Dashboards that show it at 90 percent cause false alarms, and dashboards that average it hide leaks.

The value right after a collection is the closest cheap estimate of live data; after a young collection it slightly overstates because old has not been collected, and after a mixed or full collection it is accurate.

I take the minimum over a window, which lands on the post-collection points, and that series is the one that a leak makes climb and that a sizing rule should be computed from. The JFR event and the GarbageCollectionNotificationInfo callback both provide it directly.

10 · DrillVirtual Threads, Modern Concurrency & Language Features — Q81–Q115

These thirty-five questions test whether you can say what a virtual thread is made of, where it still pins, how structured concurrency and scoped values change fan-out code, what ForkJoinPool and CompletableFuture do underneath, and what records, sealed types, pattern matching, gatherers, the FFM API and modules buy in real code, with the JDK 21 to 27 status of each as of August 2026.

Drill · Virtual threads under the hood

This group tests whether you can explain what a virtual thread physically is, what makes one leave its carrier and what does not, and how you would find the one that is stuck, rather than repeating "lightweight threads" and stopping.

Q81. "What is a virtual thread made of inside the JVM? Walk me through what happens when one blocks and later resumes."

Reveal answer

The real test Whether you know the three parts, the continuation, the scheduler and the carrier, and can say where the stack lives while the thread is parked.

Strong answer A virtual thread is a java.lang.Thread object that is not backed by an operating-system thread. It is made of three things.

The first is a continuation, the internal class jdk.internal.vm.Continuation, which is a piece of code that can be paused in the middle and resumed later, together with the stack frames it needs.

The second is a scheduler, which by default is a ForkJoinPool running in FIFO mode, meaning first-in, first-out, so submitted tasks are started in order rather than the last-in-first-out order a fork-join pool normally uses.

The third is a carrier, a platform thread owned by that pool, on which the continuation actually runs. Running the virtual thread is called mounting: the scheduler picks a carrier and the carrier executes the continuation.

When the virtual thread calls something that blocks, for example a socket read, the JDK does not block the carrier.

Instead the continuation yields: the JVM copies the frames belonging to the virtual thread off the carrier's native stack into heap objects called stack chunks, records where it stopped, and returns the carrier to the pool. That is unmounting.

When the I/O completes, the poller thread submits the continuation back to the scheduler, a carrier picks it up, the frames are copied back lazily and execution continues after the blocking call.

The cost that makes this worthwhile is small: creating a virtual thread takes about a microsecond and about a kilobyte of heap, compared with a platform thread's reserved stack of hundreds of kilobytes and a system call.

The scheduler's size is jdk.virtualThreadScheduler.parallelism, which defaults to the number of available processors, and it can temporarily grow to jdk.virtualThreadScheduler.maxPoolSize, default 256, to compensate when carriers get stuck.

what a virtual thread is, and what happens when it blocksruns offline
// A virtual thread is a Java OBJECT: a Continuation plus a Runnable, scheduled
// onto a small pool of platform "carrier" threads (a ForkJoinPool by default).
Thread.ofVirtual().start(() -> {
    var response = httpClient.send(request, ofString());   // blocks
    process(response);
});

// WHAT HAPPENS AT THE BLOCKING CALL:
// 1. The JDK's socket implementation is instrumented. It does not block the OS
//    thread; it registers interest with the poller and calls Continuation.yield().
// 2. yield() COPIES THE VIRTUAL THREAD'S STACK from the carrier's stack into
//    the heap. That is the whole trick: the stack becomes an object.
// 3. The carrier thread is released and immediately runs another virtual thread.
// 4. When the socket is readable, the scheduler submits the continuation.
// 5. Continuation.run() COPIES THE STACK BACK onto some carrier — possibly a
//    DIFFERENT one from before — and execution resumes at the exact instruction.
//
// Cost: ~1 KB of heap that grows on demand, versus a 1 MB pre-reserved platform
// stack. That is why millions of virtual threads are feasible and millions of
// platform threads are not.

// THE CONSEQUENCE THAT BREAKS CODE: the carrier can change across a blocking
// call, so ANYTHING keyed to the carrier thread is wrong:
ThreadLocal<Connection> CONN;      // still works (it is per-VIRTUAL-thread)
synchronized (lock) { io(); }      // pins before JDK 24 — see the next question

Step 2 is the entire idea. Blocking becomes a stack copy into the heap rather than an OS thread parking, which is why the cost of concurrency drops from megabytes per connection to kilobytes — and why the JDK had to reimplement every blocking API to cooperate.

Land it A virtual thread is a stack you can put in the heap and a scheduler that knows how to put it back on a CPU, and everything about its performance follows from that copy.

Likely follow-ups
"Why FIFO mode for the scheduler, and can I replace the scheduler?"

FIFO gives fairness of start order. A fork-join pool's normal mode runs the most recently submitted task first because that is best for divide-and-conquer work, but for thousands of independent requests it would starve older ones.

FIFO mode, which ForkJoinPool calls asyncMode, hands out work in arrival order.

As of Aug 2026 there is no supported public API to plug in your own scheduler; the JDK team has a pluggable-scheduler prototype and an internal system property, but I would treat that as unsupported and verify on the JEP page before relying on it.

What you can tune today are the properties jdk.virtualThreadScheduler.parallelism, maxPoolSize and minRunnable, and I only touch parallelism, for example lowering it in a container where the JVM sees more CPUs than its quota.

"What does copying frames to the heap cost, and does it happen on every block?"

Each unmount, called a freeze, copies the frames that changed since the last freeze into a stack chunk object, and each mount, called a thaw, copies back only the top frames needed to resume, pulling more on demand.

In practice a freeze and thaw pair costs on the order of a microsecond for a shallow stack, and it scales with stack depth, so a virtual thread that blocks inside twenty framework layers pays more than one that blocks near the top.

Yes, it happens on every blocking operation that unmounts; a lock acquired without contention or a read that returns immediately does not unmount, because the fast path never parks.

The garbage collector also sees the chunks as ordinary objects, which is why a million parked virtual threads cost a few hundred megabytes of heap rather than a few hundred gigabytes of native stack.

"How does the JVM find the frames of a virtual thread if they are on the heap when a GC or a stack walk runs?"

Stack chunks are ordinary Java objects of the internal type jdk.internal.vm.StackChunk, so the collector scans them like any other object and updates the references inside the copied frames when it moves things.

For stack walks the JDK made StackWalker, exception construction and JFR sampling aware of chunks: when a virtual thread is mounted its frames are on the carrier's native stack and are walked there, and when it is parked the walker reads the chunk.

That is also why a plain jstack cannot show you a parked virtual thread: it lists native threads, and a parked virtual thread has none. The new thread dump, jcmd <pid> Thread.dump_to_file -format=json out.json, walks the chunks and lists every virtual thread.

Q82. "Which operations let a virtual thread leave its carrier, which ones pin it, and what changed in JDK 24?"

Reveal answer

The real test Whether you know the pinning rules as they stand today, including that synchronized stopped being a problem in JDK 24, rather than repeating advice from 2023.

Strong answer Almost everything in the JDK that blocks has been rewritten to unmount. Socket reads and writes go through the JDK's poller threads: the virtual thread registers interest, parks and unmounts, and the poller wakes it when data arrives.

LockSupport.park, and therefore ReentrantLock, Semaphore, CountDownLatch, every BlockingQueue, Thread.sleep and Future.get, all unmount because they park through the same path.

File I/O is the exception that cannot be made asynchronous on most operating systems, so the JDK compensates: while a virtual thread is inside a blocking file read the scheduler temporarily adds a carrier, up to the maxPoolSize of 256, so throughput does not collapse.

Pinning is the bad case. It means the virtual thread cannot be unmounted, so it holds its carrier while it waits, and if enough carriers are held the whole scheduler stalls.

Until JDK 23, entering a synchronized block or calling Object.wait pinned, because the monitor implementation recorded the owning native thread.

JEP 491 in JDK 24 rewrote monitors so that synchronized and Object.wait now unmount like everything else, and that removes the most common pinning cause in real code.

Two cases still pin as of Aug 2026: a native frame on the stack, which means JNI, the Java Native Interface, or a foreign-function call through the FFM API, because the JVM cannot copy a C stack frame to the heap; and blocking during class initialisation that runs a static initialiser.

The way to see pinning is the JDK Flight Recorder event jdk.VirtualThreadPinned, which since JDK 24 records the reason and the stack; the older -Djdk.tracePinnedThreads property was removed in 24, so I would verify on the release notes before quoting it.

what pins a virtual thread, and how to find itruns offline
// PINNING = the virtual thread cannot unmount, so it holds its carrier thread
// while blocked. Enough pinned threads and the carrier pool is exhausted:
// the service stalls with low CPU, which is the signature in Q88.

// PINS (before JDK 24):
synchronized (lock) {
    jdbc.query(...);          // blocking I/O inside a monitor -> PINS
}
// FIXED IN JDK 24 by JEP 491: synchronized no longer pins.

// STILL PINS on every version:
//   - a native frame on the stack: any JNI call that blocks
//   - Object.wait() inside synchronized on older versions
//   - a few JDK internals that take a monitor around I/O

// DOES NOT PIN — the operations that were reimplemented to yield:
//   Socket / SocketChannel I/O, java.net.http, files on most platforms,
//   Thread.sleep, BlockingQueue, ReentrantLock, CompletableFuture.join,
//   and every java.util.concurrent lock.

// THE PORTABLE FIX — a ReentrantLock never pins on any version:
private final ReentrantLock lock = new ReentrantLock();
lock.lock();
try { jdbc.query(...); }      // unmounts cleanly
finally { lock.unlock(); }
detecting it in productionruns offline
# Development: print a stack trace every time a thread pins.
java -Djdk.tracePinnedThreads=full -jar app.jar

# Production: JFR has a dedicated event, at negligible cost.
jcmd <pid> JFR.start name=pin settings=profile duration=120s filename=pin.jfr
#   -> jdk.VirtualThreadPinned  (carries the duration and the full stack)

# And check the carrier pool is not simply exhausted:
jcmd <pid> Thread.dump_to_file -format=json threads.json
#   virtual threads appear as "VirtualThread[#123]" with their carrier named

jdk.VirtualThreadPinned is the event to alert on. Pinning is not an error and produces no exception — the only symptom is a service that stalls under load with idle CPU, so it has to be found by looking for it rather than by waiting for a failure.

Land it On JDK 24 or later the rule is simple: if there is no native frame on the stack, a blocking call unmounts, so the pinning inventory reduces to "where do we call native code".

Likely follow-ups
"We are on JDK 21. What exactly happens when a virtual thread blocks inside synchronized, and how bad is it?"

On 21 the virtual thread is pinned: it stays on its carrier, and the carrier is blocked for as long as the wait lasts. If the block only protects a short in-memory update it is harmless, because nothing blocks.

The damage comes when code blocks for I/O while holding a monitor, for example a JDBC driver that wraps a socket read in synchronized, or a cache with a synchronized loader that calls a remote service.

With eight carriers, eight such calls in flight freeze every other virtual thread in the process. The JDK partly protects you by adding carriers up to 256, but that is a stopgap.

On 21 the fixes are to replace those synchronized blocks with ReentrantLock, to upgrade libraries that did so, or to upgrade to 24 or later where the problem disappears.

"How does the file I/O compensation work, and why can it still bite?"

When a virtual thread is about to make a blocking file system call the JDK marks the carrier as blocked using ForkJoinPool.ManagedBlocker, which tells the pool to start an extra worker so the parallelism target is still met.

The extra worker is released when the call returns. It works because file reads usually finish in milliseconds.

It bites when they do not: a network file system that hangs, or a thousand virtual threads doing large sequential reads at once, can push the pool to its 256 cap and then everyone waits.

It also means a service that does heavy file I/O on virtual threads is actually running on up to 256 platform threads, which surprises people who sized memory for a handful of carriers. For sustained file work I keep a dedicated platform thread pool.

"How would you prove in production that pinning is or is not the problem?"

I would start a recording with jcmd <pid> JFR.start name=pin duration=120s settings=profile, then print only the pinning events with jfr print --events jdk.VirtualThreadPinned recording.jfr.

Each event has the duration the thread stayed pinned, the reason on JDK 24 and later, and the stack, so I can see the exact frame, typically a JNI method.

The event has a threshold, 20 milliseconds by default, so short pins are not recorded unless I lower it in the settings file. If the event count is zero during the incident, pinning is not the cause and I look at resource exhaustion instead.

I would also take jcmd <pid> Thread.dump_to_file -format=json and count how many virtual threads share the same blocking frame.

"Does class initialisation pinning matter in practice?"

Rarely, but it produces the most puzzling incident when it does.

If a class's static initialiser blocks, for example it opens a connection or waits on a latch, the virtual thread that triggered initialisation is pinned, and every other virtual thread that touches the class blocks waiting for initialisation to finish while pinned too.

On a service that warms up under load, a static initialiser that calls a remote config service can pin every carrier at once during the first second.

The fix is to keep static initialisers free of blocking work and move it into an explicit init method, and I would spot it in the JFR pinning event's stack as a frame inside <clinit>.

Q83 · Scenario. "A report-generation endpoint was moved to virtual threads. Now, when a few reports run, every other request on the service, including health checks, times out. CPU is at 100 percent. What is going on?"

Reveal answer

The real test Whether you know that virtual threads are not time-sliced, so a CPU-bound one holds its carrier until it blocks or finishes.

Strong answer I would diagnose in this order:

  1. The symptom pattern, everything slows while a handful of heavy tasks run and CPU is saturated, points at scheduling rather than pinning. The virtual thread scheduler is cooperative: a virtual thread runs until it blocks, yields or finishes. There is no timer that takes the carrier away from it, unlike the operating system's scheduler for platform threads. A report that spends five seconds building a PDF without any blocking call owns its carrier for five seconds.
  2. Evidence: a JSON thread dump with jcmd <pid> Thread.dump_to_file -format=json d.json shows the carriers, named like ForkJoinPool-1-worker-3, each running a report thread, and hundreds of runnable virtual threads waiting in the scheduler queue. A JFR recording with the JDK 25 CPU-time profiler, jdk.CPUTimeSample, attributes the CPU to the report code, and jdk.VirtualThreadPinned is empty, which rules pinning out.
  3. Ranked causes: CPU-bound work on virtual threads is the first; second, the scheduler parallelism equals the number of CPUs the JVM sees, which in a container with a two-CPU quota may be two, so two reports are enough; third, the reports were previously throttled by a small dedicated pool that the migration removed.
  4. Fix: move CPU-heavy work to a bounded platform thread pool, for example Executors.newFixedThreadPool(2) for reports, and keep virtual threads for the request handling around it. If the report must stay on a virtual thread, insert Thread.yield() at natural checkpoints, which lets the scheduler run other threads, and wrap the work in a Semaphore with a small number of permits. Check that jdk.virtualThreadScheduler.parallelism matches the container CPU quota.
  5. Prevention: a rule in the team's guidelines that virtual threads are for waiting, not computing, and a dashboard panel for scheduler queue length derived from the thread dump or from the JFR jdk.VirtualThreadSubmitFailed and start/end events.

Land it Virtual threads raise the throughput of waiting, not the speed of computing, so anything that computes for long needs a platform pool or a yield point.

Likely follow-ups
"Why did the JDK not add time-slicing to the virtual thread scheduler?"

Preemption would need a safe place to stop the thread, which the JVM only has at safepoints, and it would need to copy the whole stack to the heap at an arbitrary point where a lock or a JIT-compiled frame may be live.

That is expensive and complicated, and the designers judged that the target workload, servers that mostly wait on I/O, does not need it because such threads block naturally every few microseconds.

The JDK documentation explicitly says a virtual thread should not be used for long CPU-bound work. There has been discussion of a time-sharing option, but as of Aug 2026 nothing has shipped, so I would design around the cooperative model rather than wait for it.

"The fix didn't work: reports now run on a platform pool, but health checks still time out under load. What next?"

Then a second CPU consumer is still on the carriers. I would take the JSON thread dump again during the stall and read the carriers' frames.

Common findings are JSON serialisation of very large responses, compression in a servlet filter, or a regular expression with catastrophic backtracking, all of which look like ordinary request handling but burn CPU for seconds.

If the carriers are idle and the health check still times out, the bottleneck has moved: perhaps the report pool now saturates the database connection pool that the health check also needs, which I would confirm from the Hikari metrics hikaricp.connections.pending.

Giving the health check its own tiny connection or a cached answer is the usual resolution.

"What does Thread.yield() actually do on a virtual thread?"

On a virtual thread Thread.yield() unmounts the continuation and puts it at the back of the scheduler's queue, so every runnable virtual thread ahead of it gets a turn before it resumes.

It costs a freeze and thaw, roughly a microsecond, so calling it every few thousand iterations of a hot loop is cheap and effective. On a platform thread it is only a hint to the operating system and often does nothing.

I would place yields at loop boundaries in the report code rather than sprinkling them, and I would measure with a JFR recording that the scheduler queue no longer backs up.

Q84 · Design. "Design request-context propagation, the tenant id, trace id and deadline, for a service running on virtual threads. We currently use ThreadLocal."

Reveal answer

The real test Whether you know why ThreadLocal scales badly with millions of threads and can explain what ScopedValue gives instead, including how the value reaches forked subtasks.

Strong answer Requirements: three values set once at the edge of a request, readable anywhere below it without passing parameters, visible in tasks the request forks, and never leaking into another request.

Assumptions: JDK 25 or later, where ScopedValue is final under JEP 506, and structured concurrency for fan-out. The problem with ThreadLocal is structural.

Each virtual thread gets its own map, so with a million threads there are a million maps; the values are mutable, so nothing stops a deep layer overwriting the tenant; they live until the thread dies or someone remembers remove(); and InheritableThreadLocal copies the whole map into every child, which for a fan-out of twelve is twelve copies per request.

Design: one immutable record, RequestContext(tenantId, traceId, deadline), and one static final ScopedValue<RequestContext> CTX = ScopedValue.newInstance(). The edge filter binds it for the duration of the request with ScopedValue.where(CTX, ctx).run(() -> chain.doFilter(req, res)).

Any code below reads CTX.get(); outside the binding get() throws and CTX.isBound() is false, so a leak is impossible by construction.

Inside a StructuredTaskScope opened within the binding, every forked subtask sees the same binding automatically, with no copying, because the scope captures the caller's bindings once.

Rebinding is allowed but only nested: a layer that needs a shorter deadline calls ScopedValue.where(CTX, ctx.withDeadline(d)).call(...), and the outer value returns when that call ends.

Trade-offs: code that ran on a plain executor rather than a scope loses the binding, so those call sites must capture the record explicitly; libraries that still read ThreadLocal, such as an older MDC for logging, need a small bridge that copies the trace id into the MDC at the same edge.

What I would not do is keep InheritableThreadLocal and hope, or put mutable objects into a scoped value, because immutability is the whole point.

Land it A scoped value is a read-only variable with a lifetime tied to a block of code instead of a thread, which is exactly the shape a request context has and exactly what a thread-local is not.

Likely follow-ups
"The requirement changes: some downstream calls are dispatched to a plain ExecutorService, not a scope. How does the context reach them?"

A scoped value binding is not carried into a task submitted to an arbitrary executor, because the executor's thread is not part of the binding's dynamic scope. Two options.

The clean one is to capture explicitly: read CTX.get() before submitting, and inside the task call ScopedValue.where(CTX, captured).run(work); a small wrapper on the executor can do this for every submission.

The other is to replace the executor with a StructuredTaskScope at that call site, which inherits automatically and also gives cancellation and a clear lifetime. I would take the wrapper only for legacy paths, because an unstructured executor with request context is how leaks return.

"Why is ScopedValue.get() fast enough to call in a hot path?"

The bindings are stored in a small immutable structure on the current thread, and each thread keeps a tiny cache indexed by the scoped value's hash, so a lookup is a couple of array reads in the common case.

It is designed to be cheaper than ThreadLocal.get(), which hashes into a per-thread map with linear probing. It is also faster to create the binding, because where(...).run(...) pushes one node rather than copying a map.

The JDK measured this precisely because the intended users are frameworks calling it on every request, and the same mechanism is what makes inheritance into a thousand forked subtasks free.

"What would you cut under time pressure?"

I would cut the nested rebinding for per-layer deadlines and keep one deadline set at the edge, because that is the feature most likely to be misused. I would also cut the MDC bridge from the first release and instead log the trace id explicitly from the value at the few places that matter. I would not cut the immutability of the record, and I would not cut the edge binding through ScopedValue.where(...).run(...), because a half-migrated mix of thread-locals and scoped values is worse than either alone.

"Which JDK do you need, and what if you are stuck on 21?"

Scoped values were a preview API in JDK 21 through 24, so on 21 they would need --enable-preview at compile time and at run time, which I would not do in production.

On JDK 25, as of Aug 2026, java.lang.ScopedValue is a final API under JEP 506, so the design needs 25.

Stuck on 21, I would keep a ThreadLocal holding one immutable record, set and cleared in a try-finally at the edge, and pass the record explicitly into anything submitted to an executor.

That copies the discipline of scoped values without the API, and it makes the later switch a mechanical replacement.

Q85. "Why should you not pool virtual threads, and if you do not pool them, how do you limit concurrency?"

Reveal answer

Strong answer A thread pool exists because platform threads are expensive to create and limited in number, so we create a few and reuse them. Both reasons disappear with virtual threads: creating one costs about a microsecond and a kilobyte, and a process can hold millions.

So pooling them buys nothing and costs a lot. The pool's queue turns into a bottleneck, the pool size becomes an accidental throttle on every kind of work, and anything that depends on thread identity, such as a ThreadLocal cache, silently starts sharing state between requests.

The intended model is one virtual thread per task. Executors.newVirtualThreadPerTaskExecutor() gives an ExecutorService that starts a fresh virtual thread for every submitted task and never reuses one; it exists so that code written against the executor interface keeps working.

For frameworks that ask for a factory, Thread.ofVirtual().name("worker-", 0).factory() produces a ThreadFactory. What a pool used to give you as a side effect, a limit on concurrent work, you now express directly on the resource that actually has a limit.

If the database can handle 20 concurrent queries, that is the Hikari maximumPoolSize of 20, and the twenty-first virtual thread waits on the pool, unmounted and cheap.

If a downstream service allows 50 concurrent calls, a Semaphore(50) around the call expresses that; acquire() parks the virtual thread without holding a carrier.

The number lives next to the thing it protects, which is clearer than a pool size that had to be the minimum over every resource the pool touched.

do not pool virtual threads — limit the resource insteadruns offline
// WRONG — pooling defeats the entire point. A pool exists to amortise the cost
// of creating a thread; a virtual thread costs almost nothing to create, and
// pooling reintroduces the fixed concurrency limit you were trying to escape.
var pool = Executors.newFixedThreadPool(200, Thread.ofVirtual().factory());   // pointless

// RIGHT — one virtual thread per task, unbounded.
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (var task : tasks) executor.submit(() -> handle(task));
}   // close() waits for all of them

// BUT you still need to limit concurrency — not because threads are scarce,
// but because the RESOURCE behind them is. Use a Semaphore, which limits
// the scarce thing directly and lets everything else proceed.
private final Semaphore dbPermits = new Semaphore(20);      // match the pool size

void handle(Task t) {
    parse(t);                       // unlimited concurrency: it is only CPU
    dbPermits.acquire();
    try { repo.save(t); }           // at most 20 at a time, matching Hikari
    finally { dbPermits.release(); }
    notifyDownstream(t);            // limited by ITS own semaphore, separately
}

Read what the semaphore is protecting. One limit per scarce resource — connections, a downstream service's rate limit, memory for buffers — rather than one global thread count standing in for all of them, which is what a thread pool actually was.

Land it The pool was never the thing you wanted to limit; it was a proxy for the resources behind it, and virtual threads let you limit those directly.

Likely follow-ups
"Spring's spring.threads.virtual.enabled=true: what does it change and what does it leave alone?"

As of Aug 2026 that property makes Boot configure Tomcat's connector, the application task executor, the scheduler and several messaging listeners to use a virtual-thread-per-task executor instead of a bounded platform pool.

What it leaves alone is every explicit limit you set elsewhere: Hikari's pool size, a RestClient's connection pool, the size of any executor you created yourself.

So the acceptor now admits as many requests as arrive, and the first fixed limit they meet is usually the connection pool.

The important consequence is that server.tomcat.threads.max stops mattering, and if that number was your only backpressure you must replace it with limits on the resources, which is the whole migration in one sentence.

"Is there any situation where you would still wrap virtual threads in a bounded executor?"

Yes, one: when the limit is on the number of concurrent tasks as such, not on a resource. An example is a batch job where each task holds a large buffer and I want at most 200 buffers alive.

There I would still not use a fixed pool of virtual threads; I would use newVirtualThreadPerTaskExecutor() plus a Semaphore(200) acquired before submitting, so memory is bounded but threads are not reused.

Another honest answer is a library that insists on a ThreadPoolExecutor type; then I pass a factory from Thread.ofVirtual().factory() into it, accept that the pool will reuse threads, and make sure nothing there depends on thread identity.

"How does a Semaphore behave differently from a pool queue when the limit is hit?"

A pool queue is usually unbounded by default, so callers never see pressure; tasks pile up in memory until the process dies.

A Semaphore makes the caller wait in acquire(), or fail fast with tryAcquire(timeout), which is a real backpressure signal that a request handler can turn into a 503 response. It also has no memory cost per waiter beyond the parked virtual thread.

The design choice is whether waiting is acceptable: for a user request I prefer tryAcquire(200, MILLISECONDS) and a clear error, because a request that waited three seconds for a permit is usually already abandoned by its client.

Q86 · Scenario. "A batch coordinator running on virtual threads never finishes; one job is 'stuck' somewhere. jstack shows nothing useful. How do you find it?"

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: work that should complete does not, and jstack shows only the carriers, all idle in the fork-join pool. That is expected. jstack lists native threads, and a parked virtual thread has no native thread; its frames sit in heap stack chunks. So the absence of the job in jstack is not evidence that it is gone.
  2. Evidence: the new dump, jcmd <pid> Thread.dump_to_file -format=json -overwrite dump.json, lists every thread including virtual ones, grouped by their container, which is the executor or structured scope that owns them. I would search the JSON for the job's thread name, which is why I always name virtual threads with Thread.ofVirtual().name("job-", 0), and read its frames. A second dump thirty seconds later shows whether the frames changed.
  3. Ranked causes: the thread is parked on something that will never complete, for example a Future.get() on a task that failed silently or a BlockingQueue.take() on an empty queue; it is waiting for a resource such as a connection pool that has leaked to zero; it is pinned inside a native call, which the JFR event jdk.VirtualThreadPinned shows; or it finished with an uncaught exception that the coordinator swallowed, so the thread is not in the dump at all, which the JFR events jdk.VirtualThreadStart and jdk.VirtualThreadEnd reveal when correlated by thread id.
  4. Fix: for the parked cases, add a timeout to the wait and log the failure; for a leaked pool, find the leak with Hikari's leakDetectionThreshold; for pinning, move the native call to a platform thread; for the swallowed exception, install an uncaught-exception handler through Thread.ofVirtual().uncaughtExceptionHandler(...) and fail the job visibly.
  5. Prevention: named virtual threads, a structured scope per batch so the tree of jobs appears as a unit in the dump, a continuous JFR recording with the virtual thread events enabled, and a watchdog that dumps threads automatically when a job exceeds its expected duration.

Land it The tools changed with the threads: Thread.dump_to_file and the JFR virtual-thread events replace jstack, and naming your threads is what makes them usable.

Likely follow-ups
"The fix didn't work: the JSON dump has fifty thousand virtual threads and you cannot find the stuck one. What next?"

Then I stop reading and start aggregating.

A short script groups the threads by their top three frames, which turns fifty thousand entries into perhaps twenty groups with counts; the stuck job is usually in a group of one or in a group whose frame is a wait that should not be there.

If the threads were created inside a StructuredTaskScope, the dump nests them under the scope, so I can find the batch's scope and look only at its children.

If naming is absent, I would correlate with JFR: jfr print --events jdk.VirtualThreadStart gives thread id and stack at creation, and the ids without a matching jdk.VirtualThreadEnd after the expected duration are the candidates.

"Why is jdk.VirtualThreadStart disabled by default, and what does enabling it cost?"

Because a busy service can start hundreds of thousands of virtual threads per second, and an event per start with a stack trace would dominate the recording.

Enabling it in the JFR settings file, or with jfr configure to produce a custom .jfc, costs a stack walk per thread start, on the order of microseconds each, plus disk space.

For a batch coordinator that starts a few thousand threads it is negligible, and I would keep it on.

For a high-rate service I would enable it only during an investigation, or rely on the jdk.VirtualThreadPinned and jdk.VirtualThreadSubmitFailed events, which fire rarely and are on by default.

"What does jdk.VirtualThreadSubmitFailed tell you?"

It fires when the scheduler could not accept a virtual thread to run, which in the default configuration means the fork-join pool's own submission failed, typically because the JVM is shutting down or the pool was somehow terminated.

It is rare and it is serious: a virtual thread that cannot be submitted never runs, and a coordinator waiting on it waits forever. Seeing this event in a stuck-job investigation ends the investigation, because the cause is the scheduler and not the job.

I would treat any occurrence as an alert and look at what shut the pool down, which has in practice been a custom scheduler property or a test harness that called System.exit on another thread.

Q87 · Design. "We are moving an order service to virtual threads and the product team expects ten times the throughput. Design the capacity model: where is the real ceiling, and how would you size it?"

Reveal answer

The real test Whether you can reason with Little's law and name the resources that actually bound throughput once the thread limit is gone.

Strong answer Requirements and assumptions: a request touches the database once, about 8 milliseconds, and calls a payment gateway once, about 120 milliseconds; the box has four CPUs; today Tomcat's 200 platform threads are the visible limit.

The first thing I would say is that virtual threads remove one ceiling, the thread count, and expose the next ones. Little's law gives the relation: concurrency equals throughput times time in system.

At 1,000 requests per second with 130 milliseconds per request the service needs 130 requests in flight, which 200 threads already covered, so the thread limit was not the ceiling and virtual threads alone will not give ten times.

The next ceilings, in order: the Hikari pool, which with maximumPoolSize=20 and 8 milliseconds per query allows 20 divided by 0.008, about 2,500 queries per second, before requests queue for a connection; the gateway's rate limit and its latency, since 120 milliseconds times 10,000 requests per second would mean 1,200 concurrent calls open against it; and CPU, where serialisation and TLS at perhaps 1 millisecond of CPU per request cap four cores near 4,000 requests per second.

Design: keep Hikari as the database throttle and size it from the database's capacity, not from the thread count; put a Semaphore in front of the gateway sized to what the provider allows, with tryAcquire and a fast 503; measure CPU per request with the JDK 25 JFR CPU-time profiler and treat cores as the hard cap.

Where virtual threads genuinely shine is the fan-out and slow-downstream case: if each request waits 120 milliseconds doing nothing, a thousand of them in flight now cost a megabyte of heap instead of a thousand threads.

Trade-off: the service becomes able to accept far more work than its dependencies can serve, so the limits I add are what protect the database. What I would not do is promise ten times before measuring the per-request CPU and the database's own headroom.

Land it Virtual threads make waiting free, so the new ceiling is whichever dependency you were waiting on, and the capacity model is that dependency's numbers, not the thread count.

Likely follow-ups
"The requirement changes: the gateway is replaced by twelve internal services called in parallel per request. What changes in the model?"

That is the case virtual threads were built for. Per request I now open twelve calls and wait for the slowest, so time in system is roughly the slowest call plus overhead, and concurrency per request is twelve.

At 1,000 requests per second with a 100-millisecond slowest call the service holds about 1,200 outbound calls open, which on platform threads meant 1,200 threads and on virtual threads means a few megabytes.

The new ceilings are the HTTP client's connection pool per host, which I would raise to match, and the twelve services' own capacity, which each gets a semaphore. I would also add a per-request deadline through a scoped value so the fan-out cannot outlive the client.

"How do you measure the CPU per request honestly?"

I would run a load test at a steady rate, say 500 requests per second, record with jcmd <pid> JFR.start settings=profile, and read the total CPU from the JDK 25 jdk.CPUTimeSample events, which sample by CPU time rather than wall time so idle virtual threads do not distort them. Dividing process CPU seconds by requests gives CPU milliseconds per request; on a JSON service with TLS it is often 0.5 to 2 milliseconds. Then the CPU ceiling is cores times 1,000 divided by that number, with a safety margin of around 30 percent for garbage collection and JIT. I would confirm by pushing load until CPU reaches 70 percent and watching the latency curve bend.

"What would you cut under time pressure?"

I would cut the gateway semaphore's fast-fail path and start with a plain bounded wait, because a 503 path needs client-side retry work that takes longer to get right. I would cut the per-request deadline.

I would keep the Hikari sizing review and the CPU-per-request measurement, because those two numbers are the honest capacity model and the rest is refinement.

If I had to ship in a day I would enable virtual threads with the existing Hikari pool unchanged, load test, and report the measured ceiling rather than the hoped-for one.

"What breaks at ten times the load even if all the limits are right?"

Memory in flight. Ten times the requests means ten times the request bodies, response buffers and parsed objects alive at once; if each request holds 200 kilobytes, 13,000 in flight is 2.6 gigabytes of young generation churn per second and a heap that may need resizing.

Garbage collection pauses then become visible in tail latency. Second, connection counts on the load balancer and on the downstream's side, which have their own file descriptor limits. Third, logging: ten times the log lines at the same level saturates the disk or the log shipper.

I would raise -Xmx, watch -Xlog:gc* for allocation rate, and sample logs before adding the load.

Q88 · Scenario. "A virtual-thread service stalls completely under load. CPU is low, the load balancer reports timeouts, and a thread dump shows all carrier threads busy. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: low CPU with busy carriers means the carriers are waiting, not computing. A carrier should only ever wait if a virtual thread is pinned to it, so this is a pinning signature until proven otherwise. With parallelism equal to the CPU count, four or eight pinned threads freeze the whole scheduler, and the compensation up to 256 carriers only delays it.
  2. Evidence: I would confirm with the JSON dump, jcmd <pid> Thread.dump_to_file -format=json d.json, and read the frames of each carrier's mounted virtual thread; then jfr print --events jdk.VirtualThreadPinned rec.jfr for the pinning reason and stack. I would also check the JDK version with java -version, because the answer differs before and after 24.
  3. Ranked causes: on JDK 21 to 23, a blocking call inside synchronized, typically a JDBC driver, a logging appender or a cache loader; on any version, a native frame on the stack, such as a JNI-based compression or crypto library or an FFM downcall, that blocks on I/O; a deadlock through a bounded resource where virtual threads waiting on a pool are unmounted but the pool's holders are pinned waiting on something the waiters own; and class initialisation that blocks.
  4. Fix: for pre-24 synchronized, upgrade to JDK 24 or 25 where JEP 491 removes the pinning, or replace the block with ReentrantLock if the code is ours, or upgrade the driver; for native calls, route them through a dedicated platform thread pool with a bounded queue so a virtual thread submits and parks rather than pins; for the resource deadlock, break the cycle by ordering acquisition or adding timeouts; short term, raise jdk.virtualThreadScheduler.parallelism to buy headroom while the real fix ships.
  5. Prevention: a JFR pinning inventory run in staging under load before every release, a rule that native work lives on platform threads, and an alert on the pinned-event rate.

Land it Busy carriers with idle CPU means something is holding a carrier while it waits, and on a modern JDK the only things that can are native frames and class initialisers, which narrows the search to a handful of libraries.

Likely follow-ups
"The fix didn't work: you moved the native library to a platform pool and the stall still happens. What next?"

Then the carriers are held by something else, or the platform pool itself is the new choke point.

I would repeat the dump during a stall and compare the carriers' frames with the earlier dump; if they now show Future.get waiting on the platform pool, the pool is too small or its queue is unbounded and I sized it wrong.

If the carriers show a different native frame, there is a second library, often a JDBC driver compiled with native components or a metrics agent.

If the carriers are genuinely idle now and the stall persists, the problem was never pinning: I would look at the resource layer, especially connection pool exhaustion visible as hundreds of virtual threads parked in Hikari's getConnection, which the JSON dump groups clearly.

"How can a bounded resource deadlock virtual threads when nothing is pinned?"

The classic shape is a request that holds a database connection and then, while holding it, starts a nested piece of work that needs a second connection from the same pool.

With twenty connections and twenty-one concurrent requests, all twenty holders wait for a twenty-first connection that will never be free, and nobody is pinned; every thread is parked politely. Platform pools masked this because the thread count was often smaller than the pool.

The dump shows every thread in HikariPool.getConnection; the fix is to never hold a connection across a call that needs another, or to give the nested work its own pool; and Hikari's connectionTimeout turns the deadlock into an exception after 30 seconds rather than forever.

"Why not just set the scheduler parallelism to 256 and be done?"

Because that recreates a large platform pool with extra steps. Each carrier is a platform thread with its own native stack, so 256 of them cost around 256 megabytes of reserved stack and real scheduling work for the operating system.

It also hides the pinning instead of removing it: at the next traffic peak 257 pinned threads stall the service again.

It is a legitimate emergency lever to keep a service alive for a night, and I have used it as such, but the honest fix is to remove the reasons for pinning, which on JDK 24 or later comes down to native calls.

Q89 · Scenario. "We switched Tomcat to virtual threads and throughput got worse: p99 latency doubled and the database team is complaining. Nothing else changed. What happened?"

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: the database complaint is the clue. Before the switch, Tomcat's maxThreads, typically 200, was an accidental throttle on everything the service did, including how many queries it could have in flight. Virtual threads removed that throttle, so the service now admits every request that arrives and pushes the concurrency onto the database and every other dependency at once.
  2. Evidence: Hikari metrics show hikaricp.connections.pending climbing and connections.acquire time growing; the database shows ten times the concurrent sessions or, if the pool was enlarged, ten times the active queries with lock contention. A JSON thread dump shows thousands of virtual threads parked in getConnection. CPU on the JVM may also be higher than before, from ten times the request objects and garbage.
  3. Ranked causes: the lost throttle, described above; per-request caches held in ThreadLocal, such as a SimpleDateFormat, a JSON mapper or a compiled regular expression, that were built once per pooled thread and are now built once per request, which is pure CPU and allocation overhead; CPU-bound request paths that now share carriers cooperatively; and, on JDK 21 to 23, pinning inside the JDBC driver's synchronized blocks.
  4. Fix: restore a deliberate limit where the resource is, meaning size Hikari from the database's capacity and let virtual threads park on it, and add a Semaphore or a bounded queue in front of any other dependency; replace thread-local caches with shared immutable objects, such as a single ObjectMapper or DateTimeFormatter, or with a small object pool; move CPU-heavy paths to a platform pool; and upgrade to JDK 24 or later.
  5. Prevention: run the switch behind a canary with the Hikari metrics and p99 on the dashboard, with the JFR pinning inventory taken in staging first, and a load test that compares thread-per-request and virtual threads at the same connection pool size.

Land it The old thread pool was doing two jobs, running requests and limiting them, and virtual threads only took over the first, so the second has to be put back explicitly.

Likely follow-ups
"The fix didn't work: Hikari is sized correctly and thread-locals are gone, but p99 is still worse. What next?"

Then I would look at where time goes inside a slow request rather than at limits. A JFR recording with jdk.VirtualThreadPinned, the JDK 25 CPU-time samples and the socket read events, filtered to the slow requests by trace id if we emit a custom event, usually shows one of three things: many short unmount and remount cycles from a chatty protocol, each costing a freeze and thaw; a request path that walks a deep stack before blocking, which makes each freeze expensive; or the garbage collector, because ten times the in-flight objects raised the allocation rate and -Xlog:gc* shows young collections every few hundred milliseconds. For the last one the answer is more heap or a larger young generation, not anything about threads.

"How do you find every ThreadLocal that matters without reading the whole codebase?"

Two ways. Statically, grep -r "ThreadLocal" --include=*.java on our code plus a look at the frameworks we use, since the expensive ones are usually a library's cache, such as a formatter or a buffer.

Dynamically, JFR allocation profiling: with jdk.ObjectAllocationSample enabled I look for types allocated once per request that used to be allocated once per thread, for example a 64-kilobyte byte array from a buffer cache.

A heap histogram with jcmd <pid> GC.class_histogram taken under load also shows suspicious per-request counts. The fix for each is either a shared immutable instance or a small bounded object pool that a virtual thread borrows and returns.

"Would you have kept platform threads for this service?"

Possibly, and I would say so. A service whose requests are short, mostly CPU, and bounded by one database gains little from virtual threads, because it was never limited by waiting.

The gain appears when requests spend most of their time waiting on slow or many dependencies. So the honest recommendation is to measure the fraction of request time spent blocked; if it is below half, the migration is mostly risk.

Where it is above 80 percent, as in an aggregation gateway, the migration is worth doing, with the limits put back on the resources.

Drill · Structured concurrency, pools & futures

This group tests whether you understand how tasks are grouped, scheduled, chained and cancelled on the modern JDK, and whether you can tell when a virtual thread is the wrong tool.

Q90. "What is structured concurrency, what does StructuredTaskScope give you that CompletableFuture.allOf does not, and what is its status today?"

Reveal answer

The real test Whether you can state the rule, that a task's lifetime is confined to a block of code, and whether you know the API is still preview as of Aug 2026.

Strong answer Structured concurrency is a rule: if a piece of code starts concurrent subtasks, those subtasks must finish, one way or another, before that code returns, just as a local variable does not outlive its block. java.util.concurrent.StructuredTaskScope implements the rule.

You open a scope in a try-with-resources, call fork(callable) for each subtask, which starts a virtual thread and returns a Subtask handle, then call join(), which waits according to a policy, and read results after it.

The policy is a Joiner: Joiner.allSuccessfulOrThrow() waits for all and fails fast if any subtask fails, cancelling the others; Joiner.anySuccessfulResultOrThrow() returns the first success and cancels the rest; Joiner.awaitAll() just waits and lets you inspect each subtask's state.

Closing the scope guarantees every forked thread has ended, and a deadline can be set when opening it with a configuration function.

Compared with CompletableFuture.allOf: allOf does not cancel the others when one fails, it does not know what thread runs what, an exception in a callback can be silently lost, and a forgotten future keeps running with nothing to stop it.

A scope cancels siblings on failure, propagates interruption to the owner, inherits scoped values into subtasks, and shows up in the JSON thread dump as a tree, the scope with its children beneath it, so a stuck fan-out is visible as a unit.

Status as of Aug 2026: it is still a preview API, so it needs --enable-preview.

It was the fifth preview in JDK 25 under JEP 505, the sixth in 26 under JEP 525, where Joiner.onTimeout was added and allSuccessfulOrThrow returns a List, and JDK 27 carries a seventh preview under JEP 533 with a new exception type.

I would verify the exact shape on the JEP page before writing it into a production plan.

StructuredTaskScope versus CompletableFuture.allOfruns offline
// THE OLD WAY — nothing ties the futures to the request. If the caller gives
// up, the tasks keep running; if one fails, the others are not cancelled;
// and the relationship exists only in the reader's head.
CompletableFuture<User>  u = supplyAsync(() -> users.find(id), pool);
CompletableFuture<Order> o = supplyAsync(() -> orders.find(id), pool);
CompletableFuture.allOf(u, o).join();          // leaks work on failure

// STRUCTURED — the scope IS the lifetime. Nothing outlives the try block.
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    Subtask<User>  user  = scope.fork(() -> users.find(id));
    Subtask<Order> order = scope.fork(() -> orders.find(id));

    scope.joinUntil(Instant.now().plusSeconds(2));   // deadline for the whole group
    scope.throwIfFailed();                            // first failure wins

    return new Dto(user.get(), order.get());
}   // close(): every remaining subtask is CANCELLED and joined. Guaranteed.

// WHAT THIS GIVES THAT allOf DOES NOT:
//  1. Automatic cancellation — one failure shuts the siblings down immediately
//     instead of leaving them to finish work nobody will read.
//  2. A deadline for the group, not per future.
//  3. Real stack traces: the subtask's stack is linked to the parent's, so a
//     thread dump shows the request that spawned it.
//  4. No thread pool to size, and no chance of the pool-starvation deadlock
//     in Q95.

// "9 of 12 must succeed" needs a custom policy:
try (var scope = new StructuredTaskScope<Result>()) { ... }   // collect, count, decide

Point 1 is the operational difference. With allOf, a request that fails fast still leaves eleven downstream calls running to completion — so a failing dependency increases load on every other dependency, which is precisely the wrong behaviour during an incident.

Land it A scope makes the lifetime, the failure handling and the cancellation of a fan-out follow the shape of the code, which is precisely what free-floating futures do not.

Likely follow-ups
"Would you ship a preview API in production?"

Not as a general rule, and I would say so plainly. A preview API can change between releases: the JDK 25 shape already differs from JDK 21's, with ShutdownOnFailure replaced by Joiner, and 26 changed return types again.

Code compiled with --enable-preview is tied to that exact feature version and refuses to run on another.

So I would use it in an internal tool or a service we rebuild with each JDK, and elsewhere write a thin scope-like helper on top of newVirtualThreadPerTaskExecutor, a CountDownLatch and an invokeAll with a timeout, which gives most of the discipline.

When it goes final I would swap the helper for the real thing.

"How does cancellation actually reach a subtask?"

When the joiner decides the outcome is settled, for example the first failure under allSuccessfulOrThrow, the scope interrupts every unfinished subtask thread. Interruption on a virtual thread works exactly as on a platform thread: a blocked call throws InterruptedException, and a running loop must check Thread.currentThread().isInterrupted().

So a subtask that ignores interruption, for example a tight CPU loop or a library that swallows the exception, keeps running until it finishes, and close() waits for it. That is why the scope's guarantee is "every subtask has ended", not "every subtask stopped immediately".

I write subtasks to honour interruption, and I set a deadline so the owner is not left waiting on a stubborn one.

"How do you write a custom Joiner?"

A Joiner is an interface with three methods. onFork(subtask) is called when a subtask starts. onComplete(subtask) is called when one finishes and returns true if the scope should stop waiting and cancel the rest. result() is called from join() to produce the value or throw.

For a "first nine of twelve" policy, onComplete adds successful results to a thread-safe list and returns true when the count reaches nine, and result() returns a copy of the list.

The methods run on subtask threads, so they must be thread-safe; I would use ConcurrentLinkedQueue and an AtomicInteger. This is the JDK 25 shape under JEP 505, and I would verify the method names on the JEP page for the version in use.

Q91 · Scenario. "A service with 16 CPUs handles requests fine until someone adds a parallelStream() in one endpoint. Now unrelated endpoints, and even the virtual threads, stall for seconds. Explain."

Reveal answer

The real test Whether you know that parallel streams, CompletableFuture's async methods and the virtual thread scheduler all sit on ForkJoinPool, and that the common pool is one shared, small resource.

Strong answer I would diagnose in this order:

  1. Symptom: unrelated work stalls when one endpoint runs, which is a shared-resource signature. parallelStream() runs its work on ForkJoinPool.commonPool(), a single process-wide pool whose parallelism is the number of available processors minus one, so 15 here. Every parallel stream and every CompletableFuture.supplyAsync without an explicit executor shares those 15 threads.
  2. Evidence: a thread dump shows ForkJoinPool.commonPool-worker-N threads all inside the endpoint's stream operation, and if the lambda does I/O, all blocked in a socket read. Other parallel streams and async futures queue behind them. Virtual threads stall for a different but related reason: the virtual thread scheduler is a separate ForkJoinPool, but its carriers compete for the same 16 CPUs, and if the stream's work is CPU-heavy the fifteen common pool workers plus the carriers oversubscribe the machine.
  3. Ranked causes: blocking I/O inside a parallel stream, which occupies common pool threads while they wait, so the pool's effective parallelism drops to zero; CPU-bound parallel work that saturates all cores and starves everyone else; and the pool's work-stealing behaviour, where a worker waiting for a subtask it forked helps by executing other queued tasks, so one endpoint's slow lambda ends up running inside another endpoint's stream.
  4. Fix: never do I/O in a parallel stream; for CPU work that must be parallel, submit it to a dedicated ForkJoinPool of a chosen size with pool.submit(() -> list.parallelStream()...).get(), which makes the stream use that pool because the stream's tasks inherit the pool of the thread that starts them; or replace the stream with virtual threads and a Semaphore if the work is really waiting. If the code must block inside the common pool, wrap the blocking call in a ForkJoinPool.ManagedBlocker so the pool compensates with an extra worker.
  5. Prevention: a static analysis rule that flags parallelStream() and executor-less supplyAsync in request paths, and a load test that runs the endpoint mix, not endpoints in isolation.

Land it The common pool is a shared CPU budget of cores minus one, and anything that blocks or hogs inside it is taxing every other user in the process.

Likely follow-ups
"How does work-stealing actually work, and why does it matter for the stall?"

Each worker owns a double-ended queue. It pushes and pops its own tasks at one end, last-in-first-out, which keeps a subtask's data hot in cache.

An idle worker steals from the other end of a random busy worker's queue, taking the oldest and usually largest task, which spreads work with little contention.

The subtlety is join(): a worker that waits for a subtask does not sleep; it runs other tasks, including tasks from a different parallel stream.

So one endpoint's blocking lambda can be executed by a worker that was in the middle of another endpoint's computation, and that computation waits too. The same mechanism, in FIFO mode and without the join-helping, is what schedules virtual threads.

"The fix didn't work: you moved the stream to its own pool, and the other endpoints still stall. What next?"

Then the problem is CPU, not the pool.

A dedicated pool with parallelism 15 plus the virtual thread carriers still oversubscribes 16 cores, so I would size the dedicated pool to something like four and confirm with the JFR CPU-time samples that the machine is no longer saturated during the endpoint.

If the stall persists with low CPU, the stream's own pool was not actually used: a parallel stream only inherits the pool if it is started from a thread of that pool, so a CompletableFuture wrapping the call or a lambda that starts the stream on another thread silently falls back to the common pool. The worker thread names in the dump settle that immediately.

"Which system property controls the common pool, and would you change it?"

-Djava.util.concurrent.ForkJoinPool.common.parallelism=N sets its size, and there are properties for the thread factory and the uncaught-exception handler.

Setting it to a small number such as 2 in a server is a defensible defensive move, because it limits the damage any stray parallel stream can do, while still allowing occasional parallel work. I would not raise it.

Setting it to 0 or 1 makes streams effectively serial on the caller's thread, which is a way to disable parallel streams without touching code, and I have used that in a service that had no legitimate parallel stream at all.

Q92. "In a CompletableFuture chain, which thread runs each stage? Explain the difference between thenApply and thenApplyAsync, and why join and get throw different exceptions."

Reveal answer

Strong answer A CompletableFuture holds a result field and a stack of pending dependents, implemented as a lock-free linked list of Completion objects that thenApply and friends push onto. When the future completes, the completing thread pops that stack and runs each dependent.

That gives the rule for the non-async methods: thenApply(f) runs f on whichever thread completes the source future, unless the source is already complete when thenApply is called, in which case it runs immediately on the calling thread.

So the same code runs on the HTTP client's I/O thread one moment and on your request thread the next, depending on timing.

thenApplyAsync(f) always submits f to an executor: the one you pass, or ForkJoinPool.commonPool() by default, or a thread-per-task executor if the common pool's parallelism is below two.

That is where the famous incident comes from: a callback registered with thenApply on a future completed by a Netty event loop ran a slow database call on the event loop thread and stalled every connection on it.

The rule I use is that a stage that blocks or is slow gets Async with an explicit executor, and cheap transforms may stay synchronous.

On exceptions: get() comes from the Future interface and wraps any failure in a checked ExecutionException, while join() is specific to CompletableFuture and wraps it in the unchecked CompletionException; both have the real failure as the cause, and a failure that propagates through stages is already a CompletionException, so handlers must unwrap.

Timeouts arrived in JDK 9: orTimeout(1, SECONDS) fails the future with TimeoutException if it is not done in time, and completeOnTimeout(fallback, 1, SECONDS) completes it with a default. Both use one shared daemon scheduler thread inside CompletableFuture.Delayer, so the timeout action itself must be cheap.

which thread runs each stageruns offline
CompletableFuture
    .supplyAsync(() -> load(id), ioPool)      // runs on ioPool
    .thenApply(this::transform)               // ??? -- see below
    .thenApplyAsync(this::enrich)             // ForkJoinPool.commonPool()
    .thenApplyAsync(this::render, cpuPool)    // cpuPool, explicitly
    .thenAccept(this::send);

// thenApply (NO Async): runs on WHICHEVER THREAD COMPLETES THE PREVIOUS STAGE —
// or on the CALLING thread if the previous stage is already complete when
// thenApply is invoked. That is genuinely non-deterministic, and it is why:
//
//   - a blocking call inside thenApply can block an ioPool thread, a
//     commonPool thread, or your request thread, depending on timing
//   - the same code behaves differently under load than in a test
//
// thenApplyAsync (no executor): ForkJoinPool.commonPool(). Sized to
// (cores - 1) and SHARED with parallel streams across the whole JVM — so one
// blocking task in it starves every parallel stream in the process.
//
// thenApplyAsync(fn, executor): the executor you named. The only fully
// predictable form.

// RULE: use the plain form only for cheap, non-blocking transformations
// (a map, a field extraction). Anything that blocks or takes real time gets
// an explicit executor.

The commonPool default is the dangerous one. It is shared process-wide with every parallel stream, it is sized for CPU work, and blocking in it starves unrelated code — which is exactly the incident in Q91.

Land it Without Async you do not choose the thread, the completer does, so any stage that can block must name its executor.

Likely follow-ups
"How would you prove which thread ran a stage in production?"

The cheapest way is to log Thread.currentThread().getName() inside the stage once, under a debug flag, and read whether it says something like nioEventLoopGroup-3-2, ForkJoinPool.commonPool-worker-5 or the request thread.

In a JFR recording, the JDK 25 CPU-time samples and the jdk.ThreadPark events attribute time to thread names, so a slow stage on an event loop thread shows as that thread's stack containing my lambda.

If the framework exposes an event loop busy metric, a spike that lines up with the endpoint is the same evidence. Once found, the fix is thenApplyAsync(f, myExecutor), and I would keep the debug log until the load test confirms the event loop is clean.

"What happens to an exception thrown inside a stage that nobody handles?"

It does not disappear, but it is easy to lose. The stage's future completes exceptionally with a CompletionException wrapping the throwable, and every dependent stage completes exceptionally in turn, skipping its function.

If no one ever calls join, get, exceptionally, handle or whenComplete on the tail of the chain, the exception sits inside the object and is never logged. That is the silent failure that structured concurrency was designed to prevent.

My rule is that every chain ends in a whenComplete that logs, or is joined by someone; a chain built for fire-and-forget gets an explicit exceptionally that reports to metrics.

"When is CompletableFuture still the right tool on a JDK with virtual threads?"

When the source of the value is genuinely asynchronous and callback-shaped, such as a non-blocking client that hands you a future, or when the composition is the point, such as combining two futures with thenCombine where the two producers are already asynchronous.

It is also the interface many libraries expose, so you meet it whether you like it or not.

For code we write, on JDK 21 or later, I prefer a virtual thread that calls blocking methods in sequence and a scope for fan-out, because the stack trace is readable, exceptions propagate normally, and there is no thread-choice puzzle.

I would wrap a library's future with join() on a virtual thread rather than continue the chain.

Q93 · Design. "Design a Kafka consumer that processes each record with a slow HTTP call on virtual threads. The first version used newVirtualThreadPerTaskExecutor and ran out of memory. Fix the design."

Reveal answer

Strong answer Requirements and assumptions: the topic delivers up to 20,000 records per second in bursts, each record needs one HTTP call of about 200 milliseconds to a service that allows around 500 concurrent calls, and processing order within a partition does not matter but commits must be safe.

The first version failed because newVirtualThreadPerTaskExecutor has no limit: every polled record became a virtual thread holding its record and its HTTP buffers, the downstream could only serve 500 at a time, and by Little's law the number in flight grew without bound, a memory bomb of parked threads.

Design: backpressure at the source, a bounded limit at the sink and nothing unbounded in between.

The consumer loop keeps polling, but before it hands a record to a virtual thread it acquires a permit from a Semaphore(500), sized from the downstream's capacity; when permits run out the loop blocks, its poll() is delayed, and Kafka's own flow control stops fetching, because a consumer that does not poll does not receive.

To keep the consumer alive during long stalls, max.poll.interval.ms must exceed the worst-case wait, or the loop pauses the partition with consumer.pause() while permits are exhausted and keeps polling.

Each virtual thread does the call, releases the permit in a finally block, and reports its offset to a per-partition tracker that commits only up to the lowest unfinished offset, so a crash replays at most 500 records.

If the HTTP client is a reactive one with a Flow.Publisher, its request(n) is the same idea expressed by the consumer: ask for n, no more.

Trade-offs: a semaphore gives a fixed limit rather than an adaptive one, and sizing it needs a measurement; the offset tracker adds state but is what makes at-least-once safe.

What I would not do is raise the heap, add a bounded queue with a DiscardPolicy that silently drops records, or process records in poll order with a single thread per partition, which wastes the downstream's parallelism.

Land it Virtual threads make it cheap to wait but not free to hold, so the number in flight must be bounded by the slowest stage and that bound must reach back to the poll loop.

Likely follow-ups
"The requirement changes: records for the same key must be processed in order. What changes?"

Then concurrency is per key, not per record.

I would hash the key to one of N lanes, for example 512, and give each lane a single virtual thread consuming from a small bounded ArrayBlockingQueue, so records with the same key are handled sequentially while different keys run in parallel.

The semaphore moves to the lane level: a lane's thread acquires the downstream permit before its call. The poll loop offers into the lane queue with a timeout, and a full queue is the backpressure signal that pauses polling. The offset tracker stays the same.

Throughput is now limited by the hottest key, which is a property of the data and worth reporting to the producer team.

"How do you size the semaphore using Little's law?"

Concurrency equals throughput times time per item. If the downstream can serve 2,500 calls per second at 200 milliseconds each, it can hold 500 calls in flight, so 500 permits.

If we only need 1,000 records per second, 200 permits suffice and leave headroom for other callers. I would measure both numbers rather than assume: latency from the HTTP client's metrics at the intended rate, and capacity from the downstream team or a load test.

Then I would watch two gauges in production, permits available and consumer lag, because lag rising while permits sit at zero means the limit is right and the downstream is the bottleneck, whereas lag rising with free permits means the consumer loop itself is slow.

"What would you cut under time pressure?"

I would cut the per-partition offset tracker and commit after each batch completes, which is simpler and only costs some duplicate processing on a crash, acceptable if the HTTP call is idempotent. I would cut the pause and resume logic and rely on a generous max.poll.interval.ms. I would not cut the semaphore, because it is the fix for the memory problem, and I would not cut the finally block that releases it, because a leaked permit is a slow strangulation that takes a day to notice.

"Why is a bounded queue with CallerRunsPolicy a worse answer here?"

CallerRunsPolicy makes the poll thread execute the rejected task itself, so the poll loop stops polling for 200 milliseconds and Kafka's heartbeat and poll interval accounting become erratic. It also provides backpressure only by accident and only one record at a time.

A bounded queue also introduces the question of what waits in it; with a semaphore the waiting is done by the poll loop, which is exactly the thing that should slow down.

And a ThreadPoolExecutor with a queue reintroduces a pool of virtual threads, which is the pattern we agreed makes no sense.

Q94. "When do platform threads still win over virtual threads, and how do you mix the two in one service?"

Reveal answer

Strong answer Virtual threads make waiting cheap; they do nothing for computing, and they add a copy of the stack on every block. So platform threads win in five situations.

First, CPU-bound work: a thread that computes for a second wants the operating system's time-slicing, which gives every thread a fair share, whereas a virtual thread holds its carrier until it blocks.

Second, code with native frames: JNI, the Java Native Interface, and downcalls through the FFM API pin a virtual thread to its carrier, so a library that blocks inside native code, such as a native crypto or compression library, belongs on platform threads.

Third, hot loops that block and unblock millions of times per second on a very short wait, where the freeze and thaw per block, around a microsecond, is comparable to the work itself; a platform thread spinning on a lock can be faster.

Fourth, anything that needs thread priority, CPU affinity or a thread name that operating-system tools can see, because virtual threads have no scheduling priority and the operating system does not know they exist.

Fifth, frameworks built around heavy ThreadLocal state, which is cheap when the thread lives for hours and expensive when it lives for one request.

The mixed design is normal and simple: the request path runs on virtual threads because it mostly waits; a small fixed platform pool, sized to the cores, runs CPU-heavy jobs such as PDF rendering or large sorts; another small platform pool runs native calls; and the virtual thread hands work over with submit and parks on the returned future, which unmounts cleanly.

The rule I give teams is one sentence: virtual threads for waiting, platform threads for computing and for native code.

Land it The question is not which thread type the service uses but which thread type each kind of work uses, and most services need both.

Likely follow-ups
"How would you verify that a suspicious library pins, before putting it on virtual threads?"

I would write a small harness that calls the library from a few hundred virtual threads under load with a JFR recording started by -XX:StartFlightRecording=filename=pin.jfr,settings=profile, then read jfr print --events jdk.VirtualThreadPinned pin.jfr.

On JDK 24 and later each event carries the reason and the stack, so a native frame shows immediately. I would lower the event's threshold from the default 20 milliseconds to 1 millisecond in a custom settings file to catch short pins.

The same harness on JDK 21 also reports synchronized pins, which tells me whether the library is safe on that version or only on 24 and later.

"Does thread priority really not exist for virtual threads?"

Correct. Thread.setPriority on a virtual thread is silently ignored and getPriority always returns NORM_PRIORITY, which is 5. The scheduler is a FIFO fork-join pool with no notion of priority, so a latency-sensitive request and a background cleanup are equal.

On platform threads priority is a hint the operating system may honour, and on Linux by default it does not either unless the JVM runs with -XX:ThreadPriorityPolicy=1 as root.

So in practice priority is rarely a real tool on either thread type; what works is separating the classes of work into different pools and limiting the background one with a semaphore.

"Is a virtual thread always slower than a platform thread for a single request?"

For a single request in isolation the difference is small and can go either way.

A virtual thread pays a freeze and thaw on each blocking call, on the order of a microsecond, which is invisible against a millisecond of I/O. It gains a little from cheaper creation and from not needing a pool handoff.

Where it is measurably slower is a request that blocks thousands of times on very short waits, or one that has a very deep stack at each block.

Where it is faster is under load, because the process no longer runs out of threads and stops queueing requests in the acceptor. So I answer the question with load, not with a single-request benchmark.

Q95 · Scenario. "A service hangs. The thread dump shows all eight threads of a fixed pool blocked in CompletableFuture.join(), waiting on futures whose tasks are queued in the same pool. How did this happen and what do you do?"

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: a hang with no CPU and every pool thread in join(). That is pool self-deadlock: a task running on the pool submitted a child task to the same pool and then blocked waiting for it. With eight threads, once eight parents are blocked, their children sit in the queue with nobody to run them, and nothing will ever change.
  2. Evidence: the dump shows the eight worker threads with a stack of CompletableFuture.join above supplyAsync's lambda, all on pool-1-thread-N; jcmd <pid> Thread.print or the JSON dump lists no runnable thread; and if the pool is a ThreadPoolExecutor, its queue size, visible through JMX or a metrics gauge, is non-zero and constant.
  3. Ranked causes: a dependent task submitted to the parent's own executor, usually because a shared executor field was passed into both supplyAsync calls; a library that offers a synchronous facade over an async client by joining on the same pool; a recursive computation where each level submits the next level to the fixed pool, which is what ForkJoinPool solves with join-helping and a fixed pool cannot.
  4. Fix: the rule is never block inside a pool on work that the same pool must do. Options in order of preference: stop blocking and compose with thenCompose so the parent returns immediately and the child completes the chain; give children a separate executor so parents and children cannot starve each other; run parents on virtual threads with newVirtualThreadPerTaskExecutor, where blocking is cheap and there is no fixed count to exhaust; or, if the work is recursive, use a ForkJoinPool whose join lets a waiting worker run queued subtasks. The immediate recovery is a restart, since the deadlock is permanent.
  5. Prevention: a timeout on every join via orTimeout so the deadlock turns into an exception with a stack trace; an alert on pool queue length that stays constant while active count equals pool size; and a review rule that an executor is never passed to both a task and its dependents.

Land it A fixed pool that both runs tasks and waits for tasks will eventually wait for itself, so either stop waiting inside it or make the waiting happen on threads that cannot run out.

Likely follow-ups
"The fix didn't work: you gave children their own executor, and now the hang happens less often but still happens. What next?"

Then there is a third level. Children that themselves submit grandchildren to the child executor recreate the same cycle one layer down, and it appears less often because the second pool is larger.

I would take the dump again and read which pool's threads are in join and what they wait for; a dependency drawn as a graph of pools must have no cycle and no pool waiting on itself.

If the graph is clean, I would look for a hidden shared pool: thenApplyAsync without an executor argument uses the common pool, and if some stage in the chain does that while another stage blocks the common pool, the same self-deadlock hides inside ForkJoinPool.commonPool.

Joining with orTimeout everywhere turns each remaining occurrence into a logged exception that names the future.

"Why does ForkJoinPool not deadlock in this shape?"

Because its join does not simply park.

When a worker joins a task that is not done, it first tries to run that task itself if it is still queued, then runs other tasks from its queue or steals, so the queued children get executed by the waiting parents.

It also has compensation: if a worker really must block, and the blocking is announced through ManagedBlocker, the pool can start a spare worker to keep parallelism up.

A ThreadPoolExecutor has none of this; its threads are plain loops that take from a queue, and a blocked thread is simply gone. That is why recursive divide-and-conquer belongs in ForkJoinPool and why the virtual thread scheduler is built on it.

"How would you detect this class of deadlock automatically rather than from a dump?"

Two signals together are almost a proof: the executor's active count equals its maximum and has not changed for a minute, and its queue length is greater than zero and has not changed either.

I would expose both as gauges from the ThreadPoolExecutor and alert on the pair. For the futures themselves, orTimeout gives a TimeoutException that names the stage. JFR's jdk.ThreadPark events with a long duration on all pool threads are a third signal.

The standard ThreadMXBean.findDeadlockedThreads does not help here, because it only detects monitor and ownable-synchroniser cycles, and a future is neither.

Q96. "Explain interruption and cancellation properly: what Thread.interrupt does, why you restore the flag, what Future.cancel(true) does, and why virtual threads make the blocking model attractive again."

Reveal answer

Strong answer Interruption is a cooperative signal, a single boolean on the thread.

interrupt() sets the flag; if the target is blocked in a method that declares InterruptedException, such as sleep, wait, BlockingQueue.take or LockSupport.park through a lock, that method wakes up, clears the flag and throws.

If the target is blocked in an interruptible channel, the channel closes and throws ClosedByInterruptException. If the target is running, nothing happens until it checks Thread.currentThread().isInterrupted().

So a thread that ignores the signal cannot be stopped from outside, which is deliberate: forced stopping left locks and data in unknown states, and Thread.stop now throws UnsupportedOperationException. Restoring the flag matters because catching InterruptedException clears it.

If a library method catches the exception to clean up and then continues, the caller above never learns it was asked to stop. The rule is that if you cannot propagate the exception you call Thread.currentThread().interrupt() before returning, so the next blocking call throws again.

Future.cancel(true) marks the future cancelled and interrupts the thread running the task; cancel(false) only prevents it from starting. On a CompletableFuture, cancel never interrupts anything, it just completes the future with CancellationException, which surprises people.

A StructuredTaskScope uses interruption to cancel sibling subtasks when the policy is settled. Virtual threads make all this attractive again because the cost that pushed us to callbacks, one platform thread per blocked operation, is gone.

A subtask can sit in a blocking read with a readable stack trace, and cancelling it is one interrupt that arrives as an exception in the right place, rather than a cancellation token threaded through every callback.

Land it Interruption is the JDK's cancellation protocol, and it only works if every layer either throws the exception on or restores the flag; virtual threads make it cheap enough to be the default model again.

Likely follow-ups
"How do you cancel a subtask that is doing CPU work and never blocks?"

It has to check. In the loop I would test Thread.currentThread().isInterrupted() every few thousand iterations and return or throw when it is set, which costs a volatile read and nothing else.

Libraries that do long computations, such as a regular expression engine on adversarial input, often do not check, and then the only protection is a bound on the input size or a timeout that abandons the result while the computation runs to completion on its own thread.

In a scope, the owner's join returns after the deadline, but close() still waits for the stubborn subtask, so I would put such computations on a platform pool and treat the abandoned work as a known cost.

"A JDBC call is not interruptible. How do you cancel a query on a virtual thread?"

Interruption does not reach a socket read inside most JDBC drivers, because they use plain blocking streams. The tool is Statement.cancel(), called from another thread, which sends a cancel message on a separate channel and makes the blocked execute throw SQLException.

So the cancellation path is: the scope interrupts the subtask thread, which does nothing yet; a watchdog, or the subtask's own handler installed before the call, calls statement.cancel().

In practice I set setQueryTimeout on the statement, which uses the same mechanism on a driver timer, and treat interruption as best effort. The connection is then returned to the pool in a clean state because the cancel completes the statement.

"Why does CompletableFuture.cancel not interrupt, and what do you do about it?"

Because a CompletableFuture does not know what thread, if any, is producing its value; it may be completed by a callback, a timer, or code on any thread, so there is nothing to interrupt. cancel therefore only completes it exceptionally so that dependents stop waiting.

If the producer is a task I submitted, I keep the Future returned by executor.submit and cancel that with true, or I pass a cancellation flag into the task.

On a virtual thread the cleanest option is to hold the Thread object and call interrupt() directly, which is exactly what StructuredTaskScope does for you.

Q97 · Design. "Plan the migration of a classic thread-per-request service, Tomcat, JDBC, some synchronized caches and a ThreadLocal request context, to virtual threads. What do you do, in what order, and what do you refuse to do?"

Reveal answer

Strong answer Requirements and assumptions: a Spring Boot service on JDK 17 with Tomcat's 200-thread pool, Hikari at 30 connections, outbound HTTP to three partners, and a p99 target that must not regress. The goal is more concurrent waiting for the same hardware, not a rewrite.

Order of work.

First, upgrade the JDK to 25, the current long-term-support release as of Aug 2026, before touching threads, because JEP 491 in JDK 24 removed pinning on synchronized and Object.wait, and JDK 25 made ScopedValue final; migrating on 21 means rewriting every synchronized cache first, which is work the JDK now does for us.

Second, a pinning inventory in staging: run the load test with JFR and read jdk.VirtualThreadPinned; on 25 the only hits should be native frames, so I would look for JNI in the driver, the compression filter and any native crypto, and route those to a platform pool.

Third, replace the ThreadLocal request context with a ScopedValue bound in the edge filter, and audit the remaining thread-locals for per-thread caches that become per-request costs.

Fourth, put the limits back where the resources are: keep Hikari at 30 as the database throttle, add a Semaphore per partner sized to its rate limit, and remove any reliance on server.tomcat.threads.max as backpressure.

Fifth, flip spring.threads.virtual.enabled=true on one canary instance with dashboards for Hikari pending, partner semaphore waits, p99, GC allocation rate and the JFR pinned-event rate, and compare against a control instance for a week.

Trade-offs: the service can now accept more than its dependencies serve, so the semaphores are what protect them; and the JDK upgrade carries its own risks, which is why it goes first and alone.

What I would not do: migrate on JDK 21; pool virtual threads; raise Hikari to "match" the new concurrency without asking the database team; or change the thread model and the JDK in one deploy, because then a regression has two suspects.

Land it The migration is mostly an inventory of where the old thread pool was silently doing a job, and each of those jobs gets an explicit owner before the pool goes away.

Likely follow-ups
"The requirement changes: you must stay on JDK 21 for a year. Does the plan still work?"

It works with more effort and more risk.

On 21 every synchronized block that can block inside it pins, so the pinning inventory includes the JDBC driver, logging appenders and our caches; the fix is to upgrade the driver to a version that uses ReentrantLock, and to rewrite our caches on ReentrantLock or ConcurrentHashMap.computeIfAbsent.

ScopedValue is preview on 21, so the request context stays a ThreadLocal holding one immutable record with strict set and clear.

I would then run the JFR inventory again and, if the driver still pins, postpone; a migration that stalls the service under load is worse than the status quo.

"What would you cut under time pressure?"

I would cut the ScopedValue conversion and keep the thread-local context, provided it is set and cleared in a try-finally, because it still works on virtual threads and is only a scaling cost.

I would cut the partner semaphores if the partners have their own rate limiting that returns a clear 429. I would not cut the JDK upgrade, the pinning inventory or the canary, because those are where the migration fails silently.

If forced to ship in a week, the plan is JDK 25, JFR inventory, flip the flag on one instance, watch for a week.

"How do you know the migration succeeded, in numbers?"

I would define success before flipping. Same p99 at the current load, measured over a week against the control instance. At 3 times the load in a load test, the virtual-thread instance keeps p99 within 20 percent while the control instance's acceptor queue grows.

Hikari pending time stays under 5 milliseconds at current load, which shows the throttle is not now the bottleneck. Zero jdk.VirtualThreadPinned events over 20 milliseconds in a day. Memory: resident set size not above the control's plus 10 percent.

If the first number regresses, we stop and read the JFR recording rather than tune around it.

Q98 · Design. "Design an aggregation endpoint that calls twelve downstream services in parallel, needs nine of them to answer, and has a 300 millisecond budget. Use virtual threads and structured concurrency."

Reveal answer

Strong answer Requirements and assumptions: twelve independent calls with a median of 60 milliseconds and a p99 of 400; any nine results make a useful page; the whole request must return within 300 milliseconds; JDK 25 with --enable-preview accepted for this service, or the equivalent helper on plain virtual threads if preview is not acceptable.

Design: the handler opens a StructuredTaskScope with a custom Joiner whose onComplete counts successes and returns true at nine, so join() returns as soon as nine are in and cancels the remaining three by interrupting them; a deadline of 280 milliseconds is set through the scope's configuration so the owner never waits past the budget, leaving 20 milliseconds to assemble the response.

Each subtask is one virtual thread doing a blocking HTTP call with a per-call timeout of 250 milliseconds, one retry for connection failures only, with a small jitter, and an idempotency key.

The request's deadline and trace id live in a ScopedValue bound at the edge, inherited automatically by every subtask, so each call computes its remaining time from the same deadline rather than its own clock.

On timeout the joiner's result() returns whatever succeeded, and the handler renders partial results with a header that lists the missing services, so clients can decide.

Observability: one custom JFR event per aggregation with counts of successes, failures and cancellations, a histogram of time-to-ninth-result, and the scope's tree visible in Thread.dump_to_file when something hangs.

Trade-offs: cancelling the last three calls wastes their work downstream, which is acceptable at this fan-out; retries must be limited so that a slow downstream does not get twice the traffic during its own incident.

The all-or-nothing variant is simpler: Joiner.allSuccessfulOrThrow(), which fails fast on the first failure and cancels the rest, with the same deadline, and the handler returns an error instead of a partial page.

What I would not do is use CompletableFuture.allOf with a global timeout, because the outstanding calls would keep running after the timeout and nothing cancels them.

Land it The scope gives the three things a fan-out needs, a lifetime, a completion policy and cancellation of the losers, and the deadline in a scoped value is what makes twelve calls share one clock.

Likely follow-ups
"The requirement changes: two of the twelve are mandatory and the other ten are best-effort. How does the joiner change?"

The joiner's onComplete now tracks two things: whether both mandatory subtasks have succeeded, and how many optional ones have.

It returns true, ending the wait, when both mandatory are in and at least seven optional are, or immediately when a mandatory one fails, since the request cannot succeed. result() throws if a mandatory result is missing and otherwise returns the partial set.

I would tag subtasks with a small record holding the service name and a mandatory flag, passed into fork as part of the callable's result, so the joiner does not need to inspect thread names. The deadline handling stays the same.

"What would you cut under time pressure?"

I would cut the custom joiner and use Joiner.awaitAll() with the 280 millisecond deadline, then count successes after join() and return partial results if there are at least nine; that waits the full budget instead of returning at the ninth, which costs latency but not correctness.

I would cut retries entirely, since a downstream that fails once is likely failing again within the budget. I would cut the custom JFR event and log a line.

I would not cut the deadline or the cancellation, because without them the endpoint leaks work into every downstream during an incident.

"How do you prevent this endpoint from making a downstream incident worse?"

Three guards. A Semaphore per downstream sized from its capacity, acquired with a short tryAcquire, so that a slow service does not accumulate thousands of waiting calls from us; when permits are gone we treat that service as missing immediately, which also shortens our own latency.

A retry budget rather than per-call retries, for example at most 10 percent of calls per downstream per second may be retries, tracked with a token bucket.

And the cancellation from the joiner, which ensures that once we have nine answers we stop loading the slow ones. Together these are what a circuit breaker would do, expressed with the tools we already have.

"How would you test the timeout behaviour deterministically?"

I would inject the HTTP client as an interface and, in the test, supply a fake whose responses are controlled by a CountDownLatch per downstream, so the test can release exactly nine, hold three, and assert that join() returns without waiting for the held ones and that their threads are interrupted, checked with a flag set in the fake's catch block. For the deadline, the same fake holds all twelve and the test asserts the scope returns after the configured deadline, measured with a tolerance. Running the test on virtual threads is fine, and the JSON thread dump taken mid-test shows the scope tree, which is a useful artefact to keep.

Drill · Records, sealed types & pattern matching

This group tests whether you understand what the compiler generates for the JDK 21 language features, where their runtime traps are, and how the JDK 21 to 27 releases fit together as of Aug 2026.

Q99. "What does the compiler actually generate for a record, and when is a record the wrong choice?"

Reveal answer

The real test Whether you know that equals, hashCode and toString are not written into the class file as code but bootstrapped at runtime, and whether you can list the real limits rather than "immutable data class".

Strong answer A record is a class whose state is exactly its declared components.

For record Point(int x, int y) the compiler generates a final class extending java.lang.Record, one private final field per component, an accessor method per component named after it, and a canonical constructor taking all components in order.

It does not generate the bodies of equals, hashCode and toString as bytecode. Instead each of those methods contains a single invokedynamic whose bootstrap is java.lang.runtime.ObjectMethods.bootstrap; at first call the runtime builds a method handle that compares or hashes the components, and links it.

That keeps class files small and lets the JDK improve the implementation later. The compact canonical constructor, written without a parameter list, lets you validate or normalise before the fields are assigned; the assignments happen automatically at its end.

A record cannot extend another class, is implicitly final, and its fields cannot be changed, but immutability is shallow: a List component can still be mutated by whoever holds it, so I copy with List.copyOf in the compact constructor.

Serialisation is special: a record is deserialised by calling its canonical constructor with the stream's values, so validation always runs, unlike an ordinary class where the constructor is bypassed.

Records can be declared locally inside a method, which is useful for an intermediate tuple in a stream pipeline, and they participate in record patterns in instanceof and switch.

A record is wrong when identity matters, for example an entity that is the same row even after its fields change; when the object is mutable by design, such as a builder; and for JPA entities, which need a no-argument constructor, proxies and mutable fields, so a record there fails at runtime rather than at compile time.

what the compiler generates for a recordruns offline
public record Order(String id, BigDecimal total, List<Line> lines) { }

// javac generates: a final class extending java.lang.Record, with
//   - private final fields for every component
//   - a canonical constructor
//   - accessors named id(), total(), lines()   (NOT getId())
//   - equals(), hashCode(), toString() — all built from the components
//     via an invokedynamic bootstrap (ObjectMethods), not written out

// THE COMPACT CONSTRUCTOR is where validation and defensive copying go.
// Note there is no assignment: javac assigns the (possibly reassigned)
// parameters to the fields for you, after this body runs.
public record Order(String id, BigDecimal total, List<Line> lines) {
    public Order {
        Objects.requireNonNull(id);
        if (total.signum() < 0) throw new IllegalArgumentException("negative total");
        lines = List.copyOf(lines);       // defensive copy -> genuinely immutable
    }
}

// WHEN A RECORD IS THE WRONG CHOICE:
//  - the value is mutable, or has identity (an entity with a lifecycle)
//  - you need to hide or derive the representation: the components ARE the
//    public API, so you cannot change them without breaking callers
//  - you need inheritance: records are final and cannot extend anything
//  - a JPA @Entity: needs a no-arg constructor and non-final fields
//  - a component is a MUTABLE array or collection without a defensive copy —
//    equals() then compares by identity and hashCode() becomes unstable

The last bullet is the failure in Q103. A double[] component makes equals fall back to reference comparison, so two records with identical contents stop being equal and a HashMap lookup silently misses.

Land it A record is a promise that the object is nothing but its components, and the compiler enforces that promise, so use it exactly where that promise is true.

Likely follow-ups
"Why bootstrap equals through invokedynamic instead of just generating the code?"

Three reasons. Size: a generated equals for a record with ten components is a few hundred bytes of bytecode per record, and a large codebase has thousands of records.

Consistency: a single runtime implementation in ObjectMethods means every record compares the same way, including the rule that floating-point components use Double.compare semantics. Evolvability: the JDK can change the strategy, for example to vectorised hashing, without recompiling anyone.

The cost is that the first call to equals on each record class runs the bootstrap, which takes tens of microseconds and shows up as startup work; the Leyden AOT cache in JDK 24 and later can archive the linked call sites so that cost disappears.

"How do you add validation and defaults to a record without losing the generated constructor?"

With the compact canonical constructor. Writing record Range(int lo, int hi) { Range { if (lo > hi) throw new IllegalArgumentException(); } } runs the check and then assigns the fields automatically.

I can also reassign the parameters inside it, for example items = List.copyOf(items), to make a defensive copy. For defaults I add an extra constructor that delegates to the canonical one with this(lo, lo), or a static factory.

The one thing I cannot do is assign the fields myself in the compact form, and I cannot declare extra instance fields at all, which is the compiler enforcing the "nothing but components" rule.

"Can a record be used as a Spring or Jackson data transfer object without extra work?"

Yes for Jackson 2.12 and later, which detects the canonical constructor and uses the component names as property names, so no annotations are needed unless the JSON names differ, in which case @JsonProperty on the component works.

Spring's @ConfigurationProperties binds records through the canonical constructor as well, and constructor binding is the default for records.

The trap is validation: Jackson calls the canonical constructor, so a compact constructor that throws turns into a deserialisation error with a clear message, which is what you want.

Where records do not work is as JPA entities, as mentioned, and as classes that a framework needs to subclass for proxies, because records are final.

Q100. "Model a payment result with a sealed interface and explain the rules: who can implement it, what the subtypes must declare, and what happens at runtime if a new subtype appears."

Reveal answer

Strong answer A sealed type is a class or interface that lists exactly which types may extend it, so the compiler knows the whole set.

sealed interface PaymentResult permits Approved, Declined, Pending {} with record Approved(String authCode) implements PaymentResult, record Declined(String reason) implements PaymentResult and record Pending(Instant retryAt) implements PaymentResult says a result is one of exactly three shapes.

The rules: every permitted subtype must be in the same module as the sealed type, or in the same package if the code is on the class path in the unnamed module; each permitted subtype must declare how it continues the hierarchy, either final, which records are implicitly, sealed with its own permits list, or non-sealed to reopen the hierarchy for anyone; and if the subtypes are in the same source file the permits clause can be omitted and the compiler infers it.

The payoff is exhaustiveness. A switch over a PaymentResult with a case for each of the three, using type patterns or record patterns, needs no default, and if someone adds a fourth subtype the switch stops compiling, which is exactly the signal you want.

The runtime rule is the one people miss. The compiler emits, for an exhaustive switch without default, a hidden fallback that throws java.lang.MatchException.

Exhaustiveness is checked against the permits list at compile time and recorded in the class file as PermittedSubclasses, so if a library adds a subtype and ships a new jar but your switch is not recompiled, your code still loads and runs, and the first time the new subtype reaches the switch it throws MatchException.

That is a binary-compatible but not behaviour-compatible change, and it is why a sealed hierarchy across a library boundary is a versioning promise.

Land it Sealing turns "what can this be" into a compile-time fact, and the price is that adding a case is a breaking change for every exhaustive switch you do not own.

Likely follow-ups
"Sealed interface versus an enum with fields: when each?"

An enum is a fixed set of instances; a sealed interface is a fixed set of shapes, each with its own data. If every result carries the same fields, or none, an enum is simpler and serialises as a name.

When the cases carry different data, such as an approval code versus a retry time, each case wants its own record and a sealed interface is the right tool. Both give exhaustive switches.

A practical difference is evolution: adding an enum constant to a switch that has no default also throws MatchException on JDK 21 and later, so the compatibility story is the same.

I choose the enum until the first case needs its own field, and I do not mix the two.

"How does the JVM enforce the permits list?"

The class file of the sealed type carries a PermittedSubclasses attribute listing the allowed names.

When a class is loaded that declares the sealed type as its superclass or interface, the JVM checks that its name is in the list and that it is in the same module, or package for the unnamed module; if not, class loading fails with IncompatibleClassChangeError.

So a third party cannot implement your sealed interface even with bytecode tricks, which is a stronger guarantee than a package-private constructor. Reflection exposes it with Class.isSealed() and getPermittedSubclasses(), which frameworks such as Jackson use to discover the subtypes.

"Why must subtypes be in the same module or package?"

Because the compiler needs to see all of them to check exhaustiveness, and the JVM needs a boundary it can trust to reject impostors.

A module is the JDK's unit of co-compilation and of access control, so "same module" means one team controls the whole hierarchy and ships it as one unit.

On the class path there are no modules, and the package is the closest thing to a unit, which is why the rule falls back to the same package there.

It also means a sealed hierarchy cannot be split across jars of different libraries, which is a design constraint worth saying aloud: the hierarchy is an API, and its owner owns every case.

Q101 · Scenario. "A library we use added a fourth subtype to its sealed interface. Our service, which was not recompiled, now throws java.lang.MatchException in production. Explain and fix it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: a MatchException from a switch that has no default. The stack trace names our method, and the message, on recent JDKs, names the unexpected class. Nothing in our code changed; the jar underneath did, through a dependency bump or a shared library upgrade on the platform.
  2. Evidence: javap -v OurClass.class shows the switch compiled with a bootstrap to SwitchBootstraps.typeSwitch listing three case labels, and javap -v on the library's sealed interface shows a PermittedSubclasses attribute with four names. jdeps or the build's dependency report confirms which version is on the runtime class path versus the one we compiled against.
  3. Ranked causes: separate compilation, meaning our exhaustive switch was checked against the old permits list and never rechecked; a runtime class path that resolved a newer library than the build did, which happens with a parent-first application server or a shaded platform jar; or a fat jar assembled from mismatched module versions.
  4. Fix: recompile against the new library version, at which point the compiler reports the missing case and we add a branch for the new subtype with real handling, not a throwaway. For a hot fix before that lands, a default branch that logs and degrades safely, for example treats an unknown result as pending, restores service in minutes. For the class path mismatch, pin the library version in the build and make the runtime use the same artifact.
  5. Prevention: treat a sealed interface from a third party as an evolving contract and switch on it with a default that fails soft, reserving exhaustive switches for hierarchies we own; add a build check that compile-time and runtime versions match; and ask the library owner to mark additions as major versions.

Land it Exhaustiveness is checked by the compiler against the world it saw, so across a library boundary a sealed switch needs either a rebuild on every upgrade or a deliberate default.

Likely follow-ups
"The fix didn't work: you added a default branch and redeployed, and the exception still appears. What next?"

Then either the redeployed class is not the one running, or a second switch exists.

I would check the first with jcmd <pid> VM.classloaders and a heap dump or, more simply, with -verbose:class or -Xlog:class+load showing which jar the class was loaded from, because a stale jar in a lib directory or a parent class loader wins over the new one.

For the second, I would grep the codebase and, more reliably, the stack trace, because the failing switch may be in a shared internal library we also did not recompile, or in a Jackson deserialiser we wrote that switches on the same type. Each exhaustive switch over that interface needs the same treatment.

"Is adding a permitted subtype a binary-compatible change or not?"

Binary-compatible in the narrow sense the Java Language Specification uses: existing class files still link and load, no NoSuchMethodError or verification failure. Not behaviour-compatible: any exhaustive switch compiled against the old permits list throws MatchException when it meets the new case.

The specification chose this deliberately so that the switch fails loudly rather than silently taking a wrong branch.

For library authors the guidance is to treat adding a case as a major version change, or to design the hierarchy with a documented "other" case from the start so consumers always handle it.

"How would you design the library side so consumers do not break?"

If the set really may grow, I would not seal it, or I would seal it with a permitted non-sealed subtype named something like Other that consumers must handle, which forces every switch to have a branch for the future.

Alternatively I would ship the new subtype and the new version together with a clear major version and a note that exhaustive switches need recompiling. What I would avoid is adding a case in a patch release, because dependency tools will pull it in silently.

For our own internal hierarchies, where all consumers are rebuilt together, exhaustive switches are exactly right and I would keep them.

Q102. "Explain pattern matching for switch as it stands in JDK 21 and later: type patterns, record patterns, guards, null handling, dominance and exhaustiveness. What is still preview?"

Reveal answer

Strong answer Since JDK 21, under JEP 441 and JEP 440, a switch can select on any reference type and each case can be a pattern. A type pattern, case Approved a ->, tests the type and binds a variable.

A record pattern, case Approved(String code) ->, additionally deconstructs the record into its components, and patterns nest, so case Order(Customer(String name), List<Item> items) reaches two levels down. A guard adds a condition with when: case Declined d when d.reason().startsWith("FRAUD") ->.

case null is allowed explicitly, and without it a null selector throws NullPointerException as before, so a pattern switch does not silently accept null.

Dominance is the ordering rule: a case that would match everything a later case matches makes the later one unreachable, and the compiler rejects it, so case Object o must come last and an unguarded case Approved a before a guarded one on the same type is an error.

Exhaustiveness is required for switch expressions and for pattern switches: the cases must cover every possible value, which for a sealed type means every permitted subtype, and the compiler inserts a throwing fallback for the runtime case where a new subtype appears.

Underneath, the compiler emits an invokedynamic to java.lang.runtime.SwitchBootstraps.typeSwitch, which builds a classifier over the case labels and returns an index, so the switch is roughly a sequence of instanceof tests today and can be optimised by the runtime later.

What is still preview as of Aug 2026 is primitive types in patterns, JEP 507, which was the third preview in JDK 25 and continues in 26 and 27; it lets you write case int i against a long or an Object, with exactness checks.

I would verify its status on the JEP page before using it, and I would not enable preview features in production.

Land it Pattern switch makes "what is this and what is inside it" one expression the compiler can check for completeness, and the discipline is to keep the hierarchy sealed so that check means something.

Likely follow-ups
"How does the generated code decide which case matches, and is it slow?"

The bootstrap SwitchBootstraps.typeSwitch receives the list of case types and returns a method handle that, given the selector and a starting index, returns the index of the first matching case.

The current implementation tests each case in order with instanceof, which for a switch of five cases is five type checks at worst, each a few nanoseconds once the JIT inlines them.

The starting index exists so that a guard that fails can resume the search from the next case.

It is not slower than the chain of instanceof and casts it replaces, and the JDK reserves the right to generate a hash-based dispatch later without changing your class file.

"What does exhaustiveness mean for a nested record pattern?"

The compiler expands the nesting. For switch over Shape, sealed as Circle or Square, with patterns case Box(Circle c) and case Box(Square s), it reasons that a Box holds a Shape, and both shapes are covered, so Box is covered.

If a component type is sealed you must cover all its cases at that position, or use a type pattern such as Box(Shape s) that covers them all at once.

It also means a record pattern with a component that can be null still matches, because record patterns do not test components for null, only the top-level selector; a null component binds a null variable.

"Would you use pattern switch to replace the visitor pattern?"

Yes, for hierarchies I own and that change rarely, and it is the intended use.

A visitor spreads one operation across every subtype with an accept method and an interface with one method per type; a sealed hierarchy plus a pattern switch keeps the operation in one place and still gets a compile error when a case is missing.

The visitor remains better when the operations are open for extension by other modules and the set of types is closed, or when double dispatch on two hierarchies is needed.

I would not convert a stable visitor just to be modern, but new code with a closed set of shapes gets records, a sealed interface and switches.

Q103 · Scenario. "A record used as a HashMap key stopped matching after someone added a double[] component. Nothing else changed. Explain and fix it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: map.get(key) returns null for a key that was just put with equal contents, so equals or hashCode changed meaning. The only change is a new array component, which is the whole cause.
  2. Evidence: a two-line test, new Key(1, new double[]{1.0}).equals(new Key(1, new double[]{1.0})) returns false, and their hashCode values differ. javap -v Key.class shows equals as an invokedynamic to ObjectMethods.bootstrap, which is the generated implementation.
  3. Cause: the generated equals compares each component with Objects.equals for references and the appropriate primitive comparison for primitives. An array is a reference whose equals is identity, so two arrays with the same contents are not equal and their identity hash codes differ. Records do not special-case arrays; the specification says so, and the compiler even warns nothing. A second subtlety in the same area: double and float components are compared with Double.compare semantics, so NaN equals NaN and 0.0 is not equal to -0.0, unlike the == operator.
  4. Fix: replace the array with an immutable List<Double> copied in the compact constructor with List.copyOf, which compares by contents; or, if the array must stay for performance, override equals and hashCode in the record explicitly using Arrays.equals and Arrays.hashCode, and override toString too, because the generated one prints [D@1b6d3586. Overriding in a record is allowed and turns off the bootstrap for that method. Note also that a record holding an array is not really immutable: the caller can change the array after construction, so the compact constructor should clone it.
  5. Prevention: a static analysis rule that flags array components in records, and a unit test for every record used as a key that asserts value equality of two separately built instances.
the record that stopped matching as a HashMap keyruns offline
// BEFORE — worked.
record Key(String name, int version) { }
map.get(new Key("a", 1));         // finds it: String.equals and int compare by value

// AFTER — silently broken.
record Key(String name, int version, double[] weights) { }
map.get(new Key("a", 1, new double[]{0.5}));    // NEVER finds it

// WHY: the generated equals() compares each component with Objects.equals(),
// which for an ARRAY is REFERENCE equality — two distinct arrays with identical
// contents are not equal. hashCode() likewise uses the array's identity hash,
// so the same logical key hashes differently every time it is constructed.

// FIX 1 — use a type with value semantics. Almost always the right answer.
record Key(String name, int version, List<Double> weights) {
    Key { weights = List.copyOf(weights); }
}

// FIX 2 — override equals and hashCode explicitly, and use Arrays.*.
record Key(String name, int version, double[] weights) {
    @Override public boolean equals(Object o) {
        return o instanceof Key k && version == k.version
            && name.equals(k.name) && Arrays.equals(weights, k.weights);
    }
    @Override public int hashCode() {
        return Objects.hash(name, version, Arrays.hashCode(weights));
    }
}
// Note this also breaks toString(), which prints [D@1b6d3586 for the array.

The general rule: a record component should have value semantics. Arrays do not, which makes them the one common type that quietly breaks every generated member at once — equality, hashing and printing.

Land it A record's generated equality is component-wise equals, and an array's equals is identity, so an array component turns a value type into an identity type without warning.

Likely follow-ups
"The fix didn't work: you wrapped the array in a List and keys still do not match sometimes. What next?"

Then a different component is the problem, and "sometimes" suggests floating point.

If a double component is computed, two values that print the same may differ in the last bit, and Double.compare treats them as different; rounding to a fixed scale in the compact constructor, or storing a long of micro-units, fixes it.

If a component is a mutable object such as a Date or a user-defined class without equals, the same identity problem appears one level down.

And if the key is mutated after being put, for example the wrapped list was not copied and the caller changed it, the hash bucket is stale; List.copyOf in the compact constructor removes that possibility.

"Why did the language designers not compare arrays by content in records?"

Consistency and cost.

Everywhere else in Java an array's equals is identity, and making records the one place where it is not would surprise in the other direction, for example a record with a large array as a key would silently do an O(n) comparison and an O(n) hash on every lookup.

Records are also allowed to be deconstructed and rebuilt by patterns, and a content comparison would make the meaning of "same record" depend on mutable state the record does not control.

The guidance in the specification is to avoid array components in records, or to override the methods when you must, which keeps the decision visible in the source.

"How does the generated hashCode combine components, and can you rely on it across JDK versions?"

The specification says only that it is derived from the components' hash codes, and explicitly leaves the combination unspecified, so it may differ between JDK versions and even between runs in principle.

The current ObjectMethods implementation multiplies by 31 and adds, like Objects.hash, but I would not depend on it.

That matters if a record's hash is persisted, used for sharding, or compared across JVMs; for those cases I override hashCode with an explicit stable formula. Within one JVM the only guarantee you need, equal records have equal hashes, always holds.

Q104. "What did sequenced collections add in JDK 21, what does reversed() really return, and what could break when upgrading?"

Reveal answer

Strong answer Before JDK 21 there was no common type for "a collection with a defined order at both ends".

List had get(0) and get(size() - 1), Deque had getFirst and getLast, LinkedHashSet had an order but no way to read its last element, and SortedSet had first and last with different names. JEP 431 added three interfaces.

SequencedCollection extends Collection with getFirst, getLast, addFirst, addLast, removeFirst, removeLast and reversed(); List and Deque now extend it. SequencedSet extends it and Set, and LinkedHashSet and SortedSet implement it, so LinkedHashSet gained getLast and an addFirst that moves an existing element to the front.

SequencedMap gives firstEntry, lastEntry, pollFirstEntry, pollLastEntry, putFirst, putLast, reversed() and sequenced views of keys, values and entries; LinkedHashMap and SortedMap implement it, so a LinkedHashMap can finally act as a queue of entries.

reversed() returns a live view, not a copy: it is backed by the original, so changes on either side show on the other, iteration is in reverse order, and addFirst on the view is addLast on the original.

That makes reverse iteration cheap and, for a List, replaces the index loop or Collections.reverse on a copy. The upgrade caveat is about name clashes.

Any class that implemented List or Deque and already had a method called getFirst or reversed with a different return type now fails to compile, and code that called such a method through a variable typed as the class may resolve differently.

The known case was a class with getFirst() returning a subtype, which is fine, versus one returning an unrelated type, which is an error.

Unmodifiable collections throw UnsupportedOperationException from the add and remove methods, and addFirst on a SortedSet throws because the order is not the caller's to choose.

Land it Sequenced collections gave "first" and "last" one spelling across the framework, and the live reversed() view is the part that changes how you write loops.

Likely follow-ups
"How would you implement a simple LRU cache now, and what did this change?"

The classic answer is LinkedHashMap with access order, constructed as new LinkedHashMap<>(16, 0.75f, true), and removeEldestEntry overridden to return size() > max. That still works.

What changed is that eviction and inspection no longer need the iterator trick: map.pollFirstEntry() removes the least recently used entry, map.firstEntry() peeks at it, and map.putLast(k, v) explicitly marks an entry as most recent without a separate get.

For a concurrent cache none of this applies, because ConcurrentHashMap is not sequenced, and I would use Caffeine, which implements a better eviction policy than LRU anyway.

"What does reversed() cost on an ArrayList versus a LinkedList?"

On ArrayList the view is a thin wrapper that maps index i to size minus one minus i, so get is constant time and iteration walks the array backwards with no allocation beyond the view object.

On LinkedList, which is a Deque, the view uses the descending iterator, so iteration is still linear and get(i) is still linear as on the original. For a LinkedHashSet the view iterates the doubly linked entry list backwards, which was not possible before without copying.

The key property is that no copying happens anywhere, which is why the view must be treated as live: sorting the original while iterating the view fails fast with ConcurrentModificationException.

"Which JDK 21 collections changes besides sequencing would a senior engineer mention?"

Two small ones with practical value.

HashMap.newHashMap(int expectedSize), along with the same for HashSet and LinkedHashMap, was added in JDK 19 and creates a map sized so that the expected number of entries fits without resizing, which fixes the long-standing confusion that new HashMap(n) resizes at 75 percent of n.

And Collections.shuffle and the stream toList() from JDK 16, which returns an unmodifiable list that allows nulls, unlike List.of.

I mention them because interviewers sometimes use sequenced collections as a doorway to "what else changed in collections", and the sizing one is a real allocation win in hot paths.

Q105 · Design. "Design a payments domain model with records, sealed interfaces and pattern switches: states, transitions, events with versions, and JSON serialisation. What would you not do?"

Reveal answer

Strong answer Requirements and assumptions: a payment moves through created, authorised, captured, refunded, and failed; transitions must be explicit and exhaustive; events are stored for years and read by services on different release schedules; JSON is the wire format with Jackson. Design, in three layers.

The state layer is a sealed interface PaymentState permits Created, Authorised, Captured, Refunded, Failed, each a record carrying only what that state knows, for example Authorised(String authCode, Instant expiresAt) and Failed(String code, String message); no nulls for "not applicable" fields, because the type says which fields exist.

The command layer is a second sealed interface of commands, and one function PaymentState apply(PaymentState s, Command c) implemented as a nested pattern switch: case Authorise(var amount) when s instanceof Created and so on, with the compiler proving every state and command pair is handled, and invalid pairs mapped to a single Rejected outcome rather than an exception.

The event layer is a sealed interface PaymentEvent whose records carry an explicit int version and are never modified once published; a changed shape becomes a new record such as PaymentCapturedV2, and an upcaster switch turns old versions into the current one at read time.

Serialisation: annotate the sealed interface with @JsonTypeInfo(use = NAME) and let Jackson discover the subtypes from getPermittedSubclasses(), which recent Jackson versions do for sealed types, so a type name field selects the record; the canonical constructor does validation on deserialisation.

Trade-offs: more classes than a single mutable entity with a status enum, but each is a few lines; the pattern switch centralises the transition rules, which some teams prefer split by state.

What I would not do: make the state a mutable JPA entity with nullable columns for every field of every state; use a default branch in the transition switch, because it silently hides new states; serialise records by class name, which breaks on refactoring; or version by editing existing records, because stored events would fail to load.

Land it The type system does the work: each state carries exactly its data, the sealed set makes transitions exhaustive, and versioning by new types keeps stored events readable forever.

Likely follow-ups
"The requirement changes: a partial-capture feature means a payment can be in a captured state many times with different amounts. How does the model change?"

The state Captured gains a component, an immutable List<Capture> of records each with amount and time, copied with List.copyOf in the compact constructor, and a derived method remaining().

The transition case Capture(var amount) when s instanceof Authorised a && amount <= a.remaining() now also applies when s is a Captured with remaining amount, so it becomes two cases or one case with a guard on a helper.

The events gain a PaymentPartiallyCaptured record; existing PaymentCaptured events stay as they are and the upcaster maps them to a full capture. Nothing stored changes shape, which is the test of the design.

"What would you cut under time pressure?"

I would cut the separate command sealed interface and expose transition methods directly on a service, keeping the state sealed interface and the exhaustive switch inside each method. I would cut the upcaster and instead keep the first event version stable by review discipline for the first release. I would keep the sealed state with one record per state, because that is the part that removes the nullable-column bugs, and I would keep the explicit Jackson type names, because retrofitting them after events are stored is painful.

"How do you persist this in a relational database without JPA entities for each record?"

Two options that both work well.

Store the event log as rows with columns for payment id, sequence, type name, version and a JSON body, and rebuild the current state by replaying, caching the latest state in a second table as JSON. Or store only the current state as a JSON column plus a few indexed scalar columns, such as status name and amount, extracted at write time.

Either way the records never become entities; a thin repository maps rows to records with plain JDBC or Spring's JdbcClient.

The gain is that the schema does not have to represent every state's fields as nullable columns, and the type name column makes querying by state trivial.

"How does Jackson handle a sealed interface, and what breaks on rename?"

With @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") on the interface, Jackson writes a type name and, in recent 2.x versions, discovers permitted subtypes automatically; older versions need @JsonSubTypes listing them.

The default name is the simple class name, so renaming a record changes the JSON and breaks stored events.

I set explicit names with @JsonTypeName("captured") on each record, and I test with a stored fixture file per event version that must deserialise on every build. The canonical constructor runs on read, so validation failures surface as a clear ValueInstantiationException.

Q106. "What are stream gatherers, what are the parts of a Gatherer, and could you write one that removes consecutive duplicates?"

Reveal answer

Strong answer A gatherer is a custom intermediate stream operation, the missing piece that let you write your own map or filter with state, final in JDK 24 under JEP 485 and used through stream.gather(g).

Before it, anything stateful such as windowing needed a collector at the end of the pipeline or a hand-written iterator. Gatherer<T, A, R> has four parts. The initializer creates the state of type A.

The integrator receives each element and the state and pushes zero or more results downstream through a Downstream whose push returns false when nobody wants more, which is how short-circuiting works; it returns a boolean saying whether to continue.

The combiner merges two states for parallel streams, and is absent for a sequential-only gatherer. The finisher runs at the end with the state and the downstream, for emitting a last partial window.

The JDK ships a few in Gatherers: windowFixed(3) groups into lists of three, windowSliding(3) emits overlapping windows, fold(init, f) reduces to one value, scan(init, f) emits every running total, and mapConcurrent(maxConcurrency, f) applies a function to each element on its own virtual thread, at most that many at once, and preserves the order of results, which is the neat way to fan out a stream of URLs with bounded concurrency. Dedupe-consecutive in a few lines:

static <T> Gatherer<T, ?, T> dedupeConsecutive() {
    class State { T last; boolean has; }
    return Gatherer.ofSequential(State::new,
        Gatherer.Integrator.ofGreedy((state, e, down) -> {
            if (state.has && Objects.equals(state.last, e)) return true;
            state.last = e; state.has = true;
            return down.push(e);
        }));
}

ofGreedy tells the runtime the integrator never short-circuits on its own, which lets it skip a check per element. It is sequential because the "previous element" only makes sense in order, and it composes with anything: lines.gather(dedupeConsecutive()).gather(Gatherers.windowFixed(100)).

Land it Gatherers let you put the stateful step where it belongs, in the middle of the pipeline, and mapConcurrent is the one I reach for most because it is bounded fan-out on virtual threads in one call.

Likely follow-ups
"How does mapConcurrent handle a failure or a slow element?"

It starts a virtual thread per element up to the concurrency limit, keeps results in a small buffer in input order, and pushes each result downstream only when everything before it is done, so a slow element in the middle holds back later results even though they are finished.

If the function throws, the exception propagates out of the stream, the gatherer interrupts and waits for the outstanding virtual threads, and the stream terminates exceptionally.

It gives no timeout of its own, so a call that hangs hangs the stream; I wrap the function with a client timeout.

As of Aug 2026 it always uses virtual threads and does not accept an executor, so a CPU-heavy function would run on carriers and should not go through it.

"When would you make a gatherer parallel-capable, and what does the combiner have to guarantee?"

Only when the state can be split and merged meaningfully, which is true for windowing by count and for a running maximum, and false for anything depending on the previous element, such as the dedupe above. The combiner takes two states produced from adjacent portions of the input and must return the state that the sequential run would have reached over both portions together; for windowFixed that means carrying a partial window from the left state into the right one. If I cannot write that merge correctly, I declare the gatherer with Gatherer.ofSequential, and a parallel stream will still work, just by running that stage sequentially.

"How does a gatherer compare in cost with an equivalent flatMap or a custom Spliterator?"

A gatherer is implemented as a stage in the stream pipeline, so each element passes through one extra virtual call, the same as a map; the JIT usually inlines the integrator lambda when the pipeline is monomorphic.

flatMap with a state captured outside the lambda is fragile and not parallel-safe, and the stream may buffer the inner stream. A custom Spliterator is fastest but only fits at the source.

In a benchmark the gatherer is within a few percent of a hand-written loop for simple integrators, and the real cost is the same as any stream: boxing of primitives, which gatherers do not avoid, since there is no IntGatherer as of Aug 2026.

Q107. "Give me the JDK roadmap from 21 to 27 as it stands today: what each release added, what each buys a service team, and how the long-term-support cadence works."

Reveal answer

The real test Whether your facts are current to Aug 2026 and you can attach a practical benefit to each release, rather than reciting JEP numbers.

Strong answer As of Aug 2026. JDK 21, September 2023, is a long-term-support release: virtual threads went final under JEP 444, with sequenced collections, record patterns and pattern matching for switch, and generational ZGC as an opt-in.

It buys a team cheap concurrency and the modern language core, and it is the floor I would accept today. JDK 22 made the FFM API final under JEP 454, so native calls without JNI, plus unnamed variables.

JDK 23 made generational the default ZGC mode and withdrew string templates, which remain withdrawn with no replacement shipped.

JDK 24 is the big non-LTS one: JEP 491 removed pinning for synchronized, which makes virtual threads safe on existing code; stream gatherers and the Class-File API went final; the Leyden ahead-of-time class loading cache arrived with -XX:AOTCache; the SecurityManager was permanently disabled; Unsafe memory-access methods started warning; compact object headers appeared as experimental.

JDK 25, September 2025, is the current LTS: scoped values final under JEP 506, structured concurrency still preview, compact object headers as a supported product option with -XX:+UseCompactObjectHeaders saving about 4 bytes per object, generational Shenandoah, the AOT cache made easier with -XX:AOTCacheOutput plus AOT method profiling, JFR CPU-time profiling on Linux, JFR method timing and tracing, module import declarations, compact source files with instance main, and flexible constructor bodies.

It buys faster startup, a smaller heap and better profiling on a supported base. JDK 26, March 2026, added AOT object caching with any collector including ZGC, cheaper G1 write barriers, and the sixth structured concurrency preview.

JDK 27, scheduled for 15 September 2026 and in release candidate now, makes G1 the default everywhere including small containers, turns compact object headers on by default, adds a JSON API under JEP 540, a seventh structured concurrency preview that is still not final, and post-quantum key exchange in TLS. Cadence: a feature release every six months in March and September, and a long-term-support release every two years, so 21, 25 and the next in 2027, with non-LTS releases supported only until the next one ships.

I would verify any single fact on the JEP page before a planning document, because 27 is not yet general availability.

Land it The practical line is that 21 gives you virtual threads, 25 gives you virtual threads without pinning plus a smaller and faster runtime, and 27 will make the fast defaults the defaults.

Likely follow-ups
"Why would a team ever run a non-LTS release such as 24 or 26?"

Because a specific feature is worth the shorter support window. JDK 24 is the honest example: a team migrating to virtual threads on 21 in early 2025 hit synchronized pinning in their JDBC driver, and 24 removed it six months before 25 shipped.

The cost is that a non-LTS release receives updates only until the next release, so running 24 meant committing to move to 25 in September 2025.

I treat non-LTS releases as a bridge for a team that upgrades every six months anyway, which is easier than it sounds when the build is automated and the JDK is a container base image. For a fleet that upgrades every two years, LTS only.

"What in this roadmap actually changes memory or latency without code changes?"

Three things.

Compact object headers, opt-in on 25 with -XX:+UseCompactObjectHeaders and default on 27, shrink every object header from 12 to 8 bytes, which in object-heavy services cuts live heap by 10 to 20 percent and improves cache behaviour; I would trial it on 25 with a JFR baseline.

The AOT cache from 24 onward cuts startup by loading pre-parsed and pre-linked classes, often halving time to first request, and 26 lets it hold heap objects under ZGC too.

And generational ZGC as default in 23 and later, plus G1's cheaper barriers in 26, reduce pause and throughput cost with no flags. Each is worth one canary run and one dashboard comparison.

"What has been removed or disabled on the way, which an upgrade must check?"

The SecurityManager is permanently disabled since 24; System.setSecurityManager throws, so any code or policy file that depended on it must go. Thread.stop, suspend and resume throw UnsupportedOperationException since 20 and 21. The 32-bit x86 port was removed in 25.

finalize has been deprecated for removal since 18 and will eventually need Cleaner instead. The non-generational ZGC mode is gone since 24, so -XX:-ZGenerational is an error. Unsafe memory access warns since 24 with a flag to allow or deny.

And the Graal JIT left the JDK at 17, so -XX:+UseJVMCICompiler requires GraalVM. I would grep launch scripts for each before the upgrade.

"Structured concurrency has been in preview since 19. Why so long, and does it matter?"

The API has been redesigned twice. The 21 version had subclasses like ShutdownOnFailure; 25 replaced them with a Joiner interface and a configuration function; 26 changed return types and added onTimeout; and 27 under JEP 533 changes the exception type again.

The team is waiting until the shape stops moving, which is what preview is for. It matters in one practical way: code written against 21's preview does not compile on 25, so anyone who shipped it must rewrite.

That is why I would keep production fan-out on a small helper over virtual threads until the JEP page says final, and switch then; the helper is fifty lines and the switch is mechanical.

Drill · Gatherers, FFM, modules & the JDK 21→27 roadmap

This group tests whether you can work with native memory, modules and runtime images on a modern JDK, and whether you can plan an upgrade across the JDK 21 to 27 releases with the facts as they stand in Aug 2026.

Q108 · Scenario. "After upgrading to JDK 25 the logs print 'WARNING: A restricted method in java.lang.foreign.Linker has been called', and later an IllegalCallerException. A second library prints warnings about sun.misc.Unsafe. What is happening and what do you do?"

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: two different libraries touching two different restricted areas of the JDK, and the JDK's "integrity by default" policy telling us about it. Restricted means the method can break the JVM's own safety guarantees, so the JDK wants explicit permission from whoever launches the application, not from the library.
  2. Evidence: the first warning names the module or the unnamed module and the method, for example Linker.downcallHandle, called by a library using the FFM API; the IllegalCallerException comes when the call is denied outright, either because a stricter policy is in force or because a different code path enforces it. The second warning is JEP 471's deprecation of the memory-access methods in sun.misc.Unsafe, printed once per method on first use since JDK 24 under the default setting. jdeps --jdk-internals app.jar lists which libraries use Unsafe.
  3. Ranked causes: a native-access library such as a JNI-replacement, a compression or database driver using FFM, launched without --enable-native-access; an older serialisation, caching or collections library using Unsafe.getInt and friends; and a launcher or container image that sets --illegal-native-access=deny, which turns the warning into the exception.
  4. Fix: for FFM, grant access explicitly with --enable-native-access=ALL-UNNAMED for class path code or --enable-native-access=com.acme.native for a named module, or in a jar's manifest with Enable-Native-Access: ALL-UNNAMED for an executable jar; for Unsafe, upgrade the library to a version using VarHandle or FFM, and until then run with --sun-misc-unsafe-memory-access=allow to silence or =warn to keep the reminder; =debug prints a stack trace per use, which is how I find the caller, and =deny is the future default that I would test in staging.
  5. Prevention: run every candidate JDK in staging with --illegal-native-access=deny and --sun-misc-unsafe-memory-access=deny to surface all offenders before the defaults change, keep the flags in the launch script alongside a comment naming the library, and track upgrades. The defaults tighten release by release, so I would verify on the JEP 471 and JEP 472 pages exactly which mode a given JDK ships with.

Land it The JDK is moving from "libraries may break the JVM if they like" to "the application owner must say so", and the upgrade work is to say so explicitly for the few libraries that need it while pushing them to stop needing it.

Likely follow-ups
"The fix didn't work: you added --enable-native-access=ALL-UNNAMED and the exception persists. What next?"

Then the caller is not in the unnamed module. If the library is loaded as a named module, on the module path or as an automatic module, it needs its own name in the flag, for example --enable-native-access=org.lz4.java, and the warning text tells me which module.

If the application is launched through a wrapper that builds its own command line, the flag may not reach the JVM at all, which I would check with jcmd <pid> VM.flags and VM.command_line.

A third possibility is that the exception is not about native access but about a restricted method reached through reflection, such as Module.addOpens, which needs --add-opens instead.

"Why did the JDK restrict Unsafe after twenty years of everyone using it?"

Because it makes the JVM's guarantees conditional on library authors getting it right, and they often did not. An unchecked Unsafe.putLong to a wrong offset corrupts the heap, which appears later as a crash in the garbage collector with no useful stack.

Every JVM change to object layout, such as compact object headers in JDK 25 and later, risks breaking code that hard-coded offsets. The replacements now exist: VarHandle for fields and arrays with fences and atomic operations, and the FFM API for off-heap memory.

JEP 471 deprecates the memory-access methods for removal in phases, warnings first, then deny by default, then removal, and the flag exists so that each fleet can move at its own pace.

"How would you find every restricted call before the upgrade, not after?"

Static first: jdeps --jdk-internals -R --class-path 'lib/*' app.jar lists each library that references sun.misc.Unsafe or other internal packages and, for the well-known ones, prints the suggested replacement. For FFM, jdeps does not flag restricted calls, so I would grep the dependency list for libraries known to use it and then run the test suite with --illegal-native-access=deny and --sun-misc-unsafe-memory-access=deny so that every offender fails loudly. That pair of flags in the CI job on the new JDK is the cheapest early warning I know.

Q109 · Design. "We have a JNI binding to a C image-processing library. Design its replacement with the FFM API, including memory lifetime, error handling and how you keep it safe."

Reveal answer

The real test Whether you know the parts of the FFM API, the Foreign Function and Memory API final in JDK 22 under JEP 454, and can reason about arena choice and thread confinement rather than listing class names.

Strong answer Requirements and assumptions: the C library exposes resize(const uint8_t* in, size_t len, int w, int h, uint8_t* out) and a callback for progress; images are up to 50 megabytes; calls come from request threads; we want no JNI glue code and no crashes from lifetime mistakes.

Design: bind with Linker.nativeLinker() and SymbolLookup.libraryLookup("libimg.so", arena); each function becomes a MethodHandle from linker.downcallHandle(symbol, FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, JAVA_INT, JAVA_INT, ADDRESS)), created once at startup and stored in static finals so the JIT can inline the call.

I would generate these with jextract from the header rather than write them by hand, and check the generated layouts into the repository. Memory: every native allocation happens in an Arena, which owns a set of MemorySegments and frees them together when closed.

For a request, Arena.ofConfined() in a try-with-resources: only the creating thread may touch its segments, the JVM enforces that, and the segments are freed deterministically at the end of the request.

The input image is copied into a segment with arena.allocate(len) and MemorySegment.copy, the output segment is allocated the same way, and the result is copied back to a byte array before the arena closes.

Every access through a segment is bounds-checked and liveness-checked, so a wrong length throws IndexOutOfBoundsException and a use after close throws IllegalStateException instead of corrupting memory.

The progress callback is an upcall stub from linker.upcallStub(handle, descriptor, arena), allocated in a global or automatic arena because the library may hold the pointer. Strings for error messages come back as a MemorySegment read with getString(0).

Safety: the module that holds this code is the only one launched with --enable-native-access, and the binding runs on a small platform-thread pool because a downcall pins a virtual thread.

Trade-offs: copying the image in and out costs a few milliseconds at 50 megabytes, which I accept for safety; a shared arena would allow multiple threads but needs a careful close.

What I would not do is use Arena.global() for per-request buffers, which leaks, or hand raw addresses to other threads.

Land it FFM replaces the C glue with Java that the JVM can check, and the whole design reduces to choosing the arena whose lifetime matches the data.

Likely follow-ups
"The requirement changes: the library must process images from many threads sharing one large buffer. What changes?"

The confined arena no longer fits, because only one thread may access it.

I would use Arena.ofShared() for the buffer, which allows access from any thread and whose close() is safe: it stops all threads at a safepoint, checks that no access is in progress, and only then frees the memory, so a late reader gets an exception rather than a crash.

That close is expensive, on the order of a safepoint, so I would keep the shared arena alive for the process and slice it per request, with each request using segment.asSlice(offset, len) and a simple allocator in front.

I would also pin a byte layout for the slices with MemoryLayout.structLayout and access fields through VarHandles from layout.varHandle(PathElement.groupElement("width")).

"What would you cut under time pressure?"

I would cut jextract and hand-write the three descriptors we need, because setting up the tool in the build takes a day. I would cut the progress upcall and poll the output instead.

I would keep the confined arena per request and the copy-in-copy-out, because those are the safety properties; a shortcut there is exactly the kind of bug that appears as a segmentation fault at 3 a.m. under load.

I would also keep the platform pool, since pinning a virtual thread inside a 200-millisecond resize would stall the scheduler.

"How does the cost of an FFM downcall compare with JNI?"

For a plain call with primitive arguments the two are close, tens of nanoseconds, and FFM can be slightly faster because there is no hand-written transition code and the JIT understands the method handle.

FFM adds the option Linker.Option.critical(true) for very short calls that must not block, which skips the thread-state transition, and isTrivial-style calls can approach a direct call.

Where FFM wins clearly is on memory: MemorySegment access compiles to the same code as an array access after bounds checks are hoisted, whereas JNI's GetByteArrayElements often copies.

Where JNI still wins is code that already exists and is stable; I would not rewrite a working binding for speed alone.

Q110 · Scenario. "An FFM downcall crashes the JVM with an hs_err file pointing into libc, but only under load. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: a segmentation fault inside native code, so Java's own checks were bypassed. The FFM API checks bounds and liveness on the Java side; once the pointer is handed to C, anything C does with it is unchecked. "Only under load" means a race or a size that only appears with concurrency.
  2. Evidence: the hs_err_pid.log file shows the faulting address, the native frames, and the Java frames above them, which name the downcall handle and the caller; running with -Xlog:foreign* is limited, so I would add logging around the call and, in staging, run under valgrind or with the C library built with AddressSanitizer to get the exact bad access.
  3. Ranked causes: a shared arena closed by one thread while another thread's downcall still runs, which the JVM cannot detect inside native code because the check happens before the call, not during it; the native library storing the pointer, for example in an internal cache or a callback registration, and using it after our arena freed the memory; a struct layout that is wrong for the platform, typically missing padding so a field lands at the wrong offset, which reads garbage until a large value makes it a wild pointer; a string passed without its terminating zero because it was copied with MemorySegment.copy instead of arena.allocateFrom(String); and a buffer sized for the average image, not the largest.
  4. Fix, per cause: never close an arena while calls are in flight, which means either confined arenas per call or a shared arena whose close happens after a barrier such as a Phaser confirms no callers; for pointers the library keeps, allocate in Arena.ofAuto() or global and manage the lifetime explicitly; regenerate layouts with jextract and verify layout.byteSize() against sizeof in C; use allocateFrom for strings; size buffers from the maximum and check with segment.byteSize() before the call.
  5. Prevention: a test that runs the binding from 100 threads with a small heap and arenas closing aggressively, run under AddressSanitizer in CI; a review rule that every downcall documents which arena its arguments come from and who closes it.

Land it FFM guarantees safety up to the edge of the call and no further, so every crash in native code is a lifetime or a layout question about the memory you handed over.

Likely follow-ups
"The fix didn't work: you switched to confined arenas per call and it still crashes. What next?"

Then the memory is not ours, or the layout is wrong.

If the library allocated the memory it returns, for example a result struct we read after the call, the confined arena did not cover it and the library may have freed it on the next call; the fix is to copy the result into our own segment immediately, before any further call.

If the crash address is inside the library's own data, a layout mismatch is likely: I would print layout.byteSize() and each field's offset from layout.byteOffset(PathElement.groupElement("name")) and compare with a tiny C program printing offsetof.

Finally I would check that the downcall descriptor's return type matches: declaring JAVA_INT for a function that returns a pointer truncates it on 64-bit systems, and that only crashes once addresses exceed 4 gigabytes, which happens under load.

"Why does Arena.ofShared().close() need a safepoint, and what does that cost?"

A shared segment may be in the middle of an access on another thread, and the JVM cannot free the memory until it is sure no such access exists.

It brings all threads to a safepoint, inspects their frames for in-progress accesses to that segment, and if it finds one it makes that access throw and retries.

That is a global pause, similar in cost to a garbage collection safepoint, so closing a shared arena thousands of times per second is a performance bug.

The design rule follows: confined arenas for short lifetimes, shared arenas for long ones, and Arena.ofAuto() when you want the garbage collector to free the memory whenever the segment becomes unreachable and do not need determinism.

"How does a downcall interact with garbage collection and with virtual threads?"

A downcall is a native transition: the thread's state changes to "in native", which lets the collector run without waiting for the call, and native code must not touch Java heap memory, which is why FFM makes you copy into off-heap segments or use a heap segment only with Linker.Option.critical(true) for very short calls. For a virtual thread, the native frame on its stack cannot be moved to the heap, so the thread is pinned to its carrier for the whole call. A 200-millisecond image resize on a virtual thread therefore holds a carrier for 200 milliseconds, and eight such calls freeze the scheduler; the binding belongs on a platform pool.

Q111. "Explain the Java module system as you would use it in practice: the directives, strong encapsulation, the escape hatches, automatic modules and jlink. Where does it actually pay off?"

Reveal answer

Strong answer The Java Platform Module System, JPMS, groups packages into named units with explicit boundaries.

A module-info.java declares them: requires names a dependency; requires transitive passes it on to whoever requires us; requires static is compile-time only, for annotations; exports makes a package's public types visible to everyone, or exports ... to for named friends; opens allows deep reflection into a package at run time, which frameworks need for private field injection; uses and provides ... with declare service consumers and providers for ServiceLoader.

Strong encapsulation is what the JDK itself uses: since JDK 16, and fully in 17, code cannot reflect into JDK internals such as sun.nio.ch or java.lang's private fields unless the launcher grants it with --add-opens java.base/java.lang=ALL-UNNAMED, and --add-exports does the same for compile-time access to non-exported packages.

Most applications live in the unnamed module, the class path, which reads every named module and exports everything, so they need no module descriptor; a jar without one placed on the module path becomes an automatic module named from its Automatic-Module-Name manifest entry or its file name, and it reads everything and exports everything.

jlink builds a runtime image containing only the modules you list, with jlink --add-modules java.base,java.sql,com.acme.app --strip-debug --no-header-files --no-man-pages --compress=zip-6 --output image, and needs every module to be explicit; automatic modules are not allowed.

jdeps --print-module-deps app.jar tells you the JDK modules an application needs, and jdeps --jdk-internals lists illegal internal usage before the upgrade does.

Where modules pay off: shrinking a container image from a 300-megabyte JDK to a 50-megabyte runtime; making the JDK's own encapsulation hold; a large codebase that wants enforced boundaries between teams' packages; and plugins with strict isolation through ModuleLayer.

Where they do not: a typical service with fifty libraries of mixed module quality, where the class path plus a jlink image of only JDK modules gets most of the benefit with none of the fighting.

Land it Most teams should use modules to shrink the JDK they ship and to respect the JDK's own boundaries, and only modularise their own code when the boundary is worth enforcing.

Likely follow-ups
"Why does --add-opens keep appearing in launch scripts, and how would you get rid of one?"

Because a library does deep reflection into a JDK package, for example a serialisation library reading java.util.ArrayList's private elementData, or an older Netty accessing sun.nio.ch.DirectBuffer. Each such access needs the flag, and they accumulate.

To remove one I would run the test suite without it and read the InaccessibleObjectException, which names the library frame, then check whether a newer version of that library removed the access, which most did between 2021 and 2023.

If not, the flag stays with a comment naming the library and the issue number. The flag itself is not harmful, but every one is a promise that we know which internal the library depends on.

"What does jlink do to a JDK module to make the image small?"

It reads the modules from the JDK's jmods directory, which are archives of class files, native libraries, headers and resources per module, and writes only the requested ones into a single lib/modules file in its own image format, a jimage, that the JVM maps directly.

Plugins run over the content: --strip-debug removes debug attributes, --compress=zip-6 compresses entries, and --no-header-files and --no-man-pages drop what a runtime does not need.

A minimal image with java.base only is around 25 to 30 megabytes as of JDK 25; adding java.sql, java.net.http and jdk.unsupported for libraries that need Unsafe is typical. One caveat is that the image is tied to a JDK version; upgrading means rebuilding it.

"How does a service provider work across modules, and what is the class path equivalent?"

An API module declares uses com.acme.spi.Codec; each implementation module declares provides com.acme.spi.Codec with com.acme.json.JsonCodec; at run time ServiceLoader.load(Codec.class) finds every provider in the module graph, without the implementations being exported, so the implementation packages stay hidden. On the class path the same works through META-INF/services/com.acme.spi.Codec files listing implementation class names, which is how JDBC drivers register. The module form is checked at compile and link time, and jlink --bind-services pulls providers into the image, which is the answer to "the driver is missing from my image".

Q112 · Scenario. "We built a jlink runtime image for our service. It starts, then fails with ClassNotFoundException for the PostgreSQL driver, and logging prints that no provider was found. Walk me through it."

Reveal answer

Strong answer I would diagnose in this order:

  1. Symptom: two components discovered through ServiceLoader, a JDBC driver and a logging backend, are missing at run time while the application code itself loads. That is the signature of a module image that omitted service providers, or of a mix where the image was expected to contain jars that are actually still on a class path.
  2. Evidence: image/bin/java --list-modules shows which modules are in the image; if org.postgresql.jdbc and the logging implementation module are absent, that is the cause. jdeps --module-path lib --print-module-deps app.jar lists only compile-time dependencies, so providers that are only reached through ServiceLoader never appear, and a build that fed jdeps output into --add-modules silently dropped them.
  3. Ranked causes: providers not added, since jlink only includes what is transitively required unless told otherwise; the driver jar is an automatic module, which jlink refuses, so someone left it out or put it on a class path that the image launcher does not read; the logging backend is loaded by name through reflection and its module is not in the graph; or the META-INF/services file of a class path jar has no counterpart provides directive once the jar became a module.
  4. Fix: add the providers explicitly with --add-modules org.postgresql.jdbc,ch.qos.logback.classic, or use jlink --bind-services, which pulls in every module that provides a service some included module uses, at the cost of a larger image. For automatic modules, either generate a real descriptor with jdeps --generate-module-info out lib/postgresql.jar, compile it into the jar, and put the result on the module path, or use a plugin such as the Moditect tooling that does this in the build. If that becomes a fight across many libraries, keep the application on the class path and use jlink only for the JDK modules, launching with image/bin/java -cp 'lib/*' com.acme.Main, which is the pragmatic middle ground most teams end up with.
  5. Prevention: an integration test that starts the built image and performs a real database query and a real log write; and a build rule that lists the service-provider modules explicitly rather than deriving them from jdeps.

Land it jlink includes what is required, not what is discovered, so every ServiceLoader provider must be named or bound explicitly or the image is complete only on paper.

Likely follow-ups
"The fix didn't work: the modules are in the image, --list-modules shows them, and the driver still is not found. What next?"

Then the lookup is not going through the module graph. If the code calls Class.forName("org.postgresql.Driver") from the unnamed module, it can only see that class if the driver's module exports the package and the caller reads the module; --add-reads ALL-UNNAMED=org.postgresql.jdbc or a proper requires fixes that.

If a connection pool uses ServiceLoader from its own module, that module must declare uses java.sql.Driver, and java.sql does; but a logging facade that does ServiceLoader.load(SLF4JServiceProvider.class) from an automatic module works only if the provider module's descriptor actually has the provides clause, which a generated descriptor from jdeps includes only when the META-INF/services file was present. java --show-module-resolution prints the graph and usually ends the search.

"Is it worth modularising the application itself, or just the JDK?"

For a service with dozens of third-party jars, my default is to modularise only the JDK: jdeps --print-module-deps on the fat jar gives the list, jlink builds an image of those JDK modules, and the application stays on the class path.

That gets the image size and the startup benefit with no descriptor work. Modularising the application pays when you want the boundaries enforced, when you build plugins in layers, or when you want the smallest image and the class-path jars are few and already modular.

I would measure first: if the JDK-only image is 60 megabytes and the app jars are 40, full modularisation cannot save more than a few megabytes.

"What is --bind-services and why not always use it?"

It tells jlink to add, for every service used by a module in the image, every module on the module path that provides it, and then repeat until the set is stable.

With the JDK's own modules on the path that pulls in a surprising amount, such as every locale provider, every crypto provider and every charset, which can add tens of megabytes.

Used with a carefully limited module path it is exactly right, and it is the fastest way to make a JDBC driver or logging backend appear. I use it when the module path is under my control and name modules explicitly when it is not.

Q113 · Design. "Design a pipeline that reads a 200 gigabyte log file, parses each line into a record, and writes a compressed output, using memory-mapped files and the FFM API. What would you cut?"

Reveal answer

Strong answer Requirements and assumptions: one machine with 16 cores, 64 gigabytes of memory and fast local storage; lines average 200 bytes; the output is gzip or zstd; the job must be restartable and verify its own output.

The bottleneck is not CPU but moving bytes, so the design avoids copies.

Mapping: the whole file cannot be mapped at once safely, so I map it in chunks of 1 gigabyte with FileChannel.map(READ_ONLY, offset, size, arena), the JDK 22 overload that returns a MemorySegment owned by an Arena.ofShared(), so the chunk can be read by many threads and unmapped deterministically when the arena closes, instead of waiting for the garbage collector as old MappedByteBuffers did.

Chunk boundaries fall mid-line, so each worker scans forward from its start to the first newline and past its end to finish the last line, which handles boundaries without a coordinator.

Parsing: a worker walks its slice with segment.get(JAVA_BYTE, i), which the JIT compiles to a plain load after hoisting the bounds check, finds separators, and builds a record only for lines that pass the filter; for fields it needs as text it decodes with segment.getString(offset) on a sub-slice or, better, avoids strings entirely and compares bytes.

Workers: this is CPU-bound and native-adjacent, so it runs on a fixed platform pool of 16, not virtual threads, with a chunk queue of length 2 so at most 3 gigabytes are mapped at once; that queue is the backpressure.

Output: each worker compresses its own chunk into a separate part file with a GZIPOutputStream or a zstd binding, records a CRC-32C checksum with java.util.zip.CRC32C, and writes a manifest line; part files are concatenated at the end, which gzip permits.

Restart: the manifest lists finished chunks, so a rerun skips them. Page cache: sequential mapping and advancing chunks let the kernel read ahead; I would call MemorySegment.load() on the next chunk on a helper thread to prefault pages.

Trade-offs: parallel parts lose global ordering, which the manifest preserves by chunk index; a shared arena close costs a safepoint per chunk, which at 200 closes is nothing.

What I would not do: read with BufferedReader.readLine, which allocates a string per line, 1 billion strings; map the entire file; or use virtual threads for the workers.

Land it The job is a byte-moving problem, so the design keeps bytes where the kernel put them, parses in place, and lets a small bounded queue of mapped chunks set the memory ceiling.

Likely follow-ups
"The requirement changes: the input arrives as 10,000 files on object storage, not one local file. What changes?"

Mapping disappears, because you cannot map a remote object, and the unit of work becomes a file rather than a chunk.

Each worker streams one object through the storage client's InputStream into a reusable off-heap buffer allocated once per worker from a confined arena, parses from that buffer, and writes its part.

The download is I/O-bound, so a separate stage of virtual threads fetches ahead into a bounded queue of buffers, and the 16 platform workers parse; the queue length is again the memory ceiling. The manifest keys on object name and etag for restartability.

Throughput is now limited by network, so I would measure that first and consider running on several machines.

"What would you cut under time pressure?"

I would cut the FFM segments and use FileChannel.map returning MappedByteBuffer with the 2 gigabyte limit, accepting that unmapping waits for the collector, which is fine for a batch job that exits. I would cut the manifest-based restart and rerun from scratch on failure. I would cut the prefaulting helper. I would keep the chunking with boundary handling, the platform pool with the bounded queue, and the per-part checksum, because without those the job either runs out of memory or produces output nobody can trust.

"How do you verify the pipeline is really zero-copy and where the time goes?"

Three measurements. JFR allocation profiling with jdk.ObjectAllocationSample should show almost no allocation in the parse loop, only records for matching lines; a byte array or string per line means a copy crept in.

The JDK 25 CPU-time profiler attributes CPU to the parser versus the compressor, and in practice compression dominates, which is why parts are compressed in parallel.

Finally, perf stat or the JFR jdk.FileRead events confirm the kernel is reading sequentially at the disk's rate; page faults visible through perf show whether prefaulting helps.

The target I would state is that the job runs at the slower of disk read speed and compression speed, and nothing else.

Q114 · Design. "Design a modular application shipped as a jlink image: API, implementation and plugin modules, plugin loading, image size, startup, and the container image. When would a fat jar be the better answer?"

Reveal answer

Strong answer Requirements and assumptions: a data-ingestion service where third parties supply parsers as plugins, we control the core, the container must be small and start fast, and plugins must not reach into the core's internals. Design.

Modules: com.acme.ingest.api exports the parser interface and the record types plugins need and nothing else; com.acme.ingest.core requires the API, exports nothing, and holds the pipeline; com.acme.ingest.app is the launcher.

Plugins: each is a module that requires the API and declares provides com.acme.ingest.api.Parser with com.acme.csv.CsvParser; the core declares uses com.acme.ingest.api.Parser. Loading: plugins are not linked into the image.

At startup the core builds a ModuleLayer over a plugin directory with ModuleFinder.of(pluginDir), resolves the found modules against the boot layer's configuration, defines them with a fresh class loader per plugin, and calls ServiceLoader.load(layer, Parser.class), so plugins can be added by dropping a jar, can carry their own dependency versions, and cannot see the core's non-exported packages, which the JVM enforces.

Image: jlink --module-path $JAVA_HOME/jmods:build/mods --add-modules com.acme.ingest.app --strip-debug --no-header-files --no-man-pages --compress=zip-6 --output image, which for a core needing java.base, java.net.http and java.sql gives roughly 50 to 60 megabytes.

Startup: after the image is built, run a training run to produce a Leyden AOT cache with -XX:AOTCacheOutput=app.aot on JDK 25 and start with -XX:AOTCache=app.aot, which pre-loads and links the classes and typically halves time to first request; the cache is tied to the exact image and class path, so it is built in the same pipeline.

Container: a distroless base with only libc and certificates, the image copied in, no JDK, no shell, running as a non-root user; total around 80 megabytes.

Trade-offs: every library the core uses must be a proper or automatic module, and automatic ones cannot be linked, so the core's dependencies are chosen for module quality; plugin authors must write a descriptor.

A fat jar is better when the dependency set is large and of mixed module quality, when there is no plugin isolation requirement, and when the team lacks appetite for descriptor maintenance; then a jlink image of only JDK modules plus the fat jar on the class path gets most of the size and startup win.

What I would not do is modularise fifty third-party jars by hand, or load plugins on the class path and rely on convention to keep them out of internals.

Land it Modules earn their cost here because the plugin boundary must be enforced, not just documented, and ModuleLayer is the only JDK mechanism that enforces it.

Likely follow-ups
"The requirement changes: plugins must be reloadable at run time without a restart. What changes?"

The layer per plugin is already the right unit; reloading means creating a new layer with a new class loader for the new jar, switching the service registry to the new parser instances, and dropping every reference to the old layer so its classes can be unloaded by the collector.

The hard part is references: any cached parser instance, thread, or ThreadLocal holding an old class keeps the whole old layer alive, which is a metaspace leak.

I would give each plugin a lifecycle interface with a close() that stops its threads, verify unloading in a test with -Xlog:class+unload, and keep a metric of live layers.

If plugins cannot be trusted to close cleanly, the honest answer is a restart, which with the AOT cache is a few hundred milliseconds.

"What would you cut under time pressure?"

I would cut the per-plugin ModuleLayer and load plugins in the boot layer through the module path, which keeps encapsulation but loses per-plugin dependency isolation and reloading.

I would cut the AOT cache from the first release and add it once the image is stable, since its training run is another pipeline step.

I would keep the API module's minimal exports and the jlink image, because those are what make the boundary real and the container small.

A fat jar with plugins in a directory on a class path is the fallback I would take only if the module work blocked the release.

"How do you keep the image size honest as dependencies grow?"

Two checks in the build. jdeps --print-module-deps --ignore-missing-deps on the application modules produces the JDK module list, and the build fails if a new JDK module appears without a review, because java.desktop sneaking in through an image library adds 30 megabytes.

And a size gate on the output: du -sh image compared with the previous build, failing on more than 10 percent growth. I also list what each module pulls with java --describe-module when investigating.

In one case a logging library requiring java.management pulled in half the JDK, and the fix was a requires static in its descriptor upstream.

Q115 · Design. "Plan the upgrade of a fleet of two hundred services from JDK 17 to JDK 25. What do you check, in what order do you roll, what do you switch on, and what do you refuse to do?"

Reveal answer

Strong answer Requirements and assumptions: services on Spring Boot with shared base images and a common build, mixed ages, some with JNI or serialisation libraries, all with JFR available; the goal is JDK 25 as the LTS base with no regression, not adopting every new feature at once.

Phase one is inventory, run by the build on every service: jdeps --jdk-internals for Unsafe and internal API users; a scan of launch scripts for -XX:-ZGenerational, -Djava.security.manager, Graal JIT flags, and --add-opens entries; a dependency report flagging libraries with known JDK 25 issues, such as old bytecode tools that must understand class file version 69.

Phase two is a CI matrix running each service's tests on 25 with strict flags to surface future breakage now: --sun-misc-unsafe-memory-access=warn then deny, and --illegal-native-access=deny.

Fix categories: SecurityManager code deleted, since it is permanently disabled since 24; Thread.stop callers removed; libraries upgraded for Unsafe; JNI libraries granted native access explicitly.

Phase three is the roll, in rings: ten low-risk stateless services for two weeks, then a quarter of the fleet, then the rest, each service as a canary instance beside a control instance with a JFR baseline recorded on 17 beforehand and compared on 25 for allocation rate, GC pause, CPU per request and startup.

GC defaults to check: G1 remains the default on 25 unless the container has fewer than two CPUs or under 1792 megabytes, where the serial collector is chosen, which JDK 27 changes; ZGC users get generational mode with no flag; MaxRAMPercentage stays 25 percent.

Switch on later, one at a time, each with its own canary: compact object headers with -XX:+UseCompactObjectHeaders for heap savings, the AOT cache for startup, and virtual threads only for services that mostly wait.

Rollback: the base image tag is the rollback, and no feature flag that requires 25 is enabled until a service has run there for a month.

What I would not do: upgrade and enable new features in the same deploy; migrate through 21 as a stepping stone, since 21 to 25 has fewer removals than 17 to 21 and a double migration doubles the testing; or let services opt out indefinitely, because 17's free updates are ending and the fleet must move together.

Land it The upgrade is an inventory problem first and a ring rollout second, and every optional feature waits its turn behind a clean baseline on the new runtime.

Likely follow-ups
"The requirement changes: a quarter of the services cannot leave 17 for a year because of a vendor library. How does the plan change?"

Then the fleet runs two JDKs and the plan needs a wall between them.

The shared build produces both base images, and a service declares its JDK in one place so nobody accidentally compiles library code with --release 25 that a 17 service consumes; shared internal libraries build with --release 17 until the last consumer moves.

The 17 group gets a named owner, a deadline tied to the vendor's roadmap, and extended-support updates purchased if free ones end. I would still run their tests on 25 monthly so the eventual move is small.

What I would not do is fork the shared libraries, because that doubles every fix for a year.

"What would you cut under time pressure?"

I would cut the strict-flags CI matrix to a single run with warn rather than deny and read the warnings by hand. I would cut the middle ring and go from ten services to the whole fleet if the first ring is clean for two weeks.

I would cut the compact headers and AOT trials entirely from this project and schedule them later.

I would keep the jdeps inventory, the canary-with-control pattern and the JFR baseline, because those are what catch a regression before users do, and I would keep the rule that nothing new is enabled in the upgrade deploy.

"Which regressions have actually appeared in 17 to 25 upgrades, and how do you spot them?"

A few recur. Dynamic agent loading warns since 21 under JEP 451, so an APM agent attached at run time prints a warning and needs -XX:+EnableDynamicAgentLoading or a -javaagent flag at startup.

Bytecode libraries such as older ASM or ByteBuddy fail on new class file versions with UnsupportedClassVersionError or an IllegalArgumentException about unsupported version, which the test run catches. Libraries using Unsafe print warnings and later fail under deny.

Small containers switched to the serial collector on 17 and still do on 25, so they see no GC change until 27. And time-to-first-request can regress slightly from more classes in the JDK, which the AOT cache fixes.

Each shows in the canary's logs or the JFR comparison within a day.

"How do you build the JFR baseline so the comparison is fair?"

Same service version, same traffic, same instance size, recorded for the same 30 minutes at the same time of day on both JDKs, started with jcmd <pid> JFR.start name=base duration=30m settings=profile filename=/tmp/base.jfr.

I compare a fixed set: allocation rate from jdk.ObjectAllocationSample, pause distribution from jdk.GarbageCollection, CPU per request from the 25 CPU-time profiler where available and from jdk.ExecutionSample on 17, and startup from jdk.InitialSystemProperty timestamps to the first request log line.

jfr summary and jfr print --events give the numbers, and a small script diffs them. A difference over 10 percent on any of them blocks the ring from advancing until explained.

11 · DrillPerformance Investigation Scenarios & Design — Q116–Q150

The last section is the staff-level round: incidents where the evidence is a JFR file, a flame graph, a safepoint log or an hs_err file, and design prompts where you must choose a collector, a threading model and a memory layout and defend the choice. Every scenario is answered in diagnosis order and every design states what it would not do.

Drill · JFR, profilers, safepoints & honest benchmarks

This group tests whether you can pick the right measuring instrument for a JVM question, explain what each one cannot see, and tell a real result from an artefact of the tool.

Q116. "Tell me how you would use Java Flight Recorder on a production service: how you start it, what it costs, which events you actually read, and what changed in it recently."

Reveal answer

The real test Whether you treat JFR as an always-on instrument with named events you can quote, rather than "a profiler you turn on when something is wrong".

Strong answer JFR, Java Flight Recorder, is the event recorder built into HotSpot.

It writes binary events into thread-local buffers and then into a ring buffer on disk, which is why its overhead is around one percent with the default settings and around two percent with the profile settings, which sample more often and enable allocation and lock events with lower thresholds.

I run it continuously: -XX:StartFlightRecording:disk=true,maxage=6h,maxsize=1g,settings=default,filename=/var/log/app.jfr. The ring buffer keeps only the last six hours or one gigabyte, so an incident is always captured.

When I need a snapshot I use jcmd <pid> JFR.dump name=1 filename=/tmp/now.jfr, or I start a short, richer recording with jcmd <pid> JFR.start settings=profile duration=60s filename=/tmp/p.jfr.

The events I read first are jdk.ExecutionSample for CPU hot methods, jdk.ObjectAllocationSample for who allocates, jdk.JavaMonitorEnter and jdk.ThreadPark for who waits and on what, jdk.GCPhasePause and jdk.SafepointBegin for pauses, jdk.Compilation and jdk.Deoptimization for the JIT, the just-in-time compiler, jdk.VirtualThreadPinned for pinned virtual threads, and jdk.OldObjectSample for leaks.

On the command line jfr summary p.jfr lists event counts, jfr print --events jdk.GCPhasePause p.jfr dumps one event type, and since JDK 21 jfr view hot-methods p.jfr or jfr view gc-pauses p.jfr gives a ready-made table.

JDK Mission Control's automated analysis reads the same file and flags the usual problems.

What changed recently, as of Aug 2026: JDK 25 added JEP 509 CPU-time profiling on Linux, the jdk.CPUTimeSample event, which samples by CPU time consumed instead of by wall-clock timer so it does not miss short-lived threads; JEP 518 cooperative sampling, which makes the sampler safer; and JEP 520 method timing and tracing, the jdk.MethodTiming and jdk.MethodTrace events, which let me time a named method with -XX:StartFlightRecording:method-timing=com.acme.Repo::load without any agent.

In code, jdk.jfr.consumer.RecordingStream lets a service subscribe to its own events and export them as metrics.

Land it JFR is the instrument I leave running, because the recording that matters is the one that was already on when the incident started.

Likely follow-ups
"What is the practical difference between default and profile, and when would you dare use profile in production?"

Both are XML files under $JAVA_HOME/lib/jfr. default.jfc samples Java stacks every 20 ms per thread, records monitor waits and parks only above 20 ms, and keeps allocation sampling throttled to about 150 events per second, which is what keeps it near one percent.

profile.jfc samples every 10 ms, lowers the lock threshold to 10 ms, turns on jdk.ObjectAllocationSample at a higher rate and enables jdk.OldObjectSample, which is closer to two percent and grows the file faster.

I use profile in production for bounded windows, typically 60 to 120 seconds on one instance, because that is enough samples to be statistically useful and the cost is bounded. I would not leave profile on indefinitely on a latency-sensitive service.

I can also build my own settings file with jfr configure to keep, say, only the allocation events.

"How would you find a memory leak with JFR instead of a heap dump?"

I would enable the jdk.OldObjectSample event with path-to-GC-roots on: jcmd <pid> JFR.start settings=profile path-to-gc-roots=true duration=10m filename=/tmp/leak.jfr.

That event samples a small number of allocations and, if a sampled object is still alive at the end of the recording, records its allocation stack and the chain of references from a GC root, meaning a static field, a thread stack or a JNI handle, down to it.

jfr print --events jdk.OldObjectSample /tmp/leak.jfr shows the objects that survived longest and where they were allocated. Because it is sampled, it costs almost nothing and does not pause the process, unlike a heap dump.

The trade-off is that it only sees the sampled objects, so a leak of a few large objects can be missed and a heap dump is still the definitive answer.

"Why did JDK 25 add CPU-time sampling when jdk.ExecutionSample already existed?"

jdk.ExecutionSample is driven by a wall-clock timer. Every 10 or 20 ms a sampler thread picks a set of Java threads and records their stacks, whether they are running or not. That has two blind spots.

A thread that runs hot for only two milliseconds between samples may never be seen, and a process with 2,000 mostly idle threads spends samples on idle ones.

JEP 509's jdk.CPUTimeSample uses a per-thread CPU-time timer on Linux, so a thread is sampled in proportion to the CPU it actually consumes, which is what a CPU profile should mean.

It is enabled per recording, for example -XX:StartFlightRecording:jdk.CPUTimeSample#enabled=true, and the recording carries a count of failed samples so I can judge how complete it is. It is Linux-only as of Aug 2026.

"How would you turn JFR events into a metric without shipping recording files?"

Inside the service I would open a jdk.jfr.consumer.RecordingStream, enable the events I care about, for example rs.enable("jdk.GCPhasePause") and rs.enable("jdk.VirtualThreadPinned").withThreshold(Duration.ofMillis(20)), register a handler with rs.onEvent(name, event -> …) that updates a histogram in my metrics library, and call rs.startAsync().

That gives me a Prometheus-style gauge for pause time or pinned-thread count with no file handling at all. The cost is the same as the recording itself.

I keep the stream selective, because enabling everything means the handler runs for tens of thousands of events per second. This is also the mechanism behind JDK 17's jdk.jfr.consumer.EventStream for reading a repository directory remotely.

Q117 · Scenario. "Your team's benchmark says implementation A is three times faster than B. You ship A and production gets slower; B was actually faster there. Walk me through why and what you do."

Reveal answer

The real test Whether you know the specific ways a micro-benchmark lies and can name a measurement that would not have lied.

Strong answer I would work through it in this order:

  1. Symptom: a benchmark result that did not transfer. That is not a mystery, it is the normal outcome when the benchmark measured a different program than production runs. So the first step is to stop arguing about A and B and ask what was different between the two measurements.
  2. Evidence: I compare the two environments explicitly. Which JDK, which GC, what heap size, how many CPUs; the benchmark was probably on a 16-core laptop with a 4 GB heap while production runs with a 2-CPU limit and a 1 GB heap. What data shapes: the benchmark used one input type and one size, production sees a mix. I take a 60-second JFR recording of both versions in production and compare jfr view hot-methods and jfr view allocation-by-site, and I check -XX:+PrintCompilation or the jdk.Compilation events to see whether the hot method was compiled at the same tier in both.
  3. Ranked causes. First, call-site shape: in the benchmark A's interface call saw one implementation and was inlined as a monomorphic call; in production the same site sees five implementations, is megamorphic, and pays a virtual dispatch on every call, while B's simpler design had no such site. Second, on-stack replacement: the benchmark loop was compiled by OSR, which optimises a loop body differently from a full method compile of the real entry point. Third, allocation: A allocates more and it did not matter with a big young generation and an idle CPU, but under a 2-CPU limit the extra garbage collection work competes with request threads. Fourth, data size: A's array-based structure wins at 100 elements and loses at 100,000 when it no longer fits the cache.
  4. Fix: build the benchmark with production-shaped inputs, meaning the real mix of types and sizes recorded from a production sample, run it with the production GC and CPU count, and then confirm with a canary: one instance on A and one on B behind the same load balancer, compared on JFR profiles and latency histograms for an hour.
  5. Prevention: every performance claim that reaches a pull request carries the JMH configuration, the JDK, the flags and the input description, and the merge rule is that a canary, not a benchmark, is what decides.

Land it A benchmark answers the narrow question it was asked; production asks a different question, so the canary comparison is the only result I would ship on.

Likely follow-ups
"You re-ran the benchmark with production-shaped inputs and A is still faster there, but still slower in production. What next?"

Then the difference is not the inputs, it is the surroundings.

I would take async-profiler in wall mode on both canaries, because CPU profiles cannot show a thread waiting; if A is slower because it holds a lock longer or blocks on I/O more, wall mode shows it and CPU mode does not.

I would also look at the jdk.JavaMonitorEnter and jdk.ThreadPark events. Next I would check GC: -Xlog:gc* on both, comparing pause frequency and allocation rate.

Then the JIT: A's hot method might be too large to inline in production because more code was compiled around it, or it might be deoptimising repeatedly, visible as jdk.Deoptimization events.

If all of that is equal, I would check that the benchmark actually exercised the code path production takes, with a coverage run.

"Explain the monomorphic versus megamorphic point with numbers."

HotSpot keeps a type profile per call site, up to TypeProfileWidth=2 receiver types. If one type is seen, the call is monomorphic: the compiler inlines the target behind a cheap class check, and the cost is close to zero.

Two types is bimorphic and still inlinable with two checks. Three or more is megamorphic: the compiler gives up on inlining, emits a virtual or interface dispatch through a table, and every optimisation that needed to see through the call, such as escape analysis, is lost.

The cost is typically a few nanoseconds per call plus the lost inlining, which can be a factor of two to ten on a tiny hot method.

A benchmark that only ever passes ArrayList to a method that in production also receives LinkedList and an unmodifiable wrapper is measuring a different compiled program. -XX:+PrintInlining shows the decision as "virtual call" or "megamorphic".

"What would a fair A/B canary look like, concretely?"

Two instances of the same build, same JDK and flags, differing only in a feature switch that selects A or B, both behind the same load balancer with equal weights so they see the same traffic mix at the same time.

I run them for long enough to cover warm-up and at least one full GC cycle on each, usually an hour.

I compare, not averages, but the latency histogram exported with HdrHistogram at p50, p99 and p99.9, plus CPU per request, allocation rate from JFR and GC pause totals. I also swap which host runs A halfway through, because hosts differ.

The decision rule is written before the test: for example, "A wins if p99 improves by at least 10 percent with no p99.9 regression". Without a pre-stated rule the result gets argued into whatever people wanted.

Q118 · Design. "Design a JMH benchmark that would honestly tell us whether a new serialiser is faster than the old one. Tell me every way the naive version would lie."

Reveal answer

Strong answer Requirements and assumptions: we want a per-message cost, in nanoseconds and in bytes allocated, for realistic message shapes, on the production JDK, with a result that can be compared across builds.

JMH, the Java Microbenchmark Harness, is the tool because it handles forking, warm-up and the compiler traps I am about to list.

Design: one @State(Scope.Thread) class holding a set of pre-built messages read from a captured production sample, with a @Param for size class, small, medium and large, so the result is a table rather than one number.

Each @Benchmark method serialises one message and returns the byte array, or passes it to a Blackhole, so the JIT cannot delete the work as dead code.

I use @BenchmarkMode(Mode.AverageTime) with @OutputTimeUnit(NANOSECONDS), @Fork(3) so three fresh JVMs vote and one unlucky compilation does not decide, @Warmup(iterations=5, time=1) and @Measurement(iterations=10, time=1), and I run with -prof gc so gc.alloc.rate.norm reports bytes per operation, which is often the number that predicts production behaviour better than time.

Where the naive version lies: a result that is not consumed is removed by dead-code elimination, so the loop measures nothing; a message built from constants lets the compiler constant-fold the whole serialisation, which is why inputs live in @State fields, not literals; a manual loop inside the benchmark method gets compiled by on-stack replacement and unrolled, so it measures a loop the real program never runs; a single fork with no warm-up measures the interpreter; a benchmark that serialises one message type sees a monomorphic world the production code does not; and a benchmark run on a laptop with turbo boost and 16 cores does not predict a 2-CPU container.

Trade-offs: three forks and long warm-ups make the suite slow, so it runs nightly, not per commit. What I would not do: I would not report a single "3× faster" figure, and I would not benchmark on a machine other than the production instance type.

Land it A benchmark is honest when I can name what it could not see, so the design is mostly a list of the lies I have removed.

Likely follow-ups
"Requirement change: we now also need to know whether the new serialiser hurts tail latency under concurrency, not just per-call cost. What changes?"

Average time per call cannot show a tail.

I would add a second benchmark in Mode.SampleTime, which records the time of individual invocations into a histogram and reports percentiles, run with @Threads(8) or the production thread count so allocation and any shared state contend the way they will in service.

I would also add -prof gc to see whether the allocation rate under eight threads triggers young collections during measurement, because a GC pause inside a sample is exactly the tail I care about.

Even then, JMH's sample mode suffers from coordinated omission, meaning a long stall hides the requests that would have arrived during it, so for the final answer I would move to a load test against the real service with HdrHistogram recording per-request latency at a fixed arrival rate.

"Under time pressure, what would you cut from this benchmark design?"

I would cut forks from three to one and warm-up to three iterations, accept the noise, and keep everything that protects correctness: the Blackhole, the @State inputs, the production-shaped messages and -prof gc.

Those cost nothing to keep and without them the number is not just noisy but wrong. I would drop the size-class parameter and run only the medium message, because one realistic shape beats three guesses. I would also drop perfasm and any assembly-level investigation.

What I would not cut is running on the production instance type with the production JDK, because a fast result on the wrong hardware is worse than no result.

"What is -prof perfasm for and when is it worth the effort?"

It runs the benchmark under Linux perf, collects hardware instruction samples, and, if the hsdis disassembler plugin is installed, prints the hottest machine instructions of the compiled benchmark next to the Java source they came from.

It is worth it when two versions differ by a small constant factor and I need to know why: whether a bounds check was not eliminated, whether a call was not inlined, whether a loop was vectorised, or whether the hot loop is bound by a memory load.

It is not worth it for a first result, because it needs root or perf_event_paranoid lowered, a matching hsdis build, and time to read assembly. -prof perfnorm is the cheaper sibling: cycles, instructions and cache misses per operation without disassembly.

"Why do you insist on @State for inputs when a local variable would look the same?"

Because the JIT sees through local variables and constants.

If I write byte[] out = serialise(new Order(1, "abc")) inside the benchmark, the compiler can prove the input never changes, evaluate parts of the serialisation at compile time, and hoist the rest out of the timed region, so the benchmark measures a constant.

A field of a @State object is read each invocation through a reference the compiler must treat as potentially changing, so the work is real.

The same reasoning applies to the result: returning it or calling blackhole.consume(out) forces the compiler to keep every instruction that produced it. Since JMH 1.34 on JDK 17 and later the harness can use compiler-supported blackholes, which cost even less, but the discipline is the same.

Q119. "When would you reach for async-profiler instead of JFR, how do you run it, and how do you read what it gives you?"

Reveal answer

Strong answer async-profiler is an external sampling profiler for HotSpot on Linux and macOS. I reach for it when I need something JFR does not give me: native frames, meaning time inside the kernel, libc, JNI libraries or the JVM's own C++ code, shown in the same stack as the Java frames; a wall-clock view of what blocked threads were waiting on; or native memory allocation attribution.

Its sampling has no safepoint bias.

A safepoint is a point in the code where the JVM knows the exact state of every thread and can pause them; a profiler that can only see stacks at safepoints reports the nearest safepoint instead of the real hot instruction.

async-profiler uses AsyncGetCallTrace, an internal HotSpot call that walks the Java stack from a signal handler at any instruction, combined with Linux perf_events for the native side, so the stack it records is the one that was really executing.

I run it against a live process with the command line tool: asprof -d 30 -e cpu -f /tmp/cpu.html <pid> for 30 seconds of CPU samples as a flame graph.

The event modes are cpu for on-CPU time, itimer as the fallback when perf events are not permitted, wall for wall-clock time including waiting, alloc for sampled allocations by type and stack using the JVM's TLAB, thread-local allocation buffer, boundaries, lock for contended monitor time, and nativemem for malloc calls that were never freed.

Reading a flame graph: each box is a frame, width is the share of samples, the y-axis is stack depth with callers below callees.

I look for the widest box at the top of any tower, because that is where time is spent, then read downwards to learn who asked for it. Colour distinguishes Java, JVM, kernel and native frames.

In containers I need perf_event_paranoid at 1 or lower for kernel frames, otherwise I use -e itimer or ctimer; the tool must run inside the same PID namespace as the target, or via nsenter, and /tmp must be shared so the attach socket is visible.

Land it JFR is what I run always; async-profiler is what I attach when the answer is below the Java frames or in the waiting time.

Likely follow-ups
"When is wall mode the right choice, and what does it show that cpu mode hides?"

Wall mode samples every thread at a fixed interval regardless of whether it is running, so a thread sleeping in a socket read or parked on a lock shows up with its full stack.

For a latency question, "why does this request take 80 ms when it uses 3 ms of CPU", wall mode is the only profiler view that answers it, because the other 77 ms are spent waiting and CPU mode records nothing for waiting.

I usually filter to the request threads, asprof -e wall -t -I 'http-*' … style thread filters, because otherwise the hundreds of idle pool threads dominate the graph.

The cost is that wall mode is more expensive, and in a process with thousands of threads I raise the interval to 50 or 100 ms.

The trade-off is that wall mode cannot say whether the wait was avoidable; that comes from reading the frame it waited in.

"Why does async-profiler need perf_event_paranoid lowered, and what happens if the platform team refuses?"

perf_event_open is the Linux system call that creates a hardware or software sampling counter.

The sysctl kernel.perf_event_paranoid controls who may use it: at 2, an unprivileged process can only sample its own user-space; at 1 it can also see kernel stacks; at 3 or higher, which some hardening guides set, it cannot sample at all.

async-profiler's cpu mode wants kernel frames, which is what lets me see time in epoll_wait or page-fault handling.

If the platform team refuses, I run -e itimer, which uses the SIGPROF timer and needs no privilege but shows only user-space, or -e ctimer, which uses per-thread CPU-clock timers and is the better choice in containers.

Alternatively I ask for the capability CAP_PERFMON on that one pod instead of a host-wide sysctl change.

"What does alloc mode actually sample, and how would it mislead you?"

It does not intercept every allocation. It hooks the events HotSpot raises when a thread's TLAB, thread-local allocation buffer, is exhausted and a new one is issued, and when an object is too large for a TLAB and is allocated directly in the heap.

So each sample represents roughly the size of a TLAB's worth of allocation, and the histogram is weighted by bytes, not by count. That is the right weighting for "what is filling my young generation" but it can mislead in two ways.

Tiny objects allocated in huge numbers show up proportionally to their bytes, which may look modest even though their count is what hurts a cache-sensitive path.

And objects the JIT removed through escape analysis never appear at all, which is correct, but it means a debug build with less optimisation shows different allocations than production.

"How do you compare two flame graphs, say before and after a change?"

I collapse both recordings to text with -o collapsed, which gives one line per unique stack with a sample count, and then build a differential flame graph, where each frame is coloured by how its share changed between the two runs, red for grown and blue for shrunk.

async-profiler's converter tooling and the original FlameGraph scripts both support this. The rule I apply is to compare shares, not absolute counts, because the two recordings rarely have the same duration or load.

A frame that grew from 3 to 12 percent is the regression, even if a bigger frame stayed at 40 percent.

For a CI gate I do the same thing automatically on the collapsed files and fail the build when any frame moves by more than a threshold I chose from the noise of two identical runs.

Q120 · Scenario. "A CPU profile shows 40 percent of time in HashMap.get, but no code path we own looks hot and nobody can find the offending map. Where do you start?"

Reveal answer

The real test Whether you understand that a shared JDK method collects the cost of everyone who calls it, and that the profiler's attribution is a question of how you fold the stacks.

Strong answer I would take it in this order:

  1. Symptom: one JDK method dominates, and our own methods look cheap. That pattern usually means the cost is spread over many callers, each individually small, so the hot map is not one map but the sum of them. It can also mean the cost is inside what HashMap.get calls, the key's hashCode and equals, which the profiler attributes to the map because they were inlined into it.
  2. Evidence: first I check the profile is a CPU profile, not a wall-clock one, so the 40 percent is really CPU. Then I flip the flame graph to a reverse, or "callee-up", view, which groups by the frames above HashMap.get and shows what it called: if the width is in String.hashCode or a custom equals, that is the answer. Then I look one frame below HashMap.get to list callers ranked by width; with async-profiler that is the --reverse option or a search for the method name that highlights every occurrence.
  3. Ranked causes. First, expensive keys: a composite key whose hashCode walks a list, or a freshly built String on every lookup, which must recompute its hash because the cache field on a new string is empty. Second, profile pollution: HashMap.get is one piece of bytecode shared by every map in the JVM, so its call to key.equals sees every key type in the process and becomes megamorphic; an application that happens to use one map heavily pays a virtual call and no inlining on it. Third, collisions: keys with poor hash spread put many entries in one bin, and get walks a chain or a red-black tree of them. Fourth, an unexpected caller in a library, for example a metrics tag lookup or a logging context map, executed per event.
  4. Fix, once the caller is known: replace the map with an EnumMap, an array index or a primitive-keyed structure where the key allows; precompute and cache key hashes; intern or reuse keys instead of building them per lookup; for a genuinely hot polymorphic site, give it its own small lookup class so its type profile is clean.
  5. Prevention: an allocation profile alongside the CPU profile, because the freshly built key would have shown up there, and a rule that hot-path maps use stable, cheap keys.

Land it The hot method is not the culprit; the caller that makes it hot is, and finding the caller is a question of turning the flame graph upside down.

Likely follow-ups
"You found the caller and cached the key hash, but the profile barely moved. What next?"

Then the cost was not the hash computation. I would check whether the time is in equals, which runs at least once on every hit, by looking at the reverse graph again after the change.

If equals is expensive because the key is a large record, I would make the comparison short-circuit on the cached hash first.

Next I would check collisions with a quick histogram of bin sizes, because HashMap only treeifies a bin above eight entries and a key whose hashCode returns few distinct values keeps everything in a handful of bins.

If the map is huge, the cost may simply be cache misses on the table array, which no code change to the key fixes; then the answer is a smaller working set or a different structure.

Finally I would confirm the profile was taken after warm-up, because an interpreted HashMap.get looks far more expensive than a compiled one.

"Explain what you mean by profile pollution in JDK code and whether it is fixable."

HotSpot records, per bytecode call site, which receiver types it has seen. HashMap.get contains one call site for key.equals(k). Every map in the process, mine and every library's, executes that same site, so it sees String, Integer, Long, UUID and dozens more.

Beyond two types the site is megamorphic and the JIT cannot inline any equals there, even for a map that only ever holds one key type. It is partly fixable.

Inlining HashMap.get into my caller gives it a fresh copy of the site with my caller's type profile, which is why a small hot wrapper can help.

Otherwise, I sidestep the shared bytecode with a specialised map, such as EnumMap, IdentityHashMap when identity is right, or a primitive collection library. There is no JVM flag that gives each caller its own profile.

"How would you tell whether the profile itself is mis-attributing inlined frames?"

When the JIT inlines String.hashCode into HashMap.get, the machine code for both lives in one compiled method, but the compiler keeps a scope table that maps each instruction back to its original Java method, so a good profiler reports the inlined frame as its own line.

JFR's jdk.ExecutionSample and async-profiler both use those tables. The mis-attribution risk is the opposite: an old-style sampler that only looks at safepoints reports the safepoint's location, which is often the method exit or a loop back-edge, not the hot instruction.

To check, I compare a JFR profile and an async-profiler cpu profile of the same window; if they agree on the split between hashCode, equals and the table walk, the attribution is trustworthy. If a jstack-based tool disagrees with both, I ignore it.

Q121 · Design. "Design the on-host diagnostics procedure an on-call engineer may run against a production JVM: which jcmd, jstat and jmap commands are safe, which are not, and how the output gets analysed."

Reveal answer

Strong answer Requirements and assumptions: the engineer has shell access to the pod or host as the same user as the JVM, the service is under load, and the goal is to collect evidence without making the incident worse.

So the procedure is tiered by how much each command pauses the process.

Tier one, always safe, no pause worth mentioning: jcmd <pid> VM.flags and VM.info for the exact configuration, VM.version, GC.heap_info for current occupancy per generation, Compiler.codecache for code cache use, Thread.print three times ten seconds apart to see what stays stuck, or on JDK 21 and later Thread.dump_to_file -format=json /tmp/threads.json, which also includes virtual threads, and jstat -gcutil <pid> 1000 30 for thirty seconds of generation occupancy and GC counts.

If native memory tracking was enabled at start with -XX:NativeMemoryTracking=summary, then VM.native_memory summary and, later, VM.native_memory baseline followed by summary.diff show which native category is growing.

Tier two, short pauses, allowed on one instance: jcmd <pid> JFR.start settings=profile duration=60s filename=/tmp/p.jfr, and GC.class_histogram, which walks the heap at a safepoint and prints instance counts and bytes per class; on a 16 GB heap that is a pause of a few seconds.

Tier three, dangerous, only on an instance taken out of the load balancer: GC.heap_dump -all /dumps/x.hprof, or jmap -histo:live and jmap -dump:live, all of which trigger a full collection and write the whole heap, pausing for tens of seconds to minutes.

Analysis: JFR files go to jfr view and JDK Mission Control; heap dumps go to Eclipse Memory Analyzer, where the dominator tree, which shows which objects keep the most memory alive, and "path to GC roots" excluding weak references answer the leak question.

Trade-offs: tiering slows the engineer down by a minute, which is the point.

What I would not do: I would not let anyone run jmap -histo:live on a pod in the rotation because the word "live" means "full GC first", and I would not allow a heap dump to a network volume.

Land it The procedure is sorted by pause cost, and the only rule that matters is that anything with a full GC in it happens on an instance that is no longer serving traffic.

Likely follow-ups
"Requirement change: the engineers do not get shell access to production at all. What does the procedure become?"

Then everything that needs jcmd must be reachable another way. I would pre-enable continuous JFR at startup with -XX:StartFlightRecording:disk=true,maxage=4h, so a dump is a call on a management endpoint or a sidecar rather than a shell.

I would expose the diagnostic commands through the platform MBean com.sun.management:type=DiagnosticCommand, which lets an authenticated JMX client, or a small HTTP bridge, run threadPrint, gcHeapInfo and jfrStart remotely. Native memory tracking output comes from the same MBean.

Heap dumps are then set up as -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps onto a volume the platform ships to object storage. Thread dumps can also be obtained by sending SIGQUIT from the orchestrator's exec, which needs no shell for the engineer.

"Under time pressure, which commands do you cut and which do you keep?"

I keep four things: VM.flags, because half of all incidents are a flag nobody knew about; three Thread.print dumps ten seconds apart, because they take under a second and show blocked and busy threads; jstat -gcutil for thirty seconds, because it separates "GC problem" from "not a GC problem" in one screen; and a 60-second JFR recording, because it captures CPU, allocation and locks in one file I can analyse later. I cut the class histogram, native memory tracking unless it was already on, and every form of heap dump, because those cost pauses now and answer questions I can ask tomorrow from the JFR file. If only one thing is possible, it is the JFR recording.

"How large is a heap dump, how long does it take, and what makes Eclipse MAT choke on it?"

An HPROF dump is roughly the size of the used heap, so a 30 GB heap gives a file near 30 GB, and the process is stopped for the whole write; to local NVMe that is a minute or two, to a network volume it can be ten.

Since JDK 15 GC.heap_dump -gz=1 compresses on the fly, usually to a quarter of the size, and JDK 21 added a -parallel option that uses several threads for the heap walk, so I use both.

MAT then needs to build an index; its default is to parse in a JVM with a few gigabytes of heap, which fails on a 30 GB dump.

I run the headless ParseHeapDump.sh on a large machine with -Xmx set to about the dump size, and open only the generated indexes and the Leak Suspects report on the laptop.

"What is the difference between GC.class_histogram with and without -all?"

Without -all the command counts only reachable objects, which means the JVM first runs a full collection so that unreachable garbage is gone, and then walks the heap.

That is the useful number for a leak, but the full GC is a pause proportional to the live set, seconds on a big heap.

With -all it walks the heap as it is, including garbage not yet collected, with no forced collection, so the pause is just the walk and the counts include dead objects.

I use -all first on a loaded instance, because it is quick and often the leaking class is obvious even with noise, and the precise live count only on an instance out of rotation.

jmap -histo and jmap -histo:live are the same pair with the same trap.

Q122. "What is a safepoint, who needs one, what is time-to-safepoint, and why does it make some profilers lie?"

Reveal answer

Strong answer A safepoint is a moment when every Java thread is stopped at a place where the JVM knows exactly which registers and stack slots hold object references.

The JVM needs that certainty before it can do anything that moves or inspects objects on behalf of all threads: a stop-the-world garbage collection phase, a heap dump or class histogram, class redefinition by an agent, revoking a compiled method through deoptimisation, and a full thread dump.

Compiled code cooperates by containing safepoint polls, which are cheap loads from a special page at method returns and at loop back-edges; when the JVM wants a safepoint it makes that page unreadable, each thread faults at its next poll and parks.

Interpreted code checks at every bytecode, and threads in native code are considered already safe.

Time-to-safepoint is the gap between the JVM asking and the last thread arriving, and it is the hidden part of a pause: GC logs report only the work done once everyone has stopped.

-Xlog:safepoint prints both, in lines such as Safepoint "G1CollectForAllocation", Time since last: 1200 ms, Reaching safepoint: 280 ms, At safepoint: 5 ms, Total: 285 ms, and a large "Reaching safepoint" number means one thread was slow to poll.

The usual slow thread is in a long counted loop; since JDK 10 the C2 compiler applies loop strip mining, controlled by -XX:+UseCountedLoopSafepoints and -XX:LoopStripMiningIter=1000, which inserts a poll every thousand iterations, but a huge System.arraycopy or a long JNI call without polls can still delay everyone.

Since JDK 10, JEP 312 thread-local handshakes let the JVM ask one thread to do something at its next poll without stopping all threads, which is how many operations such as biased-lock revocation and single-thread stack sampling avoid a global safepoint.

Profilers lie because of the same mechanism: a sampler that obtains stacks through the JVM's thread-dump machinery only sees a thread when it reaches a poll, so it reports the location of the nearest poll, typically the end of a loop or a method exit, rather than the instruction that was hot.

That is safepoint bias, and it is why jstack-style samplers and older tools systematically blame the wrong line.

Land it A pause is time-to-safepoint plus time at safepoint, and only the second half is in the GC log, so I always read -Xlog:safepoint next to it.

Likely follow-ups
"How would you find which thread is delaying the safepoint?"

I would enable -XX:+SafepointTimeout -XX:SafepointTimeoutDelay=100. When a safepoint takes longer than 100 ms to reach, the JVM prints the names and states of the threads that have not yet arrived, which is usually one thread with a state like "in Java code" that identifies the loop.

On a diagnostic build I can add -Xlog:safepoint*=debug for more detail. Then I take a JFR recording and look at jdk.SafepointBegin events next to jdk.ExecutionSample for that thread in the milliseconds before the safepoint, which shows the method it was in.

In practice the culprits are a loop over a large primitive array with the counter typed as long, which older JDKs did not treat as a counted loop, a giant arraycopy or Arrays.fill, or a JNI function that pins an array with GetPrimitiveArrayCritical.

"Does JFR have safepoint bias?"

Mostly not. JFR's jdk.ExecutionSample sampler thread suspends a target thread and walks its stack from wherever it stopped, using the compiler's debug information to interpret the frame, so it does not wait for a poll.

JDK 25's JEP 518, cooperative sampling, changed the mechanics: the sampler now records the thread's program counter and stack pointer and the target thread itself walks and records its stack at its next safepoint poll.

The location captured is still the real one, so the bias does not return; what changed is that the expensive part of the walk moved onto the sampled thread, which makes the sampler safer and cheaper in processes with many threads.

async-profiler in cpu mode is also free of the bias. Anything that calls Thread.getAllStackTraces or jstack in a loop is fully biased and also causes safepoints of its own.

"What is a guaranteed safepoint, and why would a completely idle JVM still pause?"

HotSpot forces a safepoint at a regular interval, one second by default through GuaranteedSafepointInterval, which is a diagnostic flag on recent JDKs, so that housekeeping such as cleaning inline caches, sweeping the code cache and processing deferred handshakes gets a chance to run even when nothing else requests one.

On an idle JVM those safepoints take microseconds. They matter in two cases: on a latency-critical service where even a 100-microsecond global stop every second is visible, and when a lot of "no-op" safepoints appear in -Xlog:safepoint and someone mistakes them for a problem.

They can be disabled by setting the interval to zero after unlocking diagnostic options, but I would only do that on a system that has already removed every other source of jitter.

Q123 · Scenario. "Users see 300 ms stalls. The GC log shows every pause under 5 ms. The team says it cannot be the JVM. Convince me either way."

Reveal answer

Strong answer I would not accept "not the JVM" from the GC log alone, and I would go in this order:

  1. Symptom: application-level stalls much larger than any GC pause. Three families can produce that: the pause is real but the GC log only shows part of it; the JVM is stopped for a reason other than GC; or the operating system stopped the process.
  2. Evidence: first -Xlog:safepoint, because the GC log's 5 ms is "At safepoint" and the 300 ms may be "Reaching safepoint" on the same line. Then -Xlog:gc+cpu, which prints user, system and real time per pause; a pause whose real time far exceeds user plus system was stalled by the OS, not doing work. Then a JFR recording covering a stall, filtered on jdk.SafepointBegin, jdk.ExecutionSample and jdk.ThreadCPULoad. On the host: /sys/fs/cgroup/cpu.stat for nr_throttled, /proc/vmstat for compact_stall and thp_fault_fallback, and vmstat 1 for swap activity.
  3. Ranked causes. First, long time-to-safepoint: a thread in a tight counted loop over a huge array, a large System.arraycopy or a JNI call holding a critical array, keeping every other thread waiting for it before a 5 ms collection can even start. Second, non-GC safepoints: a monitoring agent calling Thread.getAllStackTraces every second, a heap histogram from a dashboard, class redefinition by an instrumentation agent, or a burst of deoptimisations; these appear in -Xlog:safepoint with names like ThreadDump or Deoptimize and never in the GC log. Third, OS stalls: transparent huge page compaction, swap-in of heap pages, CFS quota throttling in a container, or a noisy neighbour, all of which show as real time much larger than CPU time.
  4. Fix, per cause: for time-to-safepoint, restructure the loop or split the array copy, confirm -XX:+UseCountedLoopSafepoints is in effect, and move heavy JNI work off request threads; for agent safepoints, remove the polling agent or lower its rate; for OS stalls, set THP to madvise, disable swap, and fix CPU limits.
  5. Prevention: -Xlog:safepoint and -Xlog:gc+cpu always on alongside -Xlog:gc*, and a dashboard panel for total safepoint time per minute, not just GC time.

Land it The GC log measures only the work after everyone stopped, so a 300 ms stall with 5 ms collections tells me to look at who was slow to stop and whether the kernel stopped us first.

Likely follow-ups
"-Xlog:safepoint shows nothing above 10 ms and the OS counters are clean. The stalls continue. What next?"

Then the process was never stopped and the stall is inside the application.

I would switch to async-profiler in wall mode for the request threads, because wall mode shows where a thread waited: a lock held by a background task, a blocking call to a slow dependency, a synchronized block during class initialisation, or a connection pool checkout.

JFR's jdk.JavaMonitorEnter and jdk.ThreadPark events with a 20 ms threshold give the same picture with the lock owner named. I would also check jdk.VirtualThreadPinned if virtual threads are used, because a pinned carrier can hold a request for hundreds of milliseconds.

If there is no wait either, then the request really took 300 ms of CPU somewhere and a CPU profile aligned to a slow request trace answers it.

"Why would an APM or monitoring agent cause safepoints, and how would you prove it?"

Several agents build thread state dashboards by calling ThreadMXBean.dumpAllThreads or Thread.getAllStackTraces on a timer.

Each call needs a global safepoint so it can walk every stack consistently, and on a service with 2,000 threads and deep stacks that walk takes tens to hundreds of milliseconds, during which no request thread runs.

Some also request class histograms or use JVMTI features that force safepoints. To prove it, -Xlog:safepoint shows a periodic safepoint named ThreadDump or GetAllStackTraces with a large "At safepoint" time, at exactly the agent's interval.

The experiment is to start one instance with -javaagent removed and compare. The fix is to use the agent's sampling mode based on JFR or async-profiler, or to lower the interval to something like once a minute.

"What in the JVM gets slower when the kernel does transparent huge page compaction, and why does it look like a JVM pause?"

With THP set to always, the kernel tries to back every anonymous memory region, including the Java heap, with 2 MB pages.

When it cannot find a free contiguous 2 MB block, a page fault can trigger synchronous compaction: the faulting thread is put to sleep while the kernel shuffles physical pages to make room.

That thread can be a request thread touching a new part of the heap, or a GC thread touching a region during a collection, so the wall-clock pause grows while CPU time does not.

The JVM has no idea it happened; -Xlog:gc+cpu just shows real time much larger than user plus system. /proc/vmstat counters compact_stall and thp_fault_alloc rising during a stall confirm it.

The usual fix is madvise mode and, if huge pages are wanted, -XX:+UseTransparentHugePages with -XX:+AlwaysPreTouch so the faults happen at startup.

Q124 · Scenario. "The first attempt to take a heap dump got the pod OOM-killed. The second attempt worked but stopped the service for four minutes. We still need the leak. What now?"

Reveal answer

Strong answer I would proceed in this order:

  1. Symptom: the diagnostic is more dangerous than the disease. A heap dump writes about one byte per byte of used heap and stops every thread for the duration, so on a 24 GB heap it is a 24 GB file and minutes of stop-the-world. The OOM kill on the first attempt came from the container's memory limit: the dump touched every heap page, forcing lazily committed or swapped-out pages to become resident, and the file's dirty page cache was charged to the same cgroup, which pushed the pod over its limit.
  2. Evidence: kubectl describe pod shows the kill reason and the limit; jcmd <pid> GC.heap_info gives the used heap, which predicts the dump size; the earlier dump's duration in -Xlog:safepoint as a HeapDumper safepoint confirms the four minutes were the write to a slow volume.
  3. Ranked ways to get the answer without repeating the damage. First, cheap evidence: jcmd <pid> GC.class_histogram -all takes seconds and tells me which class is growing; run it twice an hour apart and diff the counts. Second, JFR with jcmd <pid> JFR.start settings=profile path-to-gc-roots=true duration=15m and then jfr print --events jdk.OldObjectSample, which samples long-lived objects and records the reference chain that keeps them alive, with no pause. Third, if a full dump is still required, take it from a canary: one instance removed from the load balancer, with a raised memory limit for that pod, dumping with GC.heap_dump -gz=1 -parallel=4 /dumps/x.hprof to a local disk volume, so it is compressed, faster, and the pause harms nobody.
  4. Fix for the leak itself follows from what those show, typically a static map or a listener list; the fix for the diagnostic is -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps on a volume, because a dump taken as the process dies costs no availability.
  5. Prevention: size the pod's memory limit for heap plus native plus a dump-sized allowance, or accept that dumps only ever happen on canaries; keep continuous JFR on so the OldObjectSample evidence is already there next time.

Land it A heap dump is the definitive evidence and the most expensive one, so I collect the cheap evidence first and take the dump only on an instance that is already out of service.

Likely follow-ups
"The class histogram shows byte[] growing and OldObjectSample samples nothing useful. What next?"

byte[] alone is not an answer, because everything from strings to buffers is a byte array underneath.

I would look at the second and third rows of the histogram for the owning class, for example java.nio.HeapByteBuffer or a framework's buffer class, and at the JFR allocation events, jfr view allocation-by-site, to see who allocates large byte arrays.

If OldObjectSample caught nothing, I would raise its sampling with a custom settings file, jdk.OldObjectSample#cutoff=0ms and a longer recording, because it samples by allocation and a few large arrays are easy to miss.

If that still fails, I would also check that the growth is on the heap at all: a growing RSS with a stable heap points at direct buffers, which jcmd <pid> VM.native_memory summary shows under "Other" or "Internal", and then the dump would never have shown the leak.

"Why does the dump make the process use more memory when the data is already in the heap?"

Three reasons. The heap is reserved up front but pages are committed and physically touched only as objects are allocated into them; a dump walks every region including ones that were uncommitted or never touched, so resident memory rises to the full heap size.

If any heap pages were swapped out, they come back in.

And the dump file itself is written through the kernel's page cache, and in a cgroup the dirty page cache counts against the container's memory limit until it is written back to disk; on a slow volume the dirty pages pile up faster than they drain.

The combination can exceed the limit by gigabytes. Writing with -gz=1 shrinks the file and the page cache pressure, and a fast local volume drains it quickly; raising the limit on the canary pod removes the risk entirely.

"How would you analyse a 24 GB dump once you have it?"

Not on a laptop.

I would run Eclipse Memory Analyzer's headless parser, ParseHeapDump.sh x.hprof org.eclipse.mat.api:suspects, on a machine with at least the dump size in RAM and -Xmx set accordingly in MemoryAnalyzer.ini, which produces the index files and a Leak Suspects report as a zipped HTML page.

The report usually names one dominator, meaning an object whose removal would free the most memory, with its retained size and the shortest path to a GC root.

If I need more, I open the indexes in the GUI and use the dominator tree sorted by retained heap and "Path to GC Roots, exclude all phantom, weak and soft references", so cache references do not confuse the picture. I keep the indexes, because re-parsing takes an hour.

Drill · Startup, native image, reflection & serialization

This group tests whether you know where a JVM's first seconds go, which of the new ahead-of-time tools actually helps in each case, and where reflection and serialization cost you performance or safety.

Q125. "Where does JVM startup time actually go, and what do CDS, AppCDS and the Leyden AOT cache each do about it?"

Reveal answer

The real test Whether you can separate the phases of startup and match each tool to the phase it shortens, with the flags, rather than saying "AOT makes it faster".

Strong answer Startup has four layers. The JVM itself initialises in around 40 milliseconds.

Then classes are loaded, meaning found, parsed and verified, and linked, meaning their constant pool references are resolved; a Spring service loads 10,000 to 20,000 classes and this is hundreds of milliseconds to seconds.

Then the application's own initialisation runs in the interpreter, because nothing is hot yet, and a framework that scans the classpath and calls thousands of methods reflectively is slow in interpreted mode.

Finally the JIT, the just-in-time compiler, warms up over the first minutes, so early requests are slow even after "started".

Class data sharing, CDS, attacks the second layer: the JDK ships an archive of its own core classes already parsed and verified, mapped into memory at start, enabled by default since JDK 12.

AppCDS extends the archive to application classes: run once with -XX:ArchiveClassesAtExit=app.jsa, then start with -XX:SharedArchiveFile=app.jsa; since JDK 19 -XX:+AutoCreateSharedArchive -XX:SharedArchiveFile=app.jsa does both on the first run. Typical gain is 10 to 30 percent of startup.

The Leyden AOT cache, JEP 483 in JDK 24, goes further: it also records which classes were linked and, for lambdas and method handles, the generated classes and resolved call sites. A training run with -XX:AOTMode=record -XX:AOTConfiguration=app.aotconf, then -XX:AOTMode=create -XX:AOTCache=app.aot, then production runs with -XX:AOTCache=app.aot.

JDK 25's JEP 514 collapses that to one training run with -XX:AOTCacheOutput=app.aot, and JEP 515 adds method profiles so the JIT starts with knowledge of what was hot, shortening the fourth layer.

JDK 26's JEP 516 removed the restriction that the cache only worked with G1 or Serial. The JEP quoted a Spring PetClinic startup going from about 4 seconds to about 2.3 seconds.

CRaC is a different idea: checkpoint a fully warmed process to disk and restore it in tens of milliseconds, at the cost of a build that supports it and code that closes files and sockets around the checkpoint.

In containers all of this is dwarfed by a 1-CPU limit, which starves both class loading and the JIT.

Land it CDS saves parsing, the AOT cache saves parsing plus linking plus part of warm-up, CRaC skips startup entirely, and none of them helps if the container has one CPU.

Likely follow-ups
"What can make an AOT cache or CDS archive silently unused, and how would you detect it?"

The archive is validated against the JVM it was made with and the classpath it saw.

A different JDK build, a changed jar order, a jar whose modification time changed, a different --module-path, or different GC and compressed-oops settings all cause the JVM to ignore the archive and load classes the slow way, with only a warning if -Xshare:on or -XX:AOTMode=on is set; the default is auto, which is silent.

I detect it with -Xlog:cds or -Xlog:aot at startup, which prints whether the archive mapped and why not, and with jcmd <pid> VM.info, which reports the shared archive state.

In a container image I build the archive in the same image build stage, with the exact final classpath, and I set -XX:AOTMode=on in staging so a mismatch fails loudly before production.

"How does the training run work, and what goes wrong if the training workload is unrepresentative?"

The training run is a normal execution of the application with recording enabled. The JVM notes every class loaded and linked, every lambda call site bootstrapped and, with JEP 515 in JDK 25, the JIT's method profiles, then writes the cache at exit.

Anything not exercised is not in the cache, so a training run that only starts and stops the application caches startup but not the request path; a training run that replays a few hundred representative requests caches the hot call sites too.

If the workload is unrepresentative, nothing breaks, because the cache is only a shortcut; the classes it did not see load normally and the profile it recorded is simply replaced by live profiling. The cost is lost benefit, not correctness.

I make the training run part of the image build with a small replay of recorded traffic.

"When would you pick CRaC over the AOT cache?"

When the requirement is restore in well under a second with fully compiled code, for example scale-to-zero functions or a fleet that must add capacity in seconds.

CRaC checkpoints the whole process image after warm-up, so restore skips class loading, initialisation and JIT warm-up together, and I have seen restores in 50 to 200 milliseconds.

The price is real: a JDK build with CRaC support, application and library code that implements the Resource callbacks to close sockets, files and pools before checkpoint and reopen them after, the danger of secrets and random seeds frozen into the image, and a checkpoint that is tied to a CPU model.

The AOT cache costs almost nothing to adopt and gives roughly a halving of startup. So I start with the AOT cache and only pay for CRaC when the numbers demand it.

Q126 · Scenario. "A Spring Boot service starts in 8 seconds on a laptop and 40 seconds in Kubernetes, and the readiness probe keeps restarting it. Diagnose it."

Reveal answer

Strong answer I would go in this order:

  1. Symptom: a five-fold startup slowdown that only appears under the orchestrator, plus a probe that kills the process before it finishes, which turns a slow start into an outage loop.
  2. Evidence: the pod's CPU limit and request from the deployment spec; jcmd <pid> VM.info or a one-line Runtime.getRuntime().availableProcessors() printed at boot, which shows what the JVM believes it has; /sys/fs/cgroup/cpu.stat inside the pod for nr_throttled; and a JFR startup recording with -XX:StartFlightRecording:filename=start.jfr,settings=profile,dumponexit=true read with jfr view hot-methods. -Xlog:class+load:file=/tmp/cl.log tells me how many classes load and how long that takes.
  3. Ranked causes. First, a CPU limit of one core or less: startup is the most CPU-hungry phase of a JVM's life, with class loading, verification, the interpreter and the JIT compiler threads all competing, and a 1-CPU quota with the default 100 ms CFS period throttles them; the laptop has 8 to 16 cores. With one available processor the JVM also picks Serial GC and a smaller code cache and fewer compiler threads, all of which slow warm-up further. Second, the readiness probe's initialDelaySeconds is set for the laptop number, so the pod is killed at 30 seconds and restarts forever. Third, slower storage or network: the classpath is on an overlay filesystem, and Spring's startup does DNS, config-server and database calls that take longer in the cluster. Fourth, more classes: profiles and auto-configurations that only activate in the cluster.
  4. Fix: raise the CPU limit for startup, or remove it and keep only a request, since CPU limits are the one resource where over-committing at start is usually harmless; set -XX:ActiveProcessorCount=2 or more if the limit must stay so JIT and GC threads are sized sensibly; make the readiness probe a startup probe with a generous failureThreshold; add an AppCDS archive or a Leyden AOT cache built in the image; enable lazy initialisation with spring.main.lazy-initialization=true where safe.
  5. Prevention: a startup-time budget checked in the deployment pipeline against the real pod spec, not a laptop.

Land it The laptop is measuring a different machine; the fix is CPU for the startup phase and a probe that waits for the real number, with AOT caching to make the real number smaller.

Likely follow-ups
"You raised the CPU limit to 4 and startup is still 25 seconds. What next?"

Then CPU was part of it but not all of it, and I stop guessing and read the startup recording.

jfr view hot-methods start.jfr and the thread view show where the main thread spent its 25 seconds: if it is in socket reads, the cluster's dependencies are slow, for example a config server, a database migration or DNS resolution with a search domain that retries; if it is in class loading and reflection, the fix is the AOT cache and trimming auto-configuration; if it is in a single bean's constructor, that bean is doing work that belongs in a background thread.

I would also compare -Xlog:class+load counts between laptop and pod; a profile that loads 5,000 more classes explains a lot. Finally I would check the JIT is not disabled by an old -Xint or a tiny -XX:ReservedCodeCacheSize in the container's environment.

"Why is a CPU limit worse than a CPU request for a JVM, and what does -XX:ActiveProcessorCount change?"

A request is a scheduling weight: the pod gets at least that share when the node is busy and can use idle CPU otherwise.

A limit is a hard quota enforced by the kernel's completely fair scheduler in 100 ms periods: with a limit of 1, once the pod's threads have used 100 ms of CPU in a period, all of them are stopped until the next period starts.

A JVM starting up has a dozen threads that want CPU at the same time, so it burns its quota in the first 20 ms of every period and idles for 80.

-XX:ActiveProcessorCount=n overrides what the JVM reports as available processors, which sizes the compiler thread count, the GC thread count, the common pool and the virtual-thread scheduler.

It does not give the process more CPU; it only stops the JVM from configuring itself as a single-core machine when the limit is fractional.

"Would GraalVM native image fix this instead?"

It would start in well under a second regardless of the CPU limit, because there is no class loading, no interpreter and no JIT; everything was compiled ahead of time.

But it changes the trade-off rather than removing it: build times of several minutes, reachability metadata for every reflective access the framework needs, lower peak throughput unless profile-guided optimisation is used, and a different debugging and profiling toolchain.

For a Spring Boot service that runs for days, the peak throughput and the operational tooling matter more than the first seconds, and the AOT cache with a sane CPU limit already gets startup to a few seconds.

I would pick native image for short-lived processes, command-line tools and functions, not as the fix for a probe misconfiguration.

Q127 · Design. "We have 40 command-line tools and 200 long-running services on the JVM. Design the decision of which get GraalVM native image and which get the JDK's AOT cache, and defend the trade-offs."

Reveal answer

Strong answer Requirements and assumptions: the tools are invoked thousands of times a day and each run lasts under a second, so their cost is almost entirely startup; the services run for days, so their cost is peak throughput, memory and how easily we can diagnose them.

Design: the tools get native image; the services get the JDK's AOT cache.

The mechanism behind the choice: native image compiles the whole program ahead of time under a closed-world assumption, meaning every class that can ever be used must be known at build time, so it starts in tens of milliseconds with a small resident footprint, which is exactly what a short-lived tool wants.

The costs are a build of several minutes per tool, reachability metadata for every reflective access, resource and proxy, which the tracing agent -agentlib:native-image-agent=config-output-dir=… can record from test runs, and a peak throughput below HotSpot unless profile-guided optimisation, available in Oracle GraalVM, is used; Community builds default to Serial GC. For the services those costs buy little: after a minute HotSpot's JIT produces faster code than the ahead-of-time compiler, G1 or ZGC handle large heaps better than native image's collectors, and JFR, async-profiler, heap dumps, agents and hot class redefinition all just work.

The AOT cache, -XX:AOTCacheOutput=app.aot in a training run at image build and -XX:AOTCache=app.aot at runtime, cuts their startup roughly in half without changing the program, its build or its tooling.

Trade-offs I would state: the tools now have a separate build pipeline and a slower feedback loop, and any tool that uses dynamic plugins or heavy reflection may need a JVM fallback; the services keep a few seconds of startup, which we accept because they are replaced gradually, never all at once.

What I would not do: I would not native-image the services to save a few seconds of startup and lose 20 percent of peak throughput and my profiling toolchain, and I would not use CRaC for the tools, because a checkpoint per tool version is more operational surface than a static binary.

Land it Native image is for processes that spend their life starting; the AOT cache is for processes that spend their life running; the choice is about where the process spends its time.

Likely follow-ups
"Requirement change: the services must scale from zero to serving in under two seconds. Does the answer change?"

It changes for the services that actually scale to zero. Two seconds is below what the AOT cache reliably gives a framework-heavy service on a small CPU limit.

The candidates are then CRaC, which restores a warmed process in a few hundred milliseconds and keeps HotSpot's peak throughput and tooling, and native image with profile-guided optimisation.

I would choose CRaC if the platform can support the checkpoint files and the code can be made checkpoint-safe, and native image if the services are small and reflection-light, such as Quarkus or Micronaut-style services built for it.

For the services that do not scale to zero, nothing changes. I would also push back on the requirement: keeping one warm instance is usually cheaper than re-engineering 200 services.

"Under time pressure, what would you cut?"

I would cut native image entirely for the first release and give the tools the AOT cache too.

Their startup drops from perhaps 800 milliseconds to 400, which is a visible win for one flag and no new build pipeline, and the reachability metadata work, which is where native image projects lose weeks, is deferred.

I would keep the training-run step in the image build for the services, because it is a few lines of Dockerfile. I would also cut profile-guided optimisation from any native image plan, since it needs the commercial distribution and a second build stage.

The thing I would not cut is measuring startup on the real pod spec, because without that number the whole decision is a guess.

"What exactly breaks under the closed-world assumption, and how do you find it before production?"

Anything decided at runtime that the build could not see: Class.forName on a name read from configuration, reflection on a class the analysis did not reach, a resource loaded by name, a java.lang.reflect.Proxy for an interface, JNI or serialisation of a class not registered, and dynamic class generation such as ByteBuddy or CGLIB proxies.

At runtime these fail with a ClassNotFoundException or a missing-metadata error rather than at build time.

I find them by running the test suite and a traffic replay under the tracing agent, which writes reachability-metadata.json, by using framework support that generates the metadata at build time, and by a staging soak with the native binary.

The residual risk is a code path no test exercised, which is why tools with plugin systems stay on the JVM.

Q128. "Why is Java serialization dangerous for untrusted input, and what does the JDK give you to make it safe if you cannot remove it?"

Reveal answer

Strong answer ObjectInputStream.readObject instantiates whatever classes the byte stream names, as long as they are on the classpath and implement Serializable, and it runs their readObject, readResolve and, later, hashCode and equals methods during deserialisation.

An attacker who controls the bytes can chain such methods from ordinary library classes into a gadget chain, a sequence of innocent-looking calls that ends in something like Runtime.exec; well-known chains exist for Commons Collections, Spring and even parts of the JDK, and tools like ysoserial generate them.

So the rule is: never deserialise untrusted input with Java serialization, and prefer JSON or protocol buffers with explicit schemas. When it cannot be removed, for example in RMI, JMX or an old message format, the JDK's defence is JEP 290 from JDK 9: java.io.ObjectInputFilter.

A filter sees each class about to be created plus the depth, the number of references, the array length and the stream size, and answers allow, reject or undecided.

It can be set process-wide with -Djdk.serialFilter='maxdepth=10;maxrefs=1000;maxbytes=500000;maxarray=10000;com.acme.model.**;java.base/*;!*', where ** matches a package and its sub-packages, * only one package, a module prefix restricts by module, and the final !* rejects everything not explicitly allowed.

JEP 415 in JDK 17 added filter factories: ObjectInputFilter.Config.setSerialFilterFactory, or -Djdk.serialFilterFactory=, lets me combine the global filter with a per-stream filter, and the helpers ObjectInputFilter.allowFilter, rejectFilter and rejectUndecidedClass make the allow-list approach easy.

Decisions can be logged with the java.io.serialization logger at FINER, which is how I build the allow-list from real traffic.

Records deserialise differently and more safely: a record's fields are read and then its canonical constructor is called, so its invariants are enforced and there is no readObject hook to abuse.

Land it The safe filter is a short allow-list ending in !*, and the safer design is to not read serialized objects from anyone I do not trust.

Likely follow-ups
"Why is an allow-list better than blocking the known gadget classes?"

Because the set of gadget classes is open.

A deny-list has to name every dangerous class in every library on the classpath, including ones added by a dependency upgrade next month, and researchers publish new chains every year; the JDK's own deny-list in java.security for RMI exists but is a floor, not a ceiling.

An allow-list names the twenty classes my protocol actually needs and rejects everything else, so a new gadget in a new library is rejected by default without anyone knowing it exists.

The limits matter too: maxdepth and maxrefs stop denial-of-service payloads such as deeply nested collections or a HashSet of HashSets whose hashing takes exponential time, which no class-based rule catches.

The cost is maintenance: adding a class to the protocol means adding it to the filter, which I treat as a feature of the design.

"How do the global filter and a per-stream filter combine after JEP 415?"

Before JDK 17 a stream's own filter, set with ObjectInputStream.setObjectInputFilter, simply replaced the global one.

JEP 415 introduced the filter factory, a BinaryOperator<ObjectInputFilter> that is called whenever a stream is created or its filter is set, receiving the current filter and the proposed one and returning the filter to use. The default factory keeps the old behaviour.

My own factory can return ObjectInputFilter.merge(proposed, global), so a stream may narrow the global rules but never widen them, and wrap it in rejectUndecidedClass so anything neither filter mentions is refused.

That is the pattern for a shared library: the platform sets a strict global filter and factory at startup, and each endpoint supplies the small allow-list for its message types.

"What would you replace Java serialization with in an internal RPC, and what do you lose?"

For a schema-driven internal protocol I would choose protocol buffers or a similar binary format with generated classes, because the parser only knows how to build the messages in the schema and cannot instantiate arbitrary classes, and because the format is stable across languages and versions.

For loosely structured data I would use JSON with a binding library configured to refuse polymorphic type information from the wire, since "default typing" in JSON libraries recreates the same gadget problem.

What I lose is the convenience of serialising any object graph, including cycles and references, without writing a schema; Java serialization handles a graph of objects pointing at each other automatically, and most replacements need a tree.

I also lose serialVersionUID-style versioning and gain explicit schema evolution instead, which in practice is a better trade.

Q129 · Scenario. "The JVM crashed and left an hs_err_pid file. Walk me through reading it, what you conclude, and what you collect for the bug report."

Reveal answer

Strong answer I read it top down, in this order:

  1. Symptom: a hard crash of the process, as opposed to an exception, which means either native code touched memory it should not, the JVM hit an internal assertion, or the operating system killed it. The header says which: SIGSEGV is a bad memory access, SIGBUS often a mapped-file problem, SIGFPE division in native code, and an "Internal Error" with a source file and line is the JVM's own guard failing. If there is no hs_err file at all and dmesg says "Killed process", it was the kernel's OOM killer, which is not a crash.
  2. Evidence in the file: the "Problematic frame" line, whose first letter says what kind of code was running: J for JIT-compiled Java with the method name, j for interpreted Java, V for the JVM's own C++ code with a symbol, and C for native library code, followed by the library name. Then the "Current thread" block with its name and stack, the registers, which show whether a pointer was null or garbage, the "VM_Operation" line if a safepoint operation was in progress, the memory map to see which library the crashing address belonged to, the heap summary to rule out exhaustion, the flag list, and the "Events" ring buffer of the last internal events such as deoptimisations and GC starts.
  3. Ranked causes by frame letter. A C frame in a third-party .so, or in libc called from JNI or the foreign function API, is the most common cause: a bad pointer handed to native code, a freed buffer, or a MemorySegment used after its arena closed. A J or V frame with a repeatable crash in one method suggests a JIT bug, which I confirm by excluding the method with -XX:CompileCommand=exclude,com.acme.Foo::bar and seeing the crash vanish. A V frame inside a GC function on many different hosts suggests a JVM bug; the same on one host suggests bad memory, which a hardware log or memtester confirms.
  4. Fix: for native code, fix the pointer handling or pin the library version; for a JIT bug, exclude the method and upgrade the JDK update release; for hardware, replace the node.
  5. Prevention: pin -XX:ErrorFile=/dumps/hs_err_%p.log to a persistent volume, keep -XX:+CreateCoredumpOnCrash with a core pattern that lands somewhere shippable, and collect for the report the hs_err file, the core, the exact JDK build string, the GC log and the last minutes of application log.

Land it The problematic frame's letter tells me whose bug it probably is, and the reproduction test with CompileCommand=exclude tells me whether the JIT is involved before I blame anyone.

Likely follow-ups
"You excluded the method and it still crashes, in the same J frame. What next?"

Then the compiled method is where the crash surfaces, not where it originates: some other code corrupted memory that this method later touched, which is typical of a native library writing past a buffer or of an Unsafe user computing a wrong offset.

I would look at the registers and the faulting address in the header; an address just past a known array or a pattern like 0xdeadbeef-style poisoned values points at heap corruption.

I would run with -XX:+UnlockDiagnosticVMOptions -XX:+VerifyBeforeGC -XX:+VerifyAfterGC on a test instance, which checks heap integrity at each collection and fails closer to the corrupting write.

I would review every JNI, FFM and Unsafe use on the crashing thread's stack, and try running with the native libraries swapped for pure-Java alternatives one at a time.

"What is in the memory map and heap summary sections, and when have they been the answer?"

The memory map lists every mapped region of the process: the heap, the code cache, each thread stack, every loaded .so with its address range, and mapped files.

Its value is matching the crashing address to a region: an address inside a library named by nobody in the stack shows which library really owned the code, and an address inside a thread stack's guard page means a stack overflow in native code, which shows as SIGSEGV rather than StackOverflowError.

The heap summary shows each generation's capacity and use, plus metaspace; a crash with metaspace at its limit, or with the code cache full, has been the answer when a class-loading or compilation path hit an unexpected allocation failure.

The flag list next to it has caught more than one crash caused by a forgotten experimental flag.

"How would you tell a JVM crash from an OOM kill, and why does the distinction change everything?"

The OOM killer sends SIGKILL, which cannot be caught, so the JVM writes nothing; there is no hs_err file, the container's last state says OOMKilled with exit code 137, and dmesg on the node records "Memory cgroup out of memory: Killed process".

A JVM crash leaves the hs_err file and usually exit code 134 from SIGABRT.

The distinction matters because the fixes are unrelated: an OOM kill is a sizing problem, the container limit is below heap plus native memory, fixed with -XX:MaxRAMPercentage, native memory tracking and a bigger limit; a crash is a code defect in native code, the JIT or hardware.

Teams that see exit code 137 and go hunting for a JIT bug lose days.

Q130 · Design. "Design how a framework of ours should do dependency injection, proxies and mapping code: reflection at runtime, method handles, generated code at build time, or something else. Justify each with cost."

Reveal answer

Strong answer Requirements and assumptions: the framework wires a few thousand beans at startup, intercepts a few hundred methods for transactions and metrics, and maps objects between layers on hot request paths; it must work on the AOT cache and ideally on native image.

Design in three parts.

Wiring is a startup cost, so I choose build time: an annotation processor, the same mechanism MapStruct and Micronaut use, generates the factory classes during compilation, so at runtime there is no classpath scanning and no Constructor.newInstance, and the closed-world tools see plain code.

Interception needs proxies; for interfaces I use java.lang.reflect.Proxy, which generates a class at runtime whose methods call an InvocationHandler, and for classes I generate a subclass at build time, since runtime subclassing with ByteBuddy or CGLIB is what breaks native image and forces every intercepted class to be non-final with an accessible constructor.

Where a proxy must be created at runtime, I define it as a hidden class via MethodHandles.Lookup.defineHiddenClass, which is unloadable and invisible to Class.forName.

Mapping on the hot path is generated code, full stop, because a generated toDto is a normal method the JIT inlines, while reflective field copying is 10 to 50 times slower and defeats escape analysis.

Where I do need runtime invocation, I use java.lang.invoke.MethodHandle obtained once and stored in a static final field, which the JIT can inline like a direct call; since JDK 18, JEP 416, Method.invoke is itself implemented on method handles, so its cost is close to a handle after warm-up, but a handle in a constant field is still the fastest and is what frameworks should hold.

Trade-offs: annotation processors mean a compile step, generated sources to debug, and processors that must be ordered correctly next to Lombok; build-time proxies cannot intercept classes the framework did not see at build time.

What I would not do: I would not scan the classpath at startup, and I would not write class files by hand; since JDK 24 the Class-File API, JEP 484, is the supported way to generate bytecode when generation is unavoidable.

Land it Everything that can be decided at build time is generated, everything that must be decided at runtime is a method handle in a constant field, and reflection is only what is left.

Likely follow-ups
"Requirement change: plugins are loaded at runtime from jars we do not compile. What changes?"

The build-time generation no longer covers the plugins, so I need a runtime path for them only. For wiring, I would read the plugin's constructor with reflection once, convert it with MethodHandles.publicLookup().unreflectConstructor, and cache the handle; that is a one-time cost per class.

For interception I would use Proxy where the plugin exposes interfaces, and refuse to intercept concrete classes rather than pulling in a runtime subclassing library.

For bytecode generation I would use the Class-File API to emit the adapter classes and define them as hidden classes in the plugin's loader, so unloading a plugin releases them.

Native image is then off the table for the host, which is a stated consequence, and the AOT cache still helps for everything except the plugins.

"Under time pressure, what would you cut?"

I would cut build-time proxies and use java.lang.reflect.Proxy everywhere, requiring intercepted beans to expose an interface, because that removes a whole code generator and interface-based proxies are what the JDK supports directly.

I would keep the annotation processor for wiring and mapping, because it is the part that makes both startup and the hot path fast, and generating a factory is the simplest of the three generators. I would drop hidden-class support and the Class-File API work entirely.

I would not cut the method-handle caching rule, because it is one helper class and it is the difference between reflection that is fine and reflection that shows up in a profile.

"What did JEP 416 change about Method.invoke, and does it mean reflection is now free?"

Before JDK 18, Method.invoke went through a native call for the first fifteen invocations and then generated a bytecode accessor class per method, a mechanism with two implementations and its own set of bugs.

JEP 416 replaced both with method handles: the Method object holds a handle, and invoke calls it. The result is one implementation, fewer generated classes and, after JIT warm-up, performance close to a direct handle call. It is not free.

Each call still boxes primitive arguments into an Object[], checks access, and wraps exceptions in InvocationTargetException, and because the handle is not in a constant field the JIT cannot inline through it.

A MethodHandle in a static final field, with an exact invokeExact signature, is what the JIT can turn into a direct call.

"Lombok and MapStruct in the same build keep breaking. Why, and what is the rule?"

Both are annotation processors, and MapStruct generates mappers from the getters and setters of the classes it maps, while Lombok generates those getters and setters.

Annotation processing runs in rounds, and if MapStruct's round sees the class before Lombok has added the accessors, the generated mapper is empty or fails to compile.

The rule is ordering: declare Lombok before MapStruct in the processor path, and add the lombok-mapstruct-binding processor, which exists purely to tell MapStruct to wait for Lombok.

The deeper rule for the framework design is to generate from the source the processor can see rather than from what another processor will produce, which is why I would prefer records, whose accessors exist in source, over Lombok-generated beans for anything a processor reads.

Q131 · Scenario. "We turned on -XX:+UseCompactObjectHeaders on JDK 25 to save memory. A JNI library now crashes and a serialization framework returns corrupted arrays. What happened?"

Reveal answer

Strong answer I would take it in this order:

  1. Symptom: two unrelated libraries broke at the same time as one flag changed the shape of every object. That is a strong hint that both libraries had hard-coded that shape.
  2. Evidence: the hs_err file for the JNI crash shows a C frame in the library and a faulting address inside a Java object; the corrupted arrays from the serializer are off by four bytes, which is the tell. I confirm with jcmd <pid> VM.flags that the flag is on, and I run the JOL tool, java -jar jol-cli.jar internals java.lang.Object, on the affected JDK, which prints the header size.
  3. Cause: JEP 519 made compact object headers a product feature in JDK 25, off by default. Normally an object starts with a 12-byte header, an 8-byte mark word holding the identity hash and lock state plus a 4-byte compressed class pointer, and an array's length field sits at offset 12, so the first element is at offset 16. With compact headers the class pointer moves into the mark word and the whole header is 8 bytes, so the array length is at offset 8 and the elements start at offset 12. A JNI library that computed element addresses itself, instead of asking the JVM through GetPrimitiveArrayCritical or the Get<Type>ArrayElements functions, now reads four bytes early. A serializer that copied arrays with Unsafe.copyMemory from a base offset it had hard-coded as 16, or had cached from an old JOL constants table, has the same problem in Java. Old versions of JOL itself report the wrong layout on this JDK.
  4. Fix: update the serializer to read Unsafe.arrayBaseOffset(byte[].class) or Unsafe.ARRAY_BYTE_BASE_OFFSET at runtime, or better, move it to java.lang.foreign.MemorySegment.ofArray and VarHandle access, which need no offsets at all; update or replace the JNI library so it uses the JNI array functions; until then, run with the flag off, which is the default in 25 and 26.
  5. Prevention: JDK 27, JEP 534, turns compact headers on by default as of its release candidate in Aug 2026, so every library that hard-codes offsets will break for everyone next year; I would run the test suite with the flag on now, and grep dependencies for Unsafe and JNI array arithmetic.

Land it The flag did not break anything that asked the JVM for offsets; it broke everything that assumed them, and JDK 27 will make that assumption fail by default.

Likely follow-ups
"You updated both libraries and the JNI crash is gone, but the serializer still corrupts some arrays. What next?"

Then there is a second hard-coded number somewhere.

Compact headers also change object field offsets: the first instance field of a class now sits at offset 8 instead of 12, so a serializer that cached objectFieldOffset values in a static table generated at build time, or that reads them from a configuration file, is using stale values.

I would search the library for any offset constant, any serialised layout cache on disk, and any use of Unsafe.arrayIndexScale paired with a literal base.

I would also check for a dependency that bundles its own old Unsafe helper, since shaded copies of a library do not get updated when the main one does. A -XX:+PrintFieldLayout diagnostic run on a test JVM shows the true offsets to compare against.

"What does the flag actually save, and when is it worth the risk?"

Four bytes per object.

On typical service heaps, where the average object is 30 to 40 bytes, that is 10 to 20 percent less live heap, which means fewer collections at the same heap size or a smaller heap for the same behaviour, and better cache density since more objects fit per cache line.

Oracle's numbers for JEP 519 showed around 10 percent throughput improvement on some workloads.

The cost is that the identity hash and class pointer share the mark word, so the class pointer is limited to 22 bits of compressed class space, which caps the number of loaded classes at a few million and is not a practical limit.

It is worth it once the dependency audit is clean, especially on memory-bound services, and by JDK 27 the question reverses: the risk is in turning it off and diverging from the tested default.

"How would you audit a large dependency tree for this before JDK 27?"

Three passes. First a static one: jdeps --jdk-internals over all jars lists which ones use sun.misc.Unsafe, and a bytecode search for arrayBaseOffset, objectFieldOffset and the ARRAY_ constants, which are fine, versus literal offsets like 12 or 16 passed to getInt and copyMemory, which are not.

Second, the JNI pass: list every .so in the deployable and grep the native sources or symbol tables for direct array arithmetic.

Third, the dynamic pass, which is the one that matters: the full test suite and a staging soak under -XX:+UseCompactObjectHeaders on JDK 25, with -Xcheck:jni on, which makes the JVM validate JNI calls and catches many misuses before they corrupt anything. Libraries that fail get an issue filed or a pinned upgrade.

Q132 · Design. "Design the performance-investigation runbook for our JVM fleet: what the on-call engineer does in the first five minutes, how they decide what to look at next, and what has to be in place beforehand."

Reveal answer

Strong answer Requirements and assumptions: a few hundred services on JDK 21 and 25 in containers, an on-call engineer who may not know the service, and the goal of collecting evidence before any restart destroys it.

Design, part one, what is pre-enabled on every JVM at startup, because a runbook cannot ask for evidence that was not being recorded: -Xlog:gc*,safepoint,gc+cpu:file=/var/log/gc.log:time,uptime,level,tags:filecount=5,filesize=50m; a continuous JFR ring with -XX:StartFlightRecording:disk=true,maxage=4h,maxsize=1g; -XX:NativeMemoryTracking=summary, which costs a few percent of memory and nothing measurable in CPU; -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps and -XX:ErrorFile=/dumps/hs_err_%p.log on a persistent volume; and a metrics exporter for GC pause time, heap after GC, thread count, CPU throttling and safepoint time.

Part two, the first five minutes, in a fixed order that takes under a minute of commands: triage the symptom with the USE and RED dashboards, meaning utilisation, saturation and errors for the host and rate, errors and duration for the service; then on one affected instance, jcmd <pid> VM.flags, the last 200 lines of the GC log, jcmd <pid> JFR.dump filename=/dumps/incident.jfr to capture the last four hours, three Thread.print dumps ten seconds apart, and VM.native_memory summary.

Part three, the decision tree by symptom. High CPU with normal latency: JFR hot methods. High latency with low CPU: thread dumps for blocked threads, then JFR lock and park events, then wall-clock profiling.

Rising heap after GC: class histogram, then OldObjectSample, then a canary heap dump. Rising RSS with a flat heap: native memory tracking diff, then direct buffers and thread count. Periodic stalls: safepoint log, then gc+cpu real-versus-user time, then the host's THP and throttling counters.

Part four, artefacts: everything goes to a per-incident folder in object storage with the pod spec and flags. Trade-offs: the pre-enabled logging costs a few percent of disk and around one percent of CPU, which I accept fleet-wide.

What I would not do: no jmap -histo:live or heap dumps on an instance in rotation, no restart before the JFR dump, and no flag changes during the incident except on a canary.

Land it The runbook is mostly the flags set before the incident; the five minutes are just collecting what those flags already recorded, in an order that never makes things worse.

Likely follow-ups
"Requirement change: the fleet also runs on nodes with a single shared disk and strict disk quotas. Does the always-on recording survive?"

It survives with smaller numbers. The GC log rotation drops to filecount=3,filesize=10m, which still holds days of GC events for a typical service.

The JFR ring drops to maxsize=200m; at default settings that is still an hour or more on most services, and I would rather have an hour than nothing.

Heap dumps on OOM are the real problem: a 16 GB dump on a quota'd disk fails or fills the node, so I would enable -XX:+HeapDumpOnOutOfMemoryError only on services under a size threshold and rely on OldObjectSample and class histograms for the large ones.

I would also make the incident folder an object-storage upload done by a sidecar, so nothing accumulates locally.

"Under time pressure, what would you cut from the runbook?"

I would cut native memory tracking from the always-on set, because it is the one item with a memory cost and its symptom, RSS growth without heap growth, is the rarest of the five.

I would cut the decision tree to three branches, CPU, latency and memory, and accept some wrong turns.

I would keep the GC and safepoint log, the JFR ring and the JFR dump as the very first command, because those three are what make the difference between an incident that can be analysed tomorrow and one that is a mystery forever. The metrics dashboard can be built later from the same logs.

"How do you keep the runbook from being ignored under pressure?"

By making the first five minutes one script.

A collect.sh in every image runs the fixed sequence, writes to the incident folder, and prints the three numbers that drive the decision tree: pause time in the last ten minutes, heap after the last GC, and the count of blocked threads across the three dumps.

The engineer runs one command and reads three lines. The decision tree lives next to those lines in the runbook page, with the next command for each branch already written.

I also review every incident afterwards against the runbook and add the branch that was missing, which is how the tree grew to five branches in the first place. A runbook that is only prose is a document; one that is a script is a tool.

Q133 · Design. "Design continuous profiling for 300 JVM services: how profiles are collected, stored and compared, what it costs, and what you leave out."

Reveal answer

Strong answer Requirements and assumptions: every instance should have a CPU and allocation profile available for any minute of the last month, the overhead must stay under two percent of CPU, engineers must be able to compare two versions of a service, and stack traces must not leak customer data.

Design: each JVM runs a small in-process agent.

Its default collector is JFR, started at boot with a custom settings file enabling jdk.ExecutionSample, or jdk.CPUTimeSample on JDK 25 and later, plus jdk.ObjectAllocationSample and the lock events, and the agent reads them with jdk.jfr.consumer.RecordingStream rather than shipping files.

Where native frames matter, the agent can instead run async-profiler's library in cpu mode with a 20 ms interval, which needs perf_event_paranoid at 1 or the ctimer mode in containers.

Every 60 seconds the agent folds the stacks into the collapsed text format, one line per unique stack with a count, compresses it, tags it with service, version, instance, JDK, region and CPU architecture, and uploads it to object storage.

A backend indexes by those tags and can merge any set of minute files into one flame graph, so "all instances of version 4.2 over the last hour" is a single aggregation.

Comparison is a differential flame graph between two tag sets, typically the previous version and the canary, with frames coloured by change in share.

Cost: JFR sampling at 20 ms per thread is about one percent; folding and uploading is a few milliseconds per minute; storage is roughly 50 kilobytes per instance per minute compressed, which is about 20 gigabytes per day for 300 services at 20 instances each.

Privacy: stack frames contain method names only, never arguments; the agent strips anything but class, method and line.

ARM variant: the same agent works, since JFR and async-profiler both support aarch64, but profiles are tagged by architecture and never compared across it, because inlining and intrinsics differ.

Pipeline integration: the canary stage fetches the differential against the current version and posts it on the release. Trade-offs: a per-minute resolution hides a two-second spike, which I accept because the incident JFR ring covers that case.

What I would not do: I would not ship raw JFR files from every instance, which is ten times the volume, and I would not run profile settings or wall mode continuously.

Land it The design is a stream of tiny collapsed-stack files with good tags; everything useful, aggregation, diffing and release gates, is a query over those tags.

Likely follow-ups
"Requirement change: security says no process may run with elevated perf permissions and no agent may upload directly to the internet. What changes?"

The collector becomes JFR only, which needs no kernel permissions, and on JDK 25 the jdk.CPUTimeSample event gives me CPU-proportional sampling without perf events.

I lose native frames, which I accept and document, because a JVM bug or a JNI hotspot then needs a manual async-profiler run on a canary with a one-off capability grant.

Uploads go to a node-local sidecar or a daemonset that batches files and pushes them through the platform's egress proxy, so the JVM writes only to a local directory. The tags and file format stay the same, so the backend does not change.

The overhead actually drops slightly, since JFR's sampler is cheaper than a signal-based profiler in a process with many threads.

"Under time pressure, what would you cut?"

I would cut the allocation and lock profiles and ship CPU only, because CPU answers most questions and halves the data.

I would cut the differential flame graph and the release gate, and offer only "show me this service's flame graph for this hour", because the merge-by-tags query is the core and the diff is a feature on top of it.

I would cut the ARM handling to a tag with no special treatment.

I would keep the per-minute upload cadence, the tag set and the privacy filter, because changing the file format later means throwing away history, and because a profiler that leaks arguments into storage is a security incident waiting to be found.

"How do you know the two percent budget is really being met in production?"

I measure it the same way I measure anything else: a canary. One instance runs with the agent disabled, the rest with it enabled, for a day, and I compare CPU per request and p99 latency from the service's own metrics.

JFR also reports its own cost indirectly, since the sampler and the RecordingStream thread appear in the profile under their own thread names, so I can read the agent's share off the flame graph it produced.

I also watch for indirect costs: the sampler causing safepoints in older JDKs, which -Xlog:safepoint shows, and the upload competing for CPU quota in a throttled container, which the throttling counter shows.

The budget is enforced by the agent raising its sampling interval automatically if its own measured share exceeds the limit.

"Why collapsed stacks instead of a proper database of samples?"

Collapsed stacks are already the aggregate: one minute of samples from one instance is a few thousand distinct stacks with counts, compressing to tens of kilobytes, and merging two files is adding counts for equal lines, which is trivial and parallel.

A sample database that stores each sample with a timestamp allows arbitrary time slicing, but at 50 samples per second per thread it is a hundred times the volume, and every query pays to aggregate.

The per-minute granularity is the trade: I lose the ability to ask "what happened in the 200 milliseconds at 12:03:17.4", and I get years of history at the same cost.

For the sub-second question the answer is the JFR ring buffer on the instance, which the runbook already dumps.

Drill · Production fires at the JVM layer

This group tests whether you can reason about capacity, containers, the operating system and the collector as one system, and diagnose the incidents that live in the gaps between them.

Q134. "Do the capacity arithmetic for me: how many threads does a service need, when does adding CPUs stop helping, and what competes with request threads for the CPU inside a container?"

Reveal answer

The real test Whether you can apply Little's law and Amdahl's law to a JVM with numbers, and whether you know that GC and JIT threads are not free.

Strong answer Little's law says that the number of requests in flight equals the arrival rate multiplied by the time each one spends in the system.

A service handling 2,000 requests per second with an average latency of 40 milliseconds has 80 requests in flight, so it needs about 80 threads if each request holds a thread for its whole life, and far fewer if the threads only hold CPU while the request waits elsewhere, which is the argument for virtual threads.

The trap is that latency in that formula is the latency under load, including queueing, so a pool sized from the idle latency is too small and then makes latency worse.

Amdahl's law says that speed-up from more CPUs is capped by the fraction of work that must run serially: if 10 percent of each request is serialised behind one lock or one connection, 16 CPUs give at most about 6.4 times the throughput of one, and 64 CPUs about 8.8.

So when a service stops scaling with cores, I look for the serial fraction, a hot lock, a single-threaded logger or a database connection pool of size four, rather than adding cores.

Utilisation is the fraction of time a resource is busy; saturation is work waiting for it. A CPU at 70 percent utilisation with no run-queue is fine; at 70 percent with a run-queue of ten it is saturated because the load is bursty.

In a container the JVM's own helper threads share the CPU quota with request threads.

G1 sizes ParallelGCThreads to the available processor count up to eight, and five-eighths of each core above that, ConcGCThreads to a quarter of that, and CICompilerCount, the JIT compiler threads, to a formula based on the log of the core count with a minimum of two.

All of them are computed from what the JVM believes the processor count is, which in a cgroup is the CPU quota rounded up, or whatever -XX:ActiveProcessorCount says.

With a quota of two, a young collection with two GC threads and a compiler thread burst can consume the whole 100-millisecond period, and request threads are throttled until it ends.

Capacity planning therefore includes GC and JIT CPU, which JFR's jdk.ThreadCPULoad by thread name and the GC log's gc+cpu lines quantify; a service spending 15 percent of its CPU in GC has 15 percent less capacity than the request count suggests.

Land it Threads come from throughput times latency under load, scaling stops at the serial fraction, and the CPU budget must include the collector and the compiler, because inside a quota they are not free.

Likely follow-ups
"Walk me through sizing a container for a service doing 500 requests per second at 60 ms, with 12 percent of CPU going to GC."

Little's law gives 500 times 0.06, which is 30 requests in flight, so 30 to 40 platform threads or a virtual-thread executor with no sizing at all.

For CPU I need the per-request CPU cost, say 4 milliseconds measured from JFR, so 500 requests per second cost 2 CPU-seconds per second of request work.

Add 12 percent for GC and a margin for the JIT and the kernel, which is about 2.4 cores of steady work.

I would not set a limit of 2.4 because bursts would throttle; I would set a request of 3 and a limit of 4, or no limit, and then -XX:ActiveProcessorCount=4 so GC and compiler threads are sized for four.

Memory is heap from the live set times a factor of two to three for G1, plus about 25 percent for metaspace, code cache, thread stacks and GC data structures, verified with native memory tracking.

"What is the difference between utilisation and saturation in practice, and what metric shows each for a JVM?"

Utilisation is how busy the resource is, saturation is how much work is queued for it. For CPU, utilisation is the container's CPU usage against its quota, and saturation is the throttling count in /sys/fs/cgroup/cpu.stat plus the run-queue length from vmstat.

For the request path, utilisation is active threads over pool size, and saturation is the executor's queue depth or the connection-pool wait time, which HikariCP exports as a timer.

For memory, utilisation is heap after GC over max heap, and saturation is GC time per second, because a collector working hard is the sign that memory is scarce.

The rule I use is that utilisation tells me when to add capacity, and saturation tells me users are already feeling it.

"Why does the JVM's GC thread count matter more than the CPU count suggests?"

Because GC threads run in bursts at full speed.

During a G1 young pause every parallel GC thread is busy for the whole pause; on an 8-CPU quota that is eight threads for maybe 20 milliseconds, using 160 milliseconds of CPU time inside one 100-millisecond scheduler period.

If the quota is smaller than the thread count, the kernel throttles the process mid-collection, the pause stretches to cover the wait, and every request thread is stopped for the extended pause.

That is why the same heap and workload shows 20-millisecond pauses on a bare host and 80 on a throttled container.

The fix is to make ParallelGCThreads at most the quota, and preferably to give the container a quota equal to the thread count the JVM will choose.

Q135 · Scenario. "A service in Kubernetes has a p99 that spikes every 100 milliseconds like clockwork. CPU usage looks fine. What is going on?"

Reveal answer

Strong answer I would take it in this order:

  1. Symptom: a periodic spike at exactly the period of the Linux completely fair scheduler's bandwidth control, which is 100 milliseconds by default. That period is the tell: the container is using its whole CPU quota early in each period and being stopped for the rest.
  2. Evidence: inside the pod, cat /sys/fs/cgroup/cpu.stat and watch nr_throttled and throttled_usec climb; on cgroup v1 the same lives under cpu,cpuacct/cpu.stat. The dashboard's CPU number looks fine because it is averaged over seconds, and 40 percent average with 100 percent for the first 40 milliseconds of each period is exactly this pattern. Then jcmd <pid> VM.flags for the effective GC and compiler thread counts, and a JFR recording read with jfr view thread-cpu-load to see which threads burn the quota.
  3. Ranked causes. First, the JVM has more runnable threads than the quota: with a limit of 2 CPUs, four request threads plus two GC threads plus two compiler threads can all be runnable, so the quota is spent in 25 milliseconds and everything waits 75. Second, JIT and GC bursts: a young collection or a compilation spike uses several threads at once and blows the period even when the average is low. Third, the limit is fractional, such as 500 millicores, so the JVM saw one processor, chose Serial GC and one compiler thread, and still cannot fit its bursts in 50 milliseconds per period.
  4. Fix: remove the CPU limit and keep the request, which most platforms allow, or raise the limit to cover the burst rather than the average; set -XX:ActiveProcessorCount to match the limit and cap -XX:ParallelGCThreads and -XX:CICompilerCount so the JVM cannot exceed its quota with its own helpers; make the request-thread pool no larger than the quota for CPU-bound work.
  5. Prevention: load-test with the same limits as production, alert on nr_throttled per minute, and treat CPU limits as a latency setting, not a cost setting.

Land it A 100-millisecond rhythm is the scheduler's quota period, and the fix is to stop the JVM's total runnable threads from exceeding the quota, or to stop enforcing the quota.

Likely follow-ups
"You raised the limit to 4 and capped the GC threads, throttling counters went to zero, but p99 still spikes every 100 ms. What next?"

Then the rhythm has another source with the same period.

I would look for a timer in the application or its libraries: a metrics scraper, a scheduled task, a connection-pool housekeeper or a log flusher running every 100 milliseconds; JFR's jdk.ExecutionSample and jdk.ThreadPark events with the timeline view show a thread waking on that cadence.

I would check whether a neighbour pod on the node is throttled and stealing the core, with /proc/pressure/cpu for CPU pressure stall information. And I would check the kernel's own tick and any periodic khugepaged or writeback activity in /proc/vmstat.

If nothing is periodic on the host, the spike may be in a dependency that is itself throttled, which a trace across services shows.

"Why is the CPU dashboard lying, and what would a truthful graph show?"

The dashboard integrates CPU seconds over a scrape interval of 15 or 60 seconds and divides by the interval, so it reports the average.

Throttling is about the peak within each 100-millisecond period: a process can average 30 percent of its quota and still be throttled in every single period if its work arrives in bursts.

A truthful graph plots nr_throttled divided by nr_periods from cpu.stat, which is the fraction of periods in which the container was stopped, and throttled_usec, which is how long it was stopped.

A service with 80 percent of periods throttled at 30 percent average CPU is common and looks healthy on the average graph. I put the throttling fraction next to the p99 on every JVM dashboard, because they move together.

"Is removing the CPU limit safe for the rest of the node?"

Mostly yes, because the request still applies.

The request sets the scheduler weight, so under contention each pod gets at least its requested share and no more than its fair share of the idle CPU. What removing the limit gives up is the guarantee that a pod cannot use more than N cores when the node is idle, which is only a problem for billing or for a workload that must behave identically on empty and busy nodes.

The risk to watch is a pod that leaks threads and eats the whole node; that is a bug to catch with a thread-count alert, not with a limit that punishes healthy pods every 100 milliseconds.

Many platform teams settle on requests only for latency-sensitive JVMs and limits for batch jobs.

Q136. "What does the JVM actually read from a container's cgroup, how does it size itself from that, and what changes in JDK 27?"

Reveal answer

Strong answer Since JDK 10, with -XX:+UseContainerSupport on by default, the JVM reads the cgroup control files instead of the host's numbers.

Under cgroup v2, the standard on modern kernels and supported in the JVM since JDK 15 with backports to 11, it reads memory.max for the memory limit and cpu.max for the CPU quota and period.

The memory limit drives heap sizing through percentages: -XX:MaxRAMPercentage, default 25, sets the maximum heap as a fraction of the limit; -XX:InitialRAMPercentage, default about 1.5, sets the starting heap; -XX:MinRAMPercentage, default 50, only applies to very small containers to stop the heap becoming tiny.

So a 4 GB pod gets a 1 GB heap unless I say otherwise, and I usually set MaxRAMPercentage to 50 to 70 and leave the rest for metaspace, code cache, threads, direct buffers and the collector's own tables.

For CPU, the available processor count is the quota divided by the period, rounded up, so a limit of 1500 millicores gives two processors; CPU shares are ignored since JDK 19 unless -XX:+UseContainerCpuShares is set, and -XX:ActiveProcessorCount=n overrides everything.

That count then sizes the GC threads, the compiler threads, ForkJoinPool.commonPool, the virtual-thread scheduler and, until JDK 27, the choice of collector: a JVM that sees fewer than two processors or less than about 1,792 MB of memory considers itself a client-class machine and picks Serial GC, which surprises people who assumed G1.

Throttling is the symptom that this arithmetic went wrong: nr_throttled in cpu.stat rising while the average CPU looks moderate.

JDK 27, in release candidate as of Aug 2026, ships JEP 523, which makes G1 the default in all environments including single-CPU containers, removing that surprise; Serial remains available with -XX:+UseSerialGC for the cases where it is genuinely better, such as a 512 MB heap on one core.

what the JVM reads from the cgroup, and where it gets it wrongruns offline
# Container awareness is ON by default since JDK 10 (-XX:+UseContainerSupport).
# The JVM reads, from cgroup v2:
#   /sys/fs/cgroup/memory.max          -> the memory limit
#   /sys/fs/cgroup/cpu.max             -> "quota period", e.g. "200000 100000" = 2 CPUs
#
# and derives:
#   Runtime.availableProcessors()  = ceil(quota / period)
#   default max heap               = 25% of the limit  (MaxRAMPercentage)

# CHECK WHAT IT ACTUALLY DECIDED, from inside the container:
java -XX:+PrintFlagsFinal -version | grep -E 'MaxHeapSize|ActiveProcessorCount'
cat /sys/fs/cgroup/memory.max /sys/fs/cgroup/cpu.max

# WHERE IT GOES WRONG:
#
# 1. /proc IS NOT NAMESPACED. `free`, /proc/meminfo and /proc/cpuinfo report the
#    HOST's values. Any library that reads them — not the JVM itself, but plenty
#    of libraries and agents — sizes itself for a 96-core machine.
#
# 2. CPU LIMIT vs CPU REQUEST. A request of 200m with no limit gives
#    availableProcessors() = the whole node, so ForkJoinPool.commonPool()
#    is sized for 96 cores while the pod is throttled to a fifth of one.
#
# 3. THE 25% DEFAULT IS TOO LOW for a service and too high for a 1 GB pod once
#    metaspace, code cache and 200 thread stacks are added.

# FIX: set both explicitly, and set the CPU count if the limit is fractional.
JAVA_OPTS="-XX:MaxRAMPercentage=70 -XX:ActiveProcessorCount=2"

Point 2 causes more trouble than the memory setting. A pod with a CPU request and no limit reports every core on the node, so thread pools, the common pool and GC threads are all sized for hardware the pod will never be scheduled onto.

Land it The JVM sizes everything from two cgroup numbers, and the two settings I always make explicit are the heap percentage and the processor count, because the defaults were chosen for a shared host, not a pod.

Likely follow-ups
"How would you verify what the JVM decided inside a pod?"

At startup, -Xlog:os+container=info prints every cgroup value the JVM read, the version it detected, the memory limit, the CPU quota and period, and the resulting processor count.

On a running process, jcmd <pid> VM.flags shows the computed MaxHeapSize, ParallelGCThreads, ConcGCThreads and CICompilerCount, and jcmd <pid> VM.info has a container section with the same values. java -XshowSettings:system -version prints the container limits without starting an application, which is handy in a Dockerfile check.

The number I compare against is kubectl get pod -o yaml, and the two mismatch more often than people expect, usually because a sidecar or an init container changed the cgroup, or because the node runs cgroup v1 with a JDK that only partially understands it.

"Why 25 percent by default, and what goes into the other 75?"

The default predates containers; it was chosen for a JVM sharing a host with other processes, and it was kept because raising it silently could OOM-kill existing deployments. Inside a pod the JVM is usually alone, so the question is what the non-heap parts need.

Metaspace for a framework-heavy service is 100 to 300 MB; the code cache is up to 240 MB reserved and typically 50 to 100 MB used; each platform thread stack reserves 1 MB and commits what it touches, so 500 threads can be 100 to 500 MB; G1's remembered sets and card tables are a few percent of heap; direct byte buffers default to a limit equal to the max heap; and the C library's own allocator fragments over time.

Native memory tracking's summary gives the real number for a given service, and I set MaxRAMPercentage so that heap plus that number fits the limit with 10 percent spare.

"What are the JDK 27 changes a container-heavy shop should plan for?"

Two, both scheduled for the September 2026 release.

JEP 523 makes G1 the default collector everywhere, so single-CPU pods that were silently running Serial will switch to G1 on upgrade: slightly more memory for G1's data structures, more predictable pauses, and concurrent marking threads that compete for a small quota, which is a reason to test small pods with -XX:+UseSerialGC pinned if they were happy.

JEP 534 turns compact object headers on by default, which reduces live heap by around 10 to 20 percent and needs the JNI and Unsafe audit I would do beforehand. Neither changes the cgroup reading.

I would upgrade a canary of each shape, single-CPU, memory-tight and large, with -Xlog:gc* and native memory tracking on, before moving the fleet.

Q137 · Scenario. "We moved a high-allocation service from G1 to generational ZGC on JDK 21 expecting better pauses, and p99 got four times worse. Diagnose it and tell me what you would conclude."

Reveal answer

Strong answer I would take it in this order:

  1. Symptom: a collector whose pauses are sub-millisecond made latency worse. ZGC never pauses for long, so the latency has to come from something other than pauses: threads stalling because the collector could not keep up.
  2. Evidence: -Xlog:gc* with ZGC prints Allocation Stall (thread-name) lines when a thread had to wait for the collector to free memory; their count and duration are the whole story. JFR shows the same as jdk.ZAllocationStall events. The GC log's cycle lines show how often the young generation is collected and how long each cycle takes, and jcmd <pid> VM.flags shows the ConcGCThreads value ZGC chose.
  3. Ranked causes. First, no headroom: ZGC is concurrent, so the application keeps allocating while the collector works, and it needs enough free heap to absorb that allocation for the length of a cycle; a service allocating 2 GB per second with a 4 GB heap and a 1-second cycle runs out and stalls. G1 handled the same heap because it stops the world and reclaims in one step. Second, starved GC threads: ZGC's concurrent threads share the container's CPU quota, and with a 2-CPU limit they get a fraction of a core, so cycles take longer and stalls grow. Third, bigger objects: ZGC uses 64-bit coloured pointers and does not use compressed references, so every reference field is 8 bytes instead of 4, and the live set grew 10 to 20 percent, which raised the cycle frequency. Fourth, allocation rate itself: the service allocates far more than it needs, and G1's cheap bump-pointer young collections hid it.
  4. Fix: raise the heap so there is headroom, typically double the live set plus one second of allocation; raise the CPU quota or set -XX:ConcGCThreads explicitly; and reduce allocation on the hot path using a JFR allocation profile. Then re-measure.
  5. Honest conclusion, if the numbers say so: for a high-allocation, throughput-oriented service with a modest pause target, G1 was the right collector, and the switch was a change in search of a problem. ZGC earns its place when pause time on a large heap is the actual complaint.

Land it A concurrent collector trades pause time for headroom and CPU, and when the service has neither to give, the honest fix is to go back to G1.

Likely follow-ups
"You doubled the heap and the stalls are gone, but p99 is still worse than under G1. What next?"

Then the remaining cost is throughput, not stalls.

ZGC's load barriers, the small checks it inserts on every reference load, and its concurrent work steal CPU from request threads; on a CPU-bound service that can be 5 to 15 percent, which shows up as longer service time under load.

I would compare CPU per request from JFR between the two collectors, and the jdk.ThreadCPULoad of the ZGC worker threads. If the service is CPU-saturated, the extra work pushes it into queueing and the tail grows.

The options are more CPU, less allocation, or the conclusion that G1 was correct. I would also confirm the comparison is fair: same heap size, same JDK, same load, because a G1 run with a smaller heap is not the baseline.

"Why does generational ZGC need headroom when it has a young generation now?"

The young generation makes each cycle cheaper, because most objects die young and only survivors are relocated, so cycles finish sooner and headroom requirements dropped a lot compared with the single-generation ZGC of JDK 15 to 20.

But the mechanism is unchanged: allocation continues during the cycle, so the heap must hold the live set plus everything allocated during the cycle plus the relocation space. If allocation outpaces reclamation the thread that cannot get a page stalls until a cycle completes.

ZGC adapts by starting cycles earlier when it sees high allocation, but it cannot invent memory.

As of Aug 2026 JDK 23 made the generational mode the only mode and JDK 24 removed the old one, so the headroom rule of "live set times two, plus allocation per cycle" is the one to plan with.

"What would have told you beforehand that ZGC was the wrong choice?"

Three numbers from the existing G1 deployment. The allocation rate from jfr view allocation-by-site or the GC log's young-collection frequency times the young size; above about a gigabyte per second per core ZGC needs a lot of headroom.

The live set, meaning heap after a full or mixed collection; if it is a small fraction of the heap G1's pauses are already short.

And the actual pause distribution from jfr view gc-pauses; if G1's p99 pause was 30 milliseconds and the service's p99 latency target is 200, pauses were not the problem.

ZGC is the answer when pauses on a 50 GB heap are hundreds of milliseconds and the service can afford 20 percent more memory and CPU. A one-day canary with the same flags would have shown all of it.

Q138. "What should a JVM engineer know about transparent huge pages, swap and NUMA, and which flags do you actually set?"

Reveal answer

Strong answer These three are operating-system memory settings that show up as JVM latency.

Huge pages are 2 MB memory pages instead of 4 KB ones; they reduce translation lookaside buffer misses, the CPU's cache of virtual-to-physical mappings, which can be a 5 to 10 percent throughput gain on a large heap.

Transparent huge pages, THP, are the kernel doing this automatically.

The setting in /sys/kernel/mm/transparent_hugepage/enabled can be always, madvise or never, and always is the dangerous one: the kernel promotes any memory it likes and, when it lacks a free 2 MB block, may compact memory synchronously during a page fault, which stalls the faulting thread; the khugepaged daemon also collapses pages in the background and can stall a process while it does.

The safe pattern is madvise on the host, and -XX:+UseTransparentHugePages on the JVM, which asks for huge pages only for the heap through madvise, combined with -XX:+AlwaysPreTouch so every heap page is faulted in at startup rather than during the first request.

-XX:+UseLargePages is the stricter alternative that uses pre-reserved hugetlbfs pages from vm.nr_hugepages, which cannot be swapped or fragmented but must be reserved by the operator. I check what I got in /proc/<pid>/smaps under AnonHugePages for the heap mapping.

Swap is simpler: a JVM must never swap, because a collector touching a swapped-out region turns a millisecond pause into seconds, so swap is off or vm.swappiness is near zero and the container's memory limit is below the node's real memory.

NUMA, non-uniform memory access, means a multi-socket machine where memory attached to the other socket is slower; -XX:+UseNUMA makes the collector allocate each thread's memory on the socket it runs on, which Parallel GC, G1 since JDK 14 and ZGC support, and it only helps on multi-socket hosts where the JVM spans sockets.

The flags I set on a large host: -XX:+UseTransparentHugePages -XX:+AlwaysPreTouch, THP at madvise, swap off, and -XX:+UseNUMA only if numactl --hardware shows more than one node.

Land it Huge pages are a throughput gain that becomes a latency bug when the kernel decides for you, so I ask for them explicitly, pre-touch them, and never let the heap swap.

Likely follow-ups
"What does -XX:+AlwaysPreTouch cost, and when would you not use it?"

It touches every page of the committed heap at startup. Two consequences follow: a 32 GB heap takes a few seconds longer to start, and resident memory is the full heap from the first second rather than growing with use.

The gain is worth those costs in most services. Page faults — and any transparent huge-page compaction they trigger — happen before traffic arrives, instead of during it.

And the memory the pod will eventually use becomes visible immediately, which makes an OOM kill happen at deploy time rather than at peak.

I would not use it in three situations:

  • A service with a very large -Xmx and a small typical live set that relies on the collector uncommitting memory — pre-touching commits the maximum.
  • A scale-to-zero environment, where startup seconds matter more than the first request's latency.
  • With Serial, or with small heaps, where it buys nothing.
"How do you tell a THP stall from a GC pause after the fact?"

The GC log with gc+cpu prints user, system and real time for each pause; a stall inside a pause shows as real time far above user plus system, sometimes with high system time from the kernel compacting.

Outside pauses, the stall is invisible to the JVM, so I go to the kernel counters: /proc/vmstat fields compact_stall, thp_fault_alloc and thp_fault_fallback incrementing at the moment of the stall, khugepaged showing CPU in top, and /proc/pressure/memory for memory pressure stall time.

perf trace or bpftrace on the page-fault path can pin it to the thread. If the counters do not move, it was not THP, and I look at swap-in counts and CFS throttling next.

"Do huge pages help in a container, and what is different there?"

They help the same way, since the translation lookaside buffer does not know about containers, but the settings are node-level.

transparent_hugepage/enabled is a host sysfs setting the pod cannot change, so the platform team must set it to madvise; with always every pod on the node is exposed to compaction stalls caused by its neighbours' memory churn.

hugetlbfs pages need a reservation on the node and a pod resource request of the hugepages-2Mi type, which most platforms support but few enable.

Also, huge pages cannot be partially reclaimed, so a JVM using them holds full 2 MB units, which slightly raises resident memory accounting against the pod limit.

On a small pod with a 1 GB heap the gain is not worth the setup; above roughly 8 GB it is.

Q139 · Scenario. "Every few minutes requests stall for about 200 milliseconds. GC, safepoints and JFR show nothing. The JVM says it was not paused. How do you find it?"

Reveal answer

Strong answer I would take it in this order:

  1. Symptom: a stall the JVM cannot see, which means the process was not running at all during it. When the JVM's own instruments are blank, the only remaining actor is the operating system, which stopped the threads without telling anyone.
  2. Evidence: JFR's jdk.ThreadCPULoad and the jdk.ExecutionSample timeline show a gap where no samples were taken, which is different from samples in a wait state; that gap is the signature of the process being descheduled. Then the host: sar -u -r -B 1 around the stall for CPU steal, paging and major faults; dmesg -T for kernel messages such as NMI watchdog, clock source changes or driver resets; /proc/vmstat for compact_stall, pswpin and nr_dirty; /sys/fs/cgroup/cpu.stat for throttling; and /proc/pressure/cpu, memory and io for pressure stall information, which records exactly how long tasks were stalled and why.
  3. Ranked causes. First, transparent huge page compaction or khugepaged collapsing pages, which stalls a thread on a page fault. Second, swap: a few heap pages swapped out by a memory-pressured node come back in one at a time. Third, CFS throttling or a noisy neighbour on a shared host, visible as steal time in a virtual machine. Fourth, periodic writeback: a log or journal flush saturating the disk while a thread blocks in fsync. Fifth, a clock issue: a virtual machine whose clock source jumps makes the measured stall a fiction, which dmesg and /sys/devices/system/clocksource reveal.
  4. Fix, per cause: THP to madvise with the JVM pre-touching its heap; swap off and memory limits below the node's capacity; a CPU quota that fits or dedicated nodes; logs on a separate volume with asynchronous writes; tsc as the clock source.
  5. Prevention: export the pressure stall information counters and the throttling counters as metrics next to latency, because they are the OS's own account of every stall the JVM cannot see.

Land it When every JVM instrument is blank, the process was not running, and the kernel's pressure and throttling counters are where the 200 milliseconds went.

Likely follow-ups
"The kernel counters are all flat during the stall. What next?"

Then the process was running and the stall is a wait the JVM did see but I did not look at properly.

I would take async-profiler in wall mode filtered to request threads across a stall, which shows the exact native frame they waited in; epoll_wait means a dependency, fsync means the disk, futex means a lock or a park inside the JVM. I would check DNS, because a resolver with a five-second timeout and a flaky first nameserver produces periodic stalls that look like nothing.

I would check jdk.JavaMonitorEnter with the threshold lowered to 10 milliseconds and jdk.VirtualThreadPinned if virtual threads are in play.

And I would look at the load balancer, because a stall measured at the client can be a retry or a connection re-establishment that the service never saw.

"What are the pressure stall information files and why do you rate them so highly?"

Since kernel 4.20, /proc/pressure/cpu, /proc/pressure/memory and /proc/pressure/io, and the same per cgroup under /sys/fs/cgroup/<group>/cpu.pressure, report the share of time in the last 10, 60 and 300 seconds during which some or all runnable tasks were stalled waiting for that resource, plus a total in microseconds.

They answer "was this process stopped, and for what" directly, without me inferring it from a dozen counters.

A full value on memory pressure means every task was stalled on memory at once, which is the swap or compaction case; some on CPU means runnable tasks waited for a core, which is throttling or a busy node.

I scrape them into the metrics system because they correlate with latency tails better than anything the JVM exports.

"How does jdk.ThreadCPULoad help distinguish waiting from being descheduled?"

The event samples each thread's user and system CPU time at an interval, ten seconds by default in the settings I run.

A thread that is waiting on a lock or a socket shows near-zero CPU with a stack in a park or a read; a thread that was descheduled by the kernel while runnable also shows low CPU, but its execution samples in the same window are missing or show it mid-computation, not in a wait frame.

Comparing the two, plus the wall-clock gap between consecutive execution samples for the same thread, tells them apart.

On JDK 25 the CPU-time sampler from JEP 509 makes this sharper, because it counts failed sampling attempts, and a burst of failures at the stall time is direct evidence that the threads were not on a CPU.

Q140. "Describe your GC tuning methodology: which levers matter, which flags you refuse to touch, and how you present the result."

Reveal answer

The real test Whether you tune from a measurement toward a stated goal with one change at a time, and whether you know the flags that fight the collector's own adaptivity.

Strong answer The methodology starts with a goal in numbers, because "make GC better" cannot be finished: for example, p99 pause under 50 milliseconds and GC CPU under 5 percent at 3,000 requests per second.

Then a baseline, always from -Xlog:gc*:file=gc.log:time,uptime,level,tags plus a JFR recording, read with jfr view gc-pauses and jfr view allocation-by-site, which gives me the three numbers that decide everything: the live set, meaning heap after a full or mixed collection; the allocation rate; and the pause distribution.

The levers that matter, roughly in order of effect.

First, heap size relative to live set: G1 wants the live set to be a third to a half of the heap, and most "GC problems" are a heap that is too small for the live set or a live set that is too large because of a leak or a cache.

Second, the collector: G1 for most services, ZGC when pauses on a large heap are the actual complaint and there is CPU and memory headroom, Parallel for batch throughput, Serial for tiny single-core pods.

Third, the pause target: -XX:MaxGCPauseMillis, default 200, which G1 meets by choosing the young size, so lowering it trades throughput for latency.

Fourth, region size: -XX:G1HeapRegionSize raised so that large arrays stop being humongous, meaning half a region or more and allocated directly in the old generation. Fifth, GC threads under a CPU limit, -XX:ParallelGCThreads and -XX:ConcGCThreads, so the collector cannot exceed the quota.

Sixth, -XX:MetaspaceSize raised so the first metaspace-triggered full collection does not happen at startup, and on ZGC -XX:SoftMaxHeapSize to keep the heap small when idle. One change at a time, measured for long enough to include the mixed-collection cycle, under the production load shape.

Flags I refuse to touch on G1: -Xmn, -XX:NewRatio and -XX:SurvivorRatio, because fixing the young size disables the pause-target adaptivity that is G1's entire design; and anything found on a blog for JDK 8.

Presenting: the before and after pause histograms side by side, GC CPU percentage, throughput at the same load, the one flag changed, and the sentence "this holds for this allocation rate and live set; re-check when either changes by half".

Land it Tuning is choosing a goal, measuring the live set and the allocation rate, moving one lever, and never overriding the adaptive sizing that the collector uses to meet the goal for me.

Likely follow-ups
"Why is lowering MaxGCPauseMillis to 20 usually a mistake?"

G1 meets the target by shrinking the young generation, because a young collection's time is proportional to the survivors, and a smaller young generation has fewer of them per collection.

A 20-millisecond target on a busy service produces a tiny young generation, so collections run several times a second, more objects survive into the old generation simply because they were alive at collection time, the old generation fills faster, mixed collections become frequent, and total GC CPU can double, all for pauses that were already 30 milliseconds.

The right move when 30 is too many is usually a bigger heap, less allocation, or ZGC, not a number the collector cannot honour without hurting throughput.

I would change it only with the GC log showing the young size G1 chose and the survivor rate before and after.

"How do you decide the heap size from the numbers you named?"

From the live set and the allocation rate.

For G1 I start at two to three times the live set: a 2 GB live set gets a 4 to 6 GB heap, which gives the old generation room to absorb promotions between mixed cycles and gives the young generation room to grow toward the pause target.

Then I check the allocation rate: at 500 MB per second, a 1 GB young generation means a collection every two seconds, which is comfortable; at 5 GB per second I need either a bigger young generation, meaning a bigger heap, or an allocation profile and code changes.

For ZGC the rule is stricter, live set times two plus one cycle's worth of allocation, because the collector needs headroom to run concurrently.

I then confirm with the log that heap after GC stays flat, which is the sign the size is right and there is no leak.

"What does a humongous allocation problem look like, and what is the fix?"

In G1 an object of half a region or more is humongous and takes whole contiguous regions in the old generation.

The log shows Pause Young (Concurrent Start) (G1 Humongous Allocation) lines, the old generation fills with regions that are freed only at the end of a marking cycle or, since JDK 8u40, eagerly for arrays with no references, and fragmentation can cause a full collection with plenty of free heap.

The JFR event jdk.ObjectAllocationSample with a size filter shows who allocates them, usually byte arrays for buffers or large collections.

The fix is first the region size: with a 4 GB heap the default region is 2 MB, so anything over 1 MB is humongous; -XX:G1HeapRegionSize=8m raises the threshold to 4 MB. Then the code: pool or chunk the big buffers so they are allocated once or in pieces below the threshold.

"How long is long enough to measure a change?"

Long enough to see every phase the collector goes through at least twice.

For G1 that means past the point where the old generation fills to the initiating occupancy, concurrent marking runs and the mixed collections that follow finish; on a service with a large old generation that cycle can be an hour.

A ten-minute test sees only young collections and reports that everything is fine. It also means at the production load shape, including the daily peak, because GC behaviour is a function of allocation rate.

My rule is a full day on a canary next to a control instance with the old flags, comparing jfr view gc-pauses and GC CPU from the same hours, and I write the numbers down before I look at them, so the decision was made in advance.

Q141 · Scenario. "A batch job processes a 1 TB file with parallel streams. It is slower than the single-threaded version and the machine starts swapping. Diagnose and fix it."

Reveal answer

Strong answer I would take it in this order:

  1. Symptom: parallelism made it slower and memory exploded, which together say the work was parallelised in a way that materialises data rather than streaming it, and that the extra threads are contending rather than helping.
  2. Evidence: a JFR recording under the job with jfr view allocation-by-site and jfr view hot-methods; three thread dumps, which will show the ForkJoinPool.commonPool workers and what they are doing; -Xlog:gc* for the collection rhythm; and vmstat 1 on the host for the swap-in rate and run queue.
  3. Ranked causes. First, bad splitting: Files.lines(path).parallel() comes from an iterator-backed spliterator that cannot split the file evenly, so the framework batches lines into arrays of growing size, 1024 then 2048 and so on, to give the workers something to do, which for a 1 TB file materialises gigabytes of strings in memory and then swaps. Second, an operation that collects everything, a sorted(), a collect(groupingBy(...)) over the whole stream or a toList() before the write, which makes the entire input live at once regardless of parallelism. Third, boxing: a stream of Long or Double objects allocates 16 to 24 bytes per value, so a primitive-heavy job turns into a garbage collection benchmark. Fourth, the common pool: it has one thread fewer than the core count, is shared with everything else, and a blocking I/O stage in it stalls every other parallel stream in the process. Fifth, the writer: a single synchronized output serialises all workers behind one lock.
  4. Fix: read the file in fixed-size chunks aligned to line boundaries with FileChannel and a MemorySegment map, hand each chunk to a fixed ExecutorService sized to the cores, process each chunk with LongStream or plain loops that produce a small partial result, and merge partial results at the end; write output through one buffered writer fed by a bounded queue so back-pressure stops producers when the disk is slower than the parsers. Memory becomes chunk size times thread count, a few hundred megabytes, and it no longer depends on the file size.
  5. Prevention: an allocation budget per record checked with JFR in the job's test, and a rule that parallel() is used only on sources that split, arrays and IntStream.range, never on files or iterators.

Land it Parallel streams parallelise splitting, and a file does not split, so the fix is to make the chunks myself and keep only one chunk per thread in memory.

Likely follow-ups
"You chunked the file and used a fixed pool, memory is flat, but it is still no faster than single-threaded. What next?"

Then the job is bound by something the threads share.

First the disk: a single spinning disk or a network volume delivers a few hundred megabytes per second regardless of reader count, so iostat -x 1 showing 100 percent utilisation means the parsers are waiting, and the answer is one sequential reader feeding parsers, not eight readers seeking.

Second the writer: if the output is a single file behind one lock or one fsync per record, the profile in wall mode shows every worker parked on it; batching writes fixes it.

Third the merge: a ConcurrentHashMap that every thread updates per record has enough contention to erase the gain, so each thread should keep its own map and merge once. Fourth, memory bandwidth on a machine with many cores and a parser that touches every byte twice.

"Why is boxing so expensive here, with numbers?"

A long is 8 bytes in a register or an array.

A Long is an object: 12 bytes of header plus 8 of value, padded to 24 bytes, plus the 4- or 8-byte reference that points at it, and each one is an allocation the collector must trace and eventually free, with the value one pointer dereference away from the code that uses it.

On a billion records with three numeric fields that is 3 billion allocations and about 72 GB of garbage, which at a realistic allocation rate of 2 to 4 GB per second per JVM is 20 to 40 seconds of pure allocation plus the collections.

Stream<Long> and Map<Long, Long> box on every operation; LongStream, long[] and a primitive map library do not. The JIT can remove some boxes through escape analysis, but not those stored into collections.

"What is wrong with the common pool for this job, and what would you use instead?"

ForkJoinPool.commonPool() is sized to available processors minus one and is shared by every parallel stream and every CompletableFuture without an executor in the process.

A batch job that runs blocking file reads on it occupies the workers, so anything else in the JVM using parallel streams stalls, and the pool cannot add threads to compensate because it assumes CPU-bound tasks.

It is also invisible in configuration, so its size follows the container's CPU quota, which may be one.

I would create a dedicated Executors.newFixedThreadPool(cores) for the CPU-bound parsing, name its threads so they show in thread dumps, and do the I/O on one or two separate threads.

If the enrichment stage calls a remote service per record, that part goes on a virtual-thread executor, where blocking is cheap.

Q142. "What is in your low-latency toolbox on the JVM, and what does each item cost?"

Reveal answer

Strong answer The toolbox is a list of ways to stop something from interrupting the hot path, and every item has a price.

Allocation-free hot paths: no object creation per message, using pre-allocated buffers, primitive arrays and flyweights over MemorySegment, so the collector has nothing to do; the cost is code that looks like C and a test that enforces zero allocation, measured with JMH's -prof gc or JFR's allocation events.

Lock-free hand-off: Agrona's ring buffers and Chronicle Queue for single-producer or many-producer queues built on VarHandle atomics and cache-line padding, which move a message between threads in under a microsecond; the cost is fixed capacity and a back-pressure policy I must design.

Busy-spin instead of park: a consumer thread loops on the queue calling Thread.onSpinWait(), which emits the CPU's pause instruction, rather than blocking, because waking a parked thread costs 10 to 50 microseconds; the cost is a whole core burned at 100 percent per spinning thread.

Affinity and isolation: pinning threads with taskset or, through the foreign function API, a call to sched_setaffinity, on cores removed from the general scheduler with the isolcpus kernel parameter, plus interrupts steered away from those cores; the cost is operating-system configuration owned by someone else, and cores that nothing else may use.

Collector choice: ZGC for sub-millisecond pauses on a normal heap, or Epsilon, JEP 318's no-op collector enabled with -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC, for a process that allocates so little that a sized heap lasts until a scheduled restart; the cost of Epsilon is that an allocation estimate error is an outage.

Warm-up with real shapes: replaying recorded traffic through every branch before going live, so the JIT has compiled and inlined the real paths and no deoptimisation happens on the first unusual message; the cost is a replay harness and a longer start.

Measurement: HdrHistogram for latency distributions with percentiles to p99.99, recorded with an expected interval to correct coordinated omission, the error where a stalled load generator hides the requests it failed to send; the cost is none, it is the one free item.

And the operating-system items from earlier: no swap, THP at madvise, pre-touched heap, power management off. I choose from the list according to the target: 100 microseconds needs the first three; 10 microseconds needs all of them.

Land it Each tool removes one source of interruption at a fixed price in cores, memory or operational complexity, so I buy them in order of the interruption that is actually largest in the histogram.

Likely follow-ups
"When does busy-spinning become the wrong choice?"

When the core it burns is worth more than the microseconds it saves. On a shared node, a spinning thread starves neighbours and, under a CPU quota, burns the whole container's budget and gets throttled, which is worse than parking.

It is also wrong when messages arrive rarely, since spinning for a minute to save 20 microseconds once is pointless, and on a virtual machine where the hypervisor may deschedule the spinning vCPU anyway.

The middle ground is a hybrid wait strategy: spin for a few thousand iterations, then yield, then park with a short timeout, which Agrona's BackoffIdleStrategy implements. That gives near-spin latency under load and near-zero CPU when idle.

I choose pure spinning only for a pinned core on an isolated host with a continuous message flow.

"How would you run Epsilon in production without it being reckless?"

By making the allocation rate a measured, enforced number.

First the test suite asserts zero allocation on the hot path with JFR, and a JMH run reports the bytes per operation for every remaining path, so I know, for example, 200 bytes per connection setup and nothing per message.

Then the heap is sized for the day with a margin: if the process handles 100,000 setups per day at 200 bytes that is 20 MB, and a 4 GB heap is two hundred days of margin.

The process restarts on a schedule outside trading hours, and a fail-over partner covers the restart. A metric watches heap use, and an alert at 50 percent triggers an early hand-over, because when Epsilon runs out the JVM exits with an out-of-memory error, not a pause.

It is reckless without the test and the metric, and routine with them.

"What does core isolation give you that affinity alone does not?"

Affinity, meaning pinning a thread to a core, stops the scheduler moving my thread and losing its cache contents, but it does not stop the scheduler putting other threads on that same core.

isolcpus removes the core from the general scheduling pool, so only threads explicitly pinned to it run there, and combined with steering hardware interrupts elsewhere through /proc/irq/*/smp_affinity and disabling the periodic timer tick on it with nohz_full, the core is interrupted only by the work I put on it.

The measurable difference is in the tail: with affinity alone I see occasional 50 to 200 microsecond stalls when a kernel thread or another process lands on the core; with isolation those disappear and the histogram's maximum drops by an order of magnitude.

The cost is that the core is wasted whenever my thread is idle, and a reboot to change the parameter.

Drill · Staff-level design on the JVM

This group tests whether you can design a system around the JVM's real behaviour, state the requirements and the trade-offs out loud, and say what you would leave out.

Q143 · Scenario. "After upgrading from JDK 17 to 25 with the same -Xmx, resident memory is 30 percent higher and pods are getting OOM-killed. Where did the memory go?"

Reveal answer

Strong answer I would take it in this order:

  1. Symptom: RSS, the resident set size, grew while the heap limit did not. RSS is the whole process: heap, metaspace, code cache, thread stacks, GC data structures, direct buffers, the C library's allocator and mapped files, so the first job is to find which of those grew, not to argue about the heap.
  2. Evidence: native memory tracking on both versions, -XX:NativeMemoryTracking=summary at start, then jcmd <pid> VM.native_memory summary after the same warm-up on a 17 pod and a 25 pod, and the two summaries diffed by category. Plus -Xlog:gc+heap for committed heap over time, jcmd <pid> GC.heap_info, /proc/<pid>/smaps_rollup for what the kernel counts, and -Xlog:os+container to confirm the JVM saw the same limit.
  3. Ranked causes. First, committed heap: G1 in 25 is more willing to expand toward -Xmx under load and less eager to shrink than 17 was, so a service that used to sit at 60 percent of the maximum now sits at 90; the limit was never sized for the full -Xmx. Second, the GC category itself: G1's remembered sets and mark bitmaps changed shape across 20 to 25, and with a large heap the difference is hundreds of megabytes either way. Third, code cache and metaspace: more intrinsics, more compiled code, more classes from a framework upgrade that happened at the same time. Fourth, thread stacks: a switch to virtual threads adds carrier threads and a new scheduler, and a leak of platform threads shows here. Fifth, transparent huge pages set to always, which inflates RSS because a 4 KB touch pins a 2 MB page, and JDK 25's memory layout may simply trigger it more. Sixth, no change in the JVM at all: the base image or a native library changed with the upgrade.
  4. Fix: size the pod for -Xmx plus the measured non-heap, or lower -Xmx to fit; set -XX:MaxRAMPercentage instead of -Xmx so heap follows the limit; consider -XX:+UseCompactObjectHeaders on 25, which shrinks the live heap 10 to 20 percent; and set THP to madvise.
  5. Prevention: RSS is a release gate in the canary, measured by category with native memory tracking, and the pod limit is derived from that measurement rather than from -Xmx plus a guess.

Land it RSS is not the heap, so the answer is a native memory tracking diff by category, and the fix is a pod limit derived from the measured total rather than from -Xmx.

Likely follow-ups
"The NMT diff shows every category within a few percent, but RSS is still 30 percent higher. What next?"

Then the growth is memory the JVM does not track.

Native memory tracking only sees allocations made through the JVM's own allocator; it does not see what the C library allocates for JNI libraries, compression, TLS or DNS, and it does not see kernel accounting such as page cache charged to the cgroup.

I would compare /proc/<pid>/smaps between the versions and look for anonymous mappings not owned by the JVM, which are usually glibc arenas: glibc creates up to eight arenas per core, and a thread-heavy service on a big node fragments them.

Setting MALLOC_ARENA_MAX=2 or switching to jemalloc with LD_PRELOAD usually recovers it. I would also check memory.stat in the cgroup for file pages, since a new logging setup writing faster can be the whole 30 percent.

"Why does the committed heap grow toward -Xmx even when the live set is small?"

G1 chooses its heap size to meet the pause target and a throughput goal, not to minimise memory.

When collections are frequent it expands, because a larger young generation means fewer collections, and it only shrinks after a full or remark phase when the free ratio exceeds MaxHeapFreeRatio, which is 70 percent by default.

Between 17 and 25 the adaptive sizing became more aggressive about expansion under allocation pressure and about keeping the space once taken.

So a service with a 1 GB live set and a 4 GB -Xmx will, under any steady load, end up committing most of the 4 GB. If I want the heap to track the live set, the levers are a smaller -Xmx, -XX:G1PeriodicGCInterval to trigger idle collections that uncommit, and on ZGC -XX:SoftMaxHeapSize, which G1 honours only on newer builds, so verify on the JDK in use.

"How would you have caught this before production?"

With a canary whose pass criteria included memory, not just latency and errors.

The upgrade runbook would run one instance on JDK 25 for a day with native memory tracking on and a dashboard of RSS, committed heap, metaspace and thread count next to the JDK 17 baseline, and a gate of "RSS within 10 percent of baseline at the same load".

The OOM kills happened because the pod limit had been set to -Xmx plus 20 percent from a measurement made years ago on JDK 11, and nobody re-measured.

The general lesson is that any JVM major upgrade changes the non-heap footprint, so the pod limit is a value derived from a measurement that the upgrade must repeat.

Q144 · Design. "Design a low-latency order-matching service in Java. I want the threading model, memory strategy, GC choice, persistence, fail-over and what you would refuse to do."

Reveal answer

Strong answer Requirements and assumptions: one instrument group per process, around 200,000 orders per second at peak, a p99.9 latency under 50 microseconds from network in to acknowledgement out, deterministic behaviour so that replaying the same input gives the same book, and no lost orders across a failure.

Design: the matching core is single-threaded.

One pinned thread owns the order book and processes commands in sequence from an inbound ring buffer, because a single thread with no locks is both the fastest and the only way to be deterministic; the book itself is allocation-free, with orders stored in pre-sized primitive arrays and price levels in an array indexed by price tick, so no object is created per order and the collector never runs on the hot path.

Inbound network threads decode messages into pre-allocated slots of an Agrona-style lock-free ring buffer; the core busy-spins on it with Thread.onSpinWait() between polls rather than parking, because waking a parked thread costs tens of microseconds.

Before matching, every command is appended to a journal, a memory-mapped file accessed through the foreign function and memory API's MemorySegment, written sequentially so that the page cache absorbs it; the journal is the source of truth and replaying it rebuilds the book exactly.

The outbound side is another ring buffer to a publisher thread.

Memory: the heap is small and static, the collector is ZGC for its sub-millisecond pauses, or Epsilon, the no-op collector from JEP 318, with a heap sized for a trading day and a scheduled restart, which is viable only because the hot path allocates nothing.

Cores are pinned with taskset or sched_setaffinity via FFM, on cores isolated with isolcpus. Warm-up replays a recorded session through the real code paths before the process joins the cluster, so the JIT has compiled every branch. Latency is measured per message with HdrHistogram.

Fail-over: the journal is replicated synchronously to a secondary that replays it and keeps a warm book; on failure it takes over from the last acknowledged sequence number.

Trade-offs: single-threading caps throughput at what one core does, so scale is by sharding instruments across processes; Epsilon means an outage if allocation was underestimated, so it needs an allocation gate in tests.

What I would refuse: a thread pool around the book, any lock on the hot path, JSON on the wire, and G1 with a pause target as the latency plan.

Land it One thread, no allocation, a sequential journal and a replayable book are the design; everything else is choosing how to keep the collector and the kernel out of the way.

Likely follow-ups
"Requirement change: the p99.9 target relaxes to 2 milliseconds but we now need 2 million orders per second. Does the design change?"

The core stays single-threaded, because 2 million simple matches per second is within reach of one pinned core with an allocation-free book, and the determinism argument still holds. What changes is the surroundings.

With a 2-millisecond budget I can drop busy-spinning for the network and publisher threads and use parking, freeing cores; ZGC becomes the obvious collector and Epsilon is no longer worth its risk.

The bottleneck moves to I/O: decoding 2 million messages per second needs several network threads with a many-to-one ring buffer, and the journal write needs batching, appending a block of commands per flush rather than one at a time.

If one instrument group truly needs 2 million, I would shard by price band, with a small amount of cross-shard coordination, which is where the design gets hard.

"Under time pressure, what would you cut?"

I would cut Epsilon and run ZGC, because it removes a failure mode and the tuning work at the cost of a few microseconds.

I would cut core isolation and affinity for the first release and accept the jitter, since they are operating-system configuration that can be added without code changes.

I would cut synchronous replication and accept asynchronous replication with a small window of loss, if the business signs off in writing.

I would keep the single-threaded core, the allocation-free book and the journal, because those are the architecture and cannot be retrofitted; a book built on TreeMap and Order objects behind a lock is a different system.

I would also keep HdrHistogram measurement from day one, because without it nobody knows whether the cuts hurt.

"Why is coordinated omission a problem in your latency measurement, and how does HdrHistogram help?"

Coordinated omission is the measurement error where a load generator waits for a slow response before sending the next request, so a 100-millisecond stall hides the hundred requests that should have been sent during it and shows up as a single slow sample instead of a hundred.

The percentiles then look far better than what a real client, sending at its own pace, would see.

HdrHistogram records values with high dynamic range and low memory, and its recordValueWithExpectedInterval method fills in the missing samples: when a value exceeds the expected interval between sends, it records the extra samples that would have been observed.

I measure from the time the order should have been sent, taken from a fixed schedule, not from when the generator got around to it, and I report p99.9 and the maximum, never the mean.

"How do you make the book allocation-free in Java without it becoming unreadable?"

By treating the book as a set of parallel primitive arrays with an index type.

An order is an integer slot; long[] price, long[] quantity, int[] next and int[] prev hold its fields, and a price level is the head slot of a doubly linked list of orders at that price, stored in an array indexed by price tick.

Adding an order is taking a slot from a free list; matching walks the list; cancelling links it out. Wrapped in a class with methods named add, match and cancel, the calling code reads like any book.

I verify the "no allocation" claim with a JFR recording under load that shows zero jdk.ObjectAllocationSample events from the core thread, and with a JMH run using -prof gc showing gc.alloc.rate.norm of zero bytes per operation, and I make that check a test.

Q145 · Scenario. "A penetration test shows a deserialization gadget chain works against our RMI and JMX endpoint. What do you do tonight, this week, and permanently?"

Reveal answer

Strong answer I would take it in this order:

  1. Symptom: remote code execution through a serialized object. RMI and the JMX remote connector both use Java serialization on the wire, so any class on the classpath with a known gadget chain, meaning a sequence of ordinary methods that deserialisation triggers and that ends in executing a command, is reachable by anyone who can open the port.
  2. Evidence: which processes expose the port, from ss -ltnp and the -Dcom.sun.management.jmxremote.port flags in jcmd <pid> VM.flags; whether authentication and TLS were on; and which gadget library the test used, from the payload and jdeps over the classpath.
  3. Tonight: cut the network path. Firewall the RMI and JMX ports to the management network or to localhost, and where remote JMX is not needed, remove -Dcom.sun.management.jmxremote.port entirely, so JMX is reachable only through a local attach. Enable the deserialisation filters that already exist in the JDK: a global -Djdk.serialFilter='maxdepth=10;maxrefs=1000;maxbytes=1000000;!*' denies everything by default, then an allow-list of the classes the protocol legitimately needs; for the JMX connector specifically, -Dcom.sun.management.jmxremote.serial.filter.pattern, and for RMI's registry and distributed garbage collector the sun.rmi.registry.registryFilter and sun.rmi.transport.dgcFilter properties, which take the same pattern syntax. Turn on authentication and TLS for anything that must stay remote.
  4. This week: remove the gadget libraries that are not needed, upgrade the ones that are, and log filter rejections with the java.io.serialization logger so I can see attempts and tune the allow-list.
  5. Permanently: stop using Java serialization across a network boundary. Replace the RMI protocol with a schema-based one, expose management through an HTTP endpoint with an explicit model rather than the JMX connector, and add a build check that fails when any class exposed to the network implements Serializable with a readObject method, plus the serial filter as a mandatory JVM flag in the base image.

Land it Tonight is the firewall and a deny-all filter, this week is the allow-list and the dependency clean-up, and permanently it is no Java serialization on any socket.

Likely follow-ups
"You set the global deny-all filter and the JMX connector stopped working entirely. What next?"

That is expected, because the connector itself sends serialized objects: ObjectName, Attribute, the open-type classes and the credentials array. The fix is a per-endpoint allow-list, not loosening the global filter.

For JMX the pattern is roughly java.lang.*;java.util.*;javax.management.**;javax.management.openmbean.**;java.rmi.**;!*, plus whatever custom MBean types the service exposes, set with -Dcom.sun.management.jmxremote.serial.filter.pattern, which is applied to the connector's stream and combined with the global filter through the filter factory from JEP 415.

I build the list by running the client against a test instance with the java.io.serialization logger at FINER, collecting the rejected class names, and adding only those.

The one thing I never add back is a wildcard on a package that contains a gadget, such as a whole collections library.

"Is restricting JMX to localhost enough, given a sidecar or an exec into the pod can reach it?"

It is enough against the network attacker the pen test simulated, and not enough against someone who already has code execution in the pod, but that person has already won by other means.

What localhost binding does is shrink the attack surface to processes in the same network namespace, which in Kubernetes means the pod's own containers.

I would still set the serial filter, because the gadget chain works from localhost too and a compromised sidecar is a realistic path.

For management access I would replace remote JMX with the local attach mechanism, jcmd over the Unix socket, which requires the same user ID and no network at all, or with an HTTP bridge such as Jolokia behind the service's normal authentication, which speaks JSON and never deserialises objects.

"How would you prove to the security team that the chain no longer works?"

By repeating the exact attack. I would take the pen test's payload, or generate the same chain with the ysoserial-style tool they used, and send it at the endpoint from outside the network boundary and from inside the pod.

The expected results are a connection refusal from outside, and from inside an InvalidClassException with the message "filter status: REJECTED" naming the first gadget class, logged by the java.io.serialization logger.

I would then remove the gadget library and repeat, expecting a ClassNotFoundException even with the filter off, which proves defence in depth.

Finally I would add both cases as an integration test in the pipeline, so a future dependency that reintroduces the library fails the build rather than the next pen test.

Q146 · Design. "Design a high-throughput ingestion pipeline on the JVM: Kafka in, parse, enrich against a remote service, write to a store. I care about records per second per core, not latency."

Reveal answer

Strong answer Requirements and assumptions: around 500,000 records per second across the fleet, each record a few hundred bytes, enrichment is a network call with a 5-millisecond typical latency and a cache hit rate above 90 percent, and the store accepts batched writes; end-to-end latency of a few seconds is fine.

Design: the pipeline is staged with bounded queues between stages, so each stage has its own thread type and back-pressure is structural. The consumer stage polls Kafka in large batches, max.poll.records in the thousands, on one thread per partition group.

The parse stage runs on a fixed pool of platform threads sized to the cores, because parsing is pure CPU; it parses directly from the received byte buffers into a small mutable record object that is reused per batch, so the allocation per record is the fields, not a tree of wrappers, and it avoids intermediate String objects for fields that are only forwarded.

The enrichment stage runs on a virtual-thread executor, one virtual thread per batch, because it is I/O-bound and thousands of concurrent calls to the remote service cost almost nothing in memory; a local Caffeine cache in front of it makes most lookups a map read.

The write stage batches records into the store's bulk format, a few thousand per request, on a small pool of platform threads.

Queues are ArrayBlockingQueue with fixed capacity, so a slow store fills the write queue, which stalls enrichment, which stalls parsing, which stops polling Kafka, and Kafka holds the backlog, which is what it is for.

The JVM is tuned for throughput: Parallel GC with a large young generation, or G1 with -XX:MaxGCPauseMillis=500 and a large heap so young collections are rare and cheap; either way the target is GC CPU under 5 percent, checked with -Xlog:gc*.

Allocation discipline is enforced by a CI gate: a JMH run of the parse path with -prof gc must report bytes per record under an agreed number, and a JFR recording of the integration test must show no allocation from a list of forbidden sites.

Trade-offs: the staged design adds copying between queues and a few seconds of latency, and the reusable record object is a source of bugs if a reference escapes a stage; virtual threads make the enrichment stage simple but pin if the client library uses native code, so the client is chosen for that.

What I would cut, if asked: the JMH gate first, keeping the JFR gate; the Caffeine cache last, because it is the throughput.

Land it Bounded queues between stages, platform threads for CPU, virtual threads for the network call, and a collector tuned for throughput rather than pauses are the design; everything else is keeping allocation per record honest.

Likely follow-ups
"Requirement change: records must now be visible in the store within 200 milliseconds. What changes?"

The batching that makes throughput cheap is now the latency. Write batches shrink from thousands of records to whatever accumulates in about 50 milliseconds, with a time-based flush as well as a size-based one, and the Kafka poll interval and fetch.max.wait.ms shrink to match.

The queues stay bounded but shorter, so a record cannot wait in a full queue for longer than the budget, which means back-pressure reaches Kafka faster and the fleet needs more headroom.

The collector choice moves toward G1 with the default pause target, because a 300-millisecond Parallel GC pause now breaks the requirement. Per-core throughput drops, perhaps by a third, and the honest answer to the requester is that the change costs roughly that many more instances.

"Under time pressure, what would you cut?"

I would cut the reusable record object and allocate a fresh immutable record per message, because the reuse pattern is where the subtle bugs live and a young-generation collector handles short-lived garbage cheaply; I would check the GC CPU stays under 10 percent and accept it.

I would cut the JMH gate and keep only the JFR check in the integration test. I would cut the custom byte-buffer parsing in favour of a standard parser with a known allocation profile.

I would keep the bounded queues and the stage separation, because those are the difference between a pipeline that degrades gracefully and one that runs out of memory when the store slows down, and I would keep virtual threads for enrichment, since they are less code, not more.

"Why Parallel GC here and not ZGC, when ZGC is the modern choice?"

Because the requirement is throughput per core and the workload allocates heavily.

Parallel GC does the least total work per byte allocated: a bump-pointer young generation, stop-the-world copying of survivors with all cores, no read or write barriers on the application threads, and no concurrent threads competing for CPU. Its pauses can be hundreds of milliseconds on a large heap, which this pipeline does not care about.

ZGC adds a load barrier on every reference load and runs concurrent threads that take 10 to 20 percent of CPU from the parsers, and it needs heap headroom that here would be better spent on the cache.

G1 sits between them and is the safe default if someone later adds a latency requirement. I would run all three for a day on a canary and pick by records per core-second, which is the number the requirement names.

"How do you keep the virtual-thread enrichment stage from overwhelming the remote service?"

Virtual threads remove the thread limit that used to act as an accidental concurrency cap, so I add the cap back on purpose: a Semaphore with, say, 500 permits acquired around each remote call, sized from the remote service's capacity and Little's law, 500 concurrent calls at 5 milliseconds each being 100,000 calls per second.

The queue feeding the stage is bounded too, so once the permits are exhausted the stage stops taking records rather than piling up virtual threads.

The HTTP client is configured with a connection limit and timeouts, and a circuit breaker turns a failing remote service into cached or default enrichment instead of a stall.

I watch the semaphore's wait time as a metric, because it is the earliest sign that the remote service, not the pipeline, is the bottleneck.

Q147 · Design. "Design an in-process cache for a node with 64 GB of RAM. Start from eviction and work outward."

Reveal answer

Strong answer Requirements and assumptions: tens of millions of entries, values from a few hundred bytes to a few kilobytes, a read-heavy workload with a skewed key distribution, a memory budget of around 40 GB for the cache on a 64 GB node, and a time-to-live per entry.

Starting from eviction: the policy is W-TinyLFU, the window plus frequency sketch design that Caffeine implements, because it keeps both recent and frequently used entries and resists a scan of one-off keys flushing the working set.

Eviction has to be driven by measured bytes, not entry count, so every entry carries its serialised size and the policy weighs by it.

Time-to-live is handled by a timer wheel, a set of buckets indexed by expiry time, which expires entries in batches at almost no cost. Now outward to memory.

40 GB of small objects on the Java heap is a garbage collection problem: G1 or ZGC must trace tens of millions of objects on every marking cycle, and a Java String or byte array per value has 16 to 24 bytes of header overhead.

So the values live off-heap in slabs, large MemorySegment blocks allocated through the foreign function and memory API with an Arena, divided into size classes, and an entry is a slab index plus an offset plus a length.

The index that maps keys to entries stays on the heap, but as a primitive open-addressing hash table keyed by a 64-bit hash of the key, with the policy's metadata in parallel arrays, so the collector sees a handful of large arrays rather than millions of nodes.

Accounting: a counter per slab class and a global byte count that the eviction policy reads, exposed as metrics, with the hit rate and the eviction rate next to them.

Hot keys: a small on-heap front cache of the top few thousand entries, deserialised, so the hottest reads never touch off-heap memory or deserialise. Trade-offs: off-heap values must be serialised, which costs CPU on every read and forbids caching arbitrary object graphs.

If the requirement becomes "must survive restarts", the slabs become memory-mapped files, so a restart re-maps them and rebuilds the index by scanning, at the cost of the page cache being shared with the rest of the node.

What I would not do: a ConcurrentHashMap of 40 GB of objects with a background thread deleting old entries, which is an outage waiting for a full GC.

Land it The eviction policy decides what the cache is worth, and keeping the values off the heap is what lets a 40 GB cache and a garbage collector share one process.

Likely follow-ups
"Requirement change: the values are now arbitrary object graphs with cycles that the application mutates. What changes?"

Off-heap storage stops being viable, because it requires serialising each value into a flat block and returning a copy, and a mutable shared graph would silently diverge from its cached copy.

The cache becomes on-heap, so the memory budget drops to what the collector can trace comfortably: with ZGC and a 48 GB heap and a few million entries it works, with tens of millions of small objects it does not.

I would use Caffeine directly for policy and expiry, size by weight using a measured estimator per value type, and make the ZGC headroom part of the budget.

I would also push back on the requirement, because a cache of mutable shared objects is a source of bugs that no design fixes; returning immutable snapshots or a copy per read is the safer contract.

"Under time pressure, what would you cut?"

I would cut the custom off-heap slabs and the primitive index and use Caffeine on-heap with a byte-weighed size limit at a smaller budget, perhaps 16 GB, and accept the collector cost, checked with -Xlog:gc* under a soak.

That keeps the eviction policy, the expiry wheel and the accounting, which are the parts I could not reproduce quickly and which decide the hit rate. I would cut the hot-key front cache, since Caffeine already keeps hot entries cheap.

I would cut restart survival entirely and let a restart warm from the source. The thing I would not cut is measuring the hit rate and the eviction rate from day one, because a cache without those numbers cannot be sized later.

"Why is a plain LRU wrong here, with an example?"

Least-recently-used keeps whatever was touched last. Imagine the working set is 10 million product records read constantly, and once an hour a report scans 20 million order records once each.

Under LRU the scan evicts the entire product working set, because every order record is more recent than every product record, and the hit rate collapses to near zero until the products are reloaded.

W-TinyLFU keeps a frequency sketch, a compact count-min estimate of how often each key was seen; a candidate entering from the small admission window is only admitted to the main region if its frequency beats the entry it would evict.

The one-off order records never beat the products, so the scan passes through the window and the working set stays. Caffeine's published hit rates on database and search traces are 10 to 30 points above LRU for this reason.

"How do you keep the off-heap slabs from leaking or being read after free?"

By never freeing at the granularity of an entry. A slab is a large segment from a shared Arena, entries are appended into it, and an entry's deletion only marks its bytes dead in the slab's accounting.

When a slab's dead ratio passes a threshold, a compaction copies its live entries into a fresh slab, updates the index, and the old slab is released as a unit, which is the log-structured approach that makes a use-after-free a stale index pointer rather than a memory corruption.

Each entry carries a generation number that the reader checks after copying, so a read that raced with compaction retries.

The MemorySegment API bounds-checks every access against its segment, so an arithmetic bug throws instead of corrupting the neighbour, which is the concrete reason to prefer it over Unsafe.

Q148 · Design. "The Security Manager is gone since JDK 24. Design how we run third-party plugins safely inside our product now."

Reveal answer

Strong answer Requirements and assumptions: plugins are jars written by outside parties, they receive events and return results, they must not read our files, open sockets, exhaust memory or CPU, or crash the host, and a plugin call must complete within a bounded time.

JEP 486 permanently disabled the Security Manager in JDK 24, and the honest starting point is that it was never a strong boundary anyway; the JVM offers no in-process isolation. So the design is process isolation.

Each plugin, or each trust group of plugins, runs in its own child process launched by the host: a minimal runtime built with jlink containing only the modules the plugin API needs, so there is no java.desktop or jdk.attach to abuse, started with a fixed heap and -XX:MaxRAMPercentage, as a dedicated unprivileged user, inside a cgroup that caps memory and CPU, with a seccomp profile that denies network system calls and a filesystem view limited to a read-only plugin directory and a scratch directory.

On Linux that is a container or a systemd transient unit with MemoryMax, CPUQuota and SystemCallFilter.

Communication between host and plugin is a Unix domain socket with a small length-prefixed binary protocol, which since JDK 16 SocketChannel supports directly, or, for high-volume data, a shared memory region mapped by both sides through the foreign function and memory API as a MemorySegment over a file in /dev/shm, with the socket used for signalling.

Every call carries a deadline; the host enforces it with a timeout on the socket read and kills the process if a plugin hangs, then restarts it, because a killed process is the only reliable way to stop a runaway thread.

The host validates every message from the plugin against a schema and never deserialises objects from it.

Trade-offs: a call costs tens of microseconds over the socket instead of nanoseconds in-process, startup per plugin process is seconds, which the AOT cache reduces, and memory per plugin is a full JVM, tens of megabytes at least.

What I would not do: class-loader isolation as the security boundary, because a class loader separates names, not privileges, and any plugin code can reach the file system, reflection and threads through the same JDK the host uses; nor would I try to rebuild the Security Manager with an agent that rewrites bytecode, which is a permanent arms race.

Land it The boundary is the operating system's, a separate process under cgroups and seccomp talking over a socket, because the JVM has no boundary of its own to offer.

Likely follow-ups
"Requirement change: plugins are called a million times per second and the socket round trip is too slow. What now?"

Then the shared memory path carries the calls, not just the data.

Host and plugin map the same segment and use it as a pair of ring buffers, one per direction, with sequence counters accessed through VarHandle release and acquire operations; the plugin process spins or parks on its inbound ring, and the host writes a request, bumps the counter and reads the response from the other ring.

That is under a microsecond per call and the process boundary still holds, because the plugin can only write into its own ring and the host validates every response. The cost is a pinned core per plugin process if it spins, and a more careful protocol.

If even that is too slow, the requirement is really asking for in-process execution, and the honest answer is that in-process code is trusted code, so the plugins need review and signing instead of sandboxing.

"Under time pressure, what would you cut?"

I would cut the shared memory path and use only the socket with a simple framing. I would cut the jlink image and run the plugin process on the full JDK with --limit-modules, which is weaker but a one-line change.

I would cut seccomp and rely on the container's default profile and a dedicated user with no network.

I would keep the separate process, the cgroup limits and the timeout-then-kill, because those are the three things that prevent a plugin from taking the host down, and I would keep "never deserialise objects from the plugin", which is one rule in the protocol.

What I would communicate is that the cut version protects availability and most of confidentiality, and the full version comes next quarter.

"Why exactly is class-loader isolation not a security boundary?"

A class loader controls which classes a name resolves to, so two plugins can each have their own version of a library without conflict. It does nothing about what code may do.

Plugin code loaded in a child loader still has java.io.File, ProcessBuilder, Socket, Thread and reflection from the platform loader, because those are the same classes the host uses, and it can call them freely.

Before JDK 24 the Security Manager was the thing that checked those calls against a policy, and even then it was bypassed regularly, was never designed for hostile code, and was disabled by default since JDK 17.

With it gone, a plugin in its own loader can read any file the process can, open any socket, spawn threads until the host dies, or call System.exit. Isolation of names is a packaging feature; isolation of privileges needs a process.

Q149 · Design. "Design a structured logging path that allocates nothing on the request thread. Tell me how you would measure it and what you would cut."

Reveal answer

Strong answer Requirements and assumptions: a service logging around 50,000 structured events per second at peak, each with a handful of typed fields, with the rule that the request thread must not allocate, block on disk, or wait on a lock to log, and with an explicit policy for what happens when the disk falls behind.

Design: the request thread never builds a string.

The API takes typed fields directly, log.info(EVENT_ORDER_PLACED).field(ORDER_ID, id).field(AMOUNT_CENTS, cents).emit(), where the event and field names are pre-interned constants and the builder is a per-thread reusable object, so there is no varargs array, no boxing of the long arguments and no String.format.

The builder writes fields as a compact binary record, a tag byte and the raw value, into a thread-local pre-allocated buffer, and emit() copies that record into a slot of a many-producer, single-consumer ring buffer, claimed with a VarHandle compare-and-set on a sequence counter, which is the Agrona pattern.

One I/O thread drains the ring, formats records into the JSON or line format the log pipeline wants, and writes them in large batches through a FileChannel; formatting is lazy, meaning it happens once on the I/O thread instead of on every request thread.

Exceptions are the hard case: a stack trace is built by the JVM as objects, so the path records only the exception class, message and the top few frames, captured through StackWalker into the buffer, and a full trace is written only for a sampled fraction.

Back-pressure versus drop is a stated policy: for debug and info events the ring drops the oldest when full and counts the drops in a metric; for audit-grade events the emitter spins briefly and then blocks, because losing them is worse than a stall, and those go through a separate ring so they cannot be starved by chatty events.

Measuring: a JMH benchmark of emit() with -prof gc asserting zero gc.alloc.rate.norm, a JFR recording under load showing no jdk.ObjectAllocationSample from the logging package on request threads, and the drop counter on a dashboard.

Trade-offs: a custom binary format needs its own tooling, and the drop policy will surprise someone who expected every debug line to arrive.

What I would cut under time pressure is the binary record: format to a pre-sized StringBuilder per thread and copy the characters into the ring, which still avoids allocation, and keep the ring, the single I/O thread and the drop counter.

Land it The request thread writes typed values into its own buffer and hands the bytes to one I/O thread through a ring; every allocation and every wait moves to that thread, and the drop policy is a decision written down, not an accident.

Likely follow-ups
"Requirement change: logs must carry the trace and span identifiers from the request context, which live in a ScopedValue. Does that break the zero-allocation rule?"

Not if the identifiers are already primitive. A ScopedValue, final in JDK 25 under JEP 506, is a value bound for the dynamic extent of a call, and reading it is a lookup with no allocation.

If the trace context is stored as two long fields in a small holder object bound once per request, the emitter reads the holder and writes the two numbers into the record, and nothing is created per log event.

What would break the rule is a context stored as strings that must be concatenated, or a library that formats the identifiers as hex per call; then I would store the numeric form and format on the I/O thread.

I would confirm with the same JFR check, since a single boxed Long in the holder would show up there immediately.

"Under time pressure, what would you cut?"

Beyond the binary format I already named, I would cut the separate audit ring and use one ring with a blocking policy for everything, accepting that a full disk stalls requests, which is what most logging frameworks already do.

I would cut the sampled stack-trace scheme and log exceptions through the ordinary framework path, since exceptions should be rare and an allocation on an error path is tolerable.

I would cut the JMH benchmark and keep the JFR check, because it runs in the integration test I already have.

I would keep the typed-field API, because retrofitting it later means touching every call site, and I would keep the single I/O thread, because it is what removes the lock from the request path.

"Why not just use an asynchronous appender in the existing logging framework?"

Asynchronous appenders move the disk write off the request thread, and that is worth having, but they do not remove the allocation.

The request thread still builds the message string, boxes the arguments into an Object[], creates an event object and often a copy of the diagnostic context map, which is several hundred bytes per event; at 50,000 events per second that is tens of megabytes per second of garbage on the request threads, which shows up as young collections and as cache pollution on the hot path.

Some frameworks offer a garbage-free mode that reuses message objects and formats into thread-local buffers, and if the requirement is "mostly allocation-free", that mode plus an asynchronous appender is the pragmatic answer.

The custom path is justified when the JFR allocation check must actually read zero, or when the record format needs to be typed for downstream tooling.

"When are JFR custom events the better choice than this design?"

When the consumer is an engineer diagnosing the service rather than a log pipeline.

A custom event is a class extending jdk.jfr.Event with typed fields and an optional @Threshold; begin(), end() and commit() write it into JFR's thread-local buffers with no allocation after the event object, which can be stack-allocated by the JIT, and it is dropped automatically if disabled, so the cost of leaving it in the code is nil.

It carries a thread and a timestamp, correlates with GC, lock and CPU events in the same recording, and jfr print or Mission Control read it with no custom tooling.

It is the wrong choice for audit logs, because the ring is bounded and overwritten, and for anything that must reach a central system in real time. I usually do both: business events to the log path, diagnostic timings to JFR.

Q150 · Design. "Design the JVM performance gate in our release pipeline: what runs, what it compares against, how you stop it flaking, and what you would cut."

Reveal answer

Strong answer Requirements and assumptions: about 300 services releasing daily, a gate that must catch a 10 percent regression in latency, throughput or allocation before production, run in under 30 minutes per release, and produce fewer than one false failure a week. Design in two layers.

The first is a JMH suite for the handful of hot paths per service, run in the build on a dedicated bare-metal runner of the production instance type: @Fork(3), five warm-up and ten measurement iterations, -prof gc for bytes per operation, and the comparison done statistically, not by eyeballing means; JMH prints a confidence interval, and the rule is that the new build fails only if its interval does not overlap the baseline's and the difference exceeds 5 percent, with allocation compared exactly because it is deterministic.

The second layer is a canary in the staging cluster: the candidate and the current release run side by side under replayed production traffic for 20 minutes, with the same flags and pod spec, each recording JFR with profile settings and exporting an HdrHistogram of request latency.

The gate compares p50, p99 and p99.9 with thresholds of 10 percent at p99, compares GC CPU and allocation rate from the JFR files, and produces a differential flame graph between the two profiles, which is attached to the release for the human reviewer whether or not the gate failed.

Baselines are the last three accepted releases, not just the previous one, so a slow drift of 3 percent per release is caught against the oldest.

Flake control: a fixed warm-up before measurement, CPU frequency scaling disabled on the runner, the noise level of the gate measured by running the same build against itself weekly and setting thresholds at three times that noise, and a rerun-once rule where a failure is confirmed by a second run before blocking.

Architectures: services that deploy on both x86 and ARM run the canary on both, with separate baselines per architecture, because inlining, intrinsics and vector width differ and a comparison across them is meaningless.

Trade-offs: the bare-metal runners are a real cost, the 20-minute canary sets the floor on release time, and the JMH layer only covers what someone wrote a benchmark for.

What I would cut: the JMH layer first, keeping the canary, because the canary measures the whole program under real traffic and the micro-benchmarks catch a narrower class of regression; the differential flame graph stays, because it costs nothing and turns a red gate into a diagnosis.

Land it The gate is a canary against the last three releases with thresholds derived from measured noise, and its most valuable output is the differential flame graph that says why, not the red or green.

Likely follow-ups
"Requirement change: releases must go out in under ten minutes end to end. What changes?"

The 20-minute canary no longer fits, so the gate splits into a fast pre-release check and a slower post-release watch.

Pre-release, I keep a five-minute canary with a shorter warm-up and compare only allocation rate and p99, since allocation is stable within seconds and p99 at five minutes is usable if the threshold is widened to the measured noise.

Post-release, the same comparison runs automatically for the first hour on the real production canary, which every progressive rollout has anyway, with an automatic rollback if the thresholds are breached.

The JMH layer moves to a nightly job that bisects to the commit when it finds a regression.

The honest statement to the team is that a ten-minute release means some regressions reach production for up to an hour, and the rollback is part of the design.

"Under time pressure, what would you cut?"

Everything except a single canary comparison of p99 latency and allocation rate against the previous release, with a threshold of 15 percent and a rerun-once rule, and the differential flame graph attached to the output.

That is an afternoon of pipeline work if the canary infrastructure exists. I would defer the three-release baseline, the statistical JMH comparison, the ARM split and the noise calibration.

I would tell the team which regressions the cut version misses: slow drift under 15 percent per release, tail regressions above p99, and anything only visible under a traffic shape the replay lacks.

The one thing I would not skip is running the same build against itself once before enabling the gate, because without that I do not know whether a red result means anything.

"How do you compare two JMH results properly, rather than looking at the means?"

JMH reports the mean and a 99.9 percent confidence interval per benchmark, computed across the measurement iterations of all forks. Two results are different when the intervals do not overlap; if they overlap, the run cannot tell them apart and the gate must not fail.

For a stricter test I feed the raw per-iteration scores, which JMH writes with -rf json, into a two-sample test such as a Mann-Whitney U test, which does not assume the scores are normally distributed, and require both statistical significance and a practical difference of at least 5 percent.

Allocation from -prof gc is compared exactly, because gc.alloc.rate.norm is deterministic for the same code and inputs, so any change is a real change. And forks matter: with a single fork, one JIT compilation order decides the number, and three forks show the spread.

"How would you build the differential flame graph in the pipeline?"

Both canaries write a JFR file with jdk.ExecutionSample, or jdk.CPUTimeSample on JDK 25. A converter, async-profiler's jfrconv or a small script over jfr print --json, folds each file into collapsed stacks, one line per unique stack with a count.

The differential step normalises each file by its total samples, subtracts baseline share from candidate share per stack, and renders a flame graph coloured by the difference, red where the candidate spends more, blue where less; the FlameGraph project's difffolded.pl and flamegraph.pl do exactly this and take seconds.

The pipeline uploads the HTML as a build artefact and links it in the release.

It also feeds a machine rule: any single frame whose share moved by more than the noise threshold is listed in the gate's message, so the reviewer opens the graph already knowing which method to look at.

12 · RecapWhat You Can Do Now

  • You can trace a method from javac bytecode through loading, linking and initialisation into the interpreter, C1 and C2, name the thresholds, and explain inlining, escape analysis, inline caches and deoptimisation as mechanisms rather than words
  • You can say in one sentence why "Plugin cannot be cast to Plugin" is correct, and design a plugin loader that avoids it
  • You can state the happens-before rules, explain why the spinning-worker bug appears only after C2 compiles the loop, and pick a VarHandle access mode on purpose
  • You can describe an object's bytes, the TLAB fast path, G1's regions and mixed collections, ZGC's coloured pointers and load barriers, and read a -Xlog:gc* line and a native-memory summary
  • You can explain what a virtual thread is made of, what still pins it after JEP 491, why the connection pool is the next ceiling, and the August 2026 status of structured concurrency and scoped values
  • You can show what records, sealed types, exhaustive switches, gatherers, FFM and modules change in real code, and recite the JDK 21 to 27 roadmap with dates
  • You can collect and read a JFR recording and a flame graph, separate time-to-safepoint from a GC pause, write a JMH benchmark that does not lie, and choose between the AOT cache and native image
  • You can answer the opener, "CPU 100 percent and throughput down after a JDK upgrade", with evidence in ten minutes
🧠 Flex your memory

Close the page and write down, from memory: the four tiers a hot method passes through and the two invocation thresholds; the eight happens-before rules; the three numbers in a G1 pause line and what "to-space exhausted" means; the two things that still pin a virtual thread on JDK 25; and the difference between "Reaching safepoint" and "At safepoint". Then reach back to Chapter E1's memory chapter: which of the objects in its Library Manager lab would survive into the old generation, and which of them would the escape analysis in this chapter's section 02 be able to eliminate entirely, and why?