▚ The Software Engineer's Field Manual
Chapter E3 · Senior interview drill

Java Interview Drill — 300 Questions, Answered Properly

"A senior interview does not test whether you know the rule. It tests whether you were there when the rule was broken."

300 questions · answers collapsed For: experienced Java engineers (~9 years) prepping the senior round Heavy on: concurrency · debugging · production tuning

01 · How to use this drillSay the Answer Out Loud Before You Reveal It

Three hundred interview questions with hidden answers. The value is not in reading them — it is in committing to your own answer out loud, before you reveal theirs.

This page is a question bank for the interviews a nine-year Java engineer actually faces.

Those are the rounds that probe equals and hashCode until something breaks. That hand you a frozen service and ask what you would do first. That keep asking "why?" until they find the bottom of your understanding.

It is the senior companion to Chapter E1, which teaches Java from zero, and to the T3 skill test, which is a timed quiz.

This page is neither of those. It is a drill.

Every answer starts hidden behind a Reveal answer control. That is deliberate: the whole value of the exercise is the ten seconds where you commit to an answer before checking it.

The 300 questions come in two kinds, deliberately mixed. Direct questions test whether you can explain a mechanism clearly — "why must hashCode be overridden when equals is?". Scenario questions (marked Scenario in the question number) put you in a production incident — a thread dump, a connection-pool timeout, a query that was fast yesterday — and grade the order of your diagnosis as much as the fix. Interviewers at senior level lean hard on scenarios, because memorized definitions cannot fake a debugging sequence.

Each answer has up to three parts.

Work a section at a time. Answer aloud — really aloud; your desk does not judge. Then reveal, and compare.

Questions you could not finish go on a list you revisit two days later. That spacing is what makes them stick.

Sections 02–04 cover the language and the JVM you claim daily fluency in. Sections 05–07 are the deep end this drill exists for: memory, threads, synchronized and the monitor, and the java.util.concurrent toolkit. Section 08 is pure production debugging — thread dumps, CPU spikes, pool exhaustion. Section 09 covers tuning APIs and database access from the Java side; its database questions stop where Chapter E8 — the database operations primer with its own 200-question drill — picks up.

02 · Core languageCore Language & OOP — Q1–Q40

These forty questions are the ones a senior round uses to check that nine years of Java built understanding, not just habit. They circle the object model — what equality really means, what immutability really costs and buys, and what the modern class-design features are actually for. Every answer here carries the reasoning, because at the senior level the interviewer is grading your "why", not your recall.

Drill · equals, hashCode & identity

This group tests whether you understand what equality means to the collections that store your objects — the single most common place senior candidates reveal shallow knowledge.

Q1. "You've overridden equals on a class. Why is overriding hashCode not optional — what exactly breaks inside a HashMap if you skip it?"

Reveal answer

The real test Whether you can walk the actual bucket lookup instead of reciting "it's the contract".

Strong answer A HashMap stores entries in an array of buckets — slots of that internal array.

When you call put, it takes the key's hash code — an int summary of the object's contents — spreads its bits, and masks it with the array size minus one to pick one bucket index.

When you call get, it recomputes the hash of the key you pass, jumps to that one bucket, and only there compares candidates with equals. If I override equals but not hashCode, two logically equal objects inherit Object's identity-based hash, which is different per instance.

They land in different buckets, so get searches the wrong slot and returns null without ever calling my equals.

That is why the contract says equal objects must produce equal hash codes — the hash is the address, and equals is only consulted after the address matches.

equals without hashCode — the exact failureruns offline
class User {
    final String email;
    User(String email) { this.email = email; }

    @Override public boolean equals(Object o) {
        return o instanceof User u && email.equals(u.email);
    }
    // hashCode NOT overridden -> inherits Object's identity hash
}

var map = new HashMap<User, String>();
map.put(new User("a@x.com"), "Ann");
map.get(new User("a@x.com"));      // null

// WHY: get() computes hash(key) FIRST to pick a bucket, and only then uses
// equals() within that bucket. Two equal objects with different identity
// hashes land in different buckets, so equals() is never even called.
//
//   put: hash=0x1b6d3586 -> bucket 6   [stored here]
//   get: hash=0x4554617c -> bucket 12  [looks here, finds nothing]

// The contract that was broken: equal objects MUST have equal hash codes.
// The reverse is not required — unequal objects may collide, and that is fine.

// FIX — derive both from the same fields.
@Override public int hashCode() { return email.hashCode(); }
// or let the compiler do it:
record User(String email) { }

Read the two bucket numbers. The value is not lost and not overwritten — it is sitting in bucket 6, and the lookup is searching bucket 12, so no amount of correct equals logic can ever find it.

Land it The hash finds the bucket and equals confirms the match, so the two methods are one unit — override both or neither.

Likely follow-ups
"What if I override hashCode but not equals — what breaks then?"

Nothing breaks in the map's mechanics, but the map stops recognising logical duplicates.

Two objects with the same fields now hash to the same bucket, so they sit next to each other in the chain, but the map still compares them with Object.equals, which is reference identity.

So put with a second, equal-by-content key adds a second entry instead of replacing the first, and get with a fresh instance returns null after walking right past the stored one. It is the mirror-image bug: equal hashes, unequal objects.

The contract only forbids the other direction, so this compiles and runs without complaint, which is why I say the two methods are one unit and generate both from the same fields.

"Does the map really compare the stored hash before calling equals? Why does that matter?"

Yes. Each HashMap.Node stores the spread hash as an int field, and the lookup loop checks e.hash == hash && (e.key == key || key.equals(e.key)). The integer comparison is one instruction, while equals on a real key may compare several strings.

So in a bucket with a short chain, equals is only invoked for nodes whose full 32-bit hash matches, which for a decent hash function is almost always the one true match.

It also means the identity check e.key == key short-circuits the common case of looking up with the same instance you stored. That is why a slow equals rarely shows in profiles unless the hash function itself is poor.

"How would you catch a missing hashCode in the build rather than in production?"

Three layers. First, the compiler cannot help, so I turn on a static-analysis rule: Error Prone's EqualsHashCode check fails compilation when a class overrides one without the other, and SpotBugs reports HE_EQUALS_NO_HASHCODE.

Second, a property-style unit test with EqualsVerifier, which constructs instances, checks all five equals rules, and asserts equal objects produce equal hash codes. Third, a design rule: value types are records, which generate both methods from the same components, so the drift is impossible.

In a code review I would ask why a hand-written equals exists at all, because since JDK 16 records cover almost every value-type case.

"Does the same reasoning apply to HashSet, ConcurrentHashMap and Hashtable?"

Yes, all of them. HashSet is a HashMap underneath, so a set of keys with a broken hashCode will happily hold duplicates and report contains as false.

ConcurrentHashMap uses the same bucket-by-hash design with a different spreading function and lock striping, and Hashtable is the same idea with a modulo instead of a mask.

The one family that does not care is the sorted one: TreeMap and TreeSet ignore both hashCode and equals and use only compareTo or the comparator.

So a key class can be broken for hash maps and fine for tree maps, or the other way around, and I test both when a type is used as a key in both.

Q2. "Walk me through the equals contract. Can you show me a realistic way symmetry gets violated?"

Reveal answer

The real test Naming the five rules is junior; producing the subclassing symmetry break is senior.

Strong answer The contract has five parts, and each protects the collections that rely on it:

  • Reflexive: an object equals itself.
  • Symmetric: if x.equals(y) is true then y.equals(x) must be true.
  • Transitive: if x equals y and y equals z, then x must equal z.
  • Consistent: repeated calls give the same result unless the objects change.
  • Non-null: x.equals(null) returns false rather than throwing.

Symmetry classically breaks with inheritance. Say Point implements equals using instanceof Point and compares x and y. A subclass ColorPoint adds a color field and its equals requires instanceof ColorPoint plus a color match.

Now point.equals(colorPoint) is true, because the color point is a Point and coordinates match, but colorPoint.equals(point) is false, because a plain Point is not a ColorPoint. A List.contains call then answers differently depending on which side does the comparing.

The honest fixes are to prefer composition over inheritance for value types, use a getClass() check when subclasses must not compare equal, or make equals final in the base class.

Land it There is no clean way to add a field in a subclass and keep the contract, which is why value classes should be final — records enforce exactly that.

Likely follow-ups
"You said use getClass() instead of instanceof to keep symmetry. What does that cost you?"

It costs you Liskov substitutability.

With getClass(), a Point and a subclass instance with identical coordinates are never equal, even when the subclass adds no state, for example a subclass created only to add a helper method or a framework-generated proxy such as a Hibernate lazy-loading subclass.

That last case bites in real systems: an entity loaded through a proxy has a different runtime class from the same entity loaded directly, so getClass()-based equality says they differ.

So the trade is exact symmetry at the price of treating every subclass as a foreign type. My preference is to avoid the choice by making value classes final, or using records, so there are no subclasses to worry about.

"Can you actually break transitivity, not just symmetry?"

Yes, and the fix for symmetry usually causes it. Suppose ColorPoint.equals is made symmetric by ignoring colour when the other object is a plain Point.

Take a red point p1, a plain point p2 at the same coordinates, and a blue point p3 at the same coordinates. Now p1.equals(p2) is true because colour is ignored, p2.equals(p3) is true for the same reason, but p1.equals(p3) is false because red is not blue.

That violates transitivity, and a HashSet containing all three can hold two or three elements depending on insertion order. This is the argument in Effective Java that you cannot add a value component to an instantiable class while keeping the contract; composition is the escape.

"Why does the contract say equals(null) must return false rather than throw?"

Because collections call equals on your behalf with arguments you did not choose. List.contains(null), Collections.frequency, and Map.remove with a null argument all end up calling element.equals(null).

If that threw a NullPointerException, a perfectly legal question, "does this list contain null", would crash instead of answering no. The idiomatic implementation gets this for free: if (!(o instanceof Point p)) return false; handles null because instanceof is false for null.

What I watch for in review is a version that starts with o.getClass() without a null guard, which throws exactly the exception the contract forbids.

"How does a record's generated equals behave with floats, doubles and arrays?"

The generated method compares primitive components with the same rules as their wrapper's equals, so double components are compared with Double.compare semantics: NaN equals NaN and positive zero does not equal negative zero, which differs from the == operator. Reference components are compared with Objects.equals, and here is the trap: an array component is a reference, so two records holding different array instances with identical contents are not equal, and their hash codes differ. If a record needs array-like data, I store a List copied with List.copyOf in the compact constructor, or I override equals and hashCode explicitly using Arrays.equals and Arrays.hashCode.

Q3 · Scenario. "A teammate reports that values put into a HashMap with a custom key class 'disappear' — get returns null even though the entry prints when they iterate the map. Here's the key class. Diagnose and fix it."

Reveal answer

The real test A calm diagnosis sequence ending in the one-line root cause, not a guess.

Strong answer I would diagnose it in this order:

  1. Confirm the symptom precisely: map.get(key) and map.containsKey(key) both fail, yet iterating entrySet() shows the entry. That combination means the entry exists but lookup goes to the wrong bucket — a hashing problem, not a storage problem.
  2. Check whether the lookup key is the same instance as the stored key. If the same instance also fails, hashing is unstable; if only a new-but-equal instance fails, the two instances hash differently.
  3. Open the key class and check for hashCode. Here it is missing — equals is overridden alone, so each instance keeps Object's identity hash and equal keys scatter across different buckets.
OrderKey.java
public final class OrderKey {
    private final String customerId;
    private final long orderNo;

    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof OrderKey)) return false;
        OrderKey k = (OrderKey) o;
        return orderNo == k.orderNo
            && customerId.equals(k.customerId);
    }
    // BUG: no hashCode() — Object's identity hash is used,
    // so two equal keys land in different buckets.

    // The fix — derive it from the same fields equals uses:
    @Override public int hashCode() {
        return java.util.Objects.hash(customerId, orderNo);
    }
}

The fix is a hashCode built from exactly the fields equals compares — or better, replace the class with a record OrderKey(String customerId, long orderNo), which generates both correctly. For prevention I add a unit test asserting that two equal instances have equal hash codes, and I turn on a static-analysis check such as Error Prone's EqualsHashCode, which fails the build on this exact mistake.

a key mutated after insertionruns offline
class OrderKey {
    String region;                          // MUTABLE
    OrderKey(String region) { this.region = region; }
    @Override public boolean equals(Object o) {
        return o instanceof OrderKey k && region.equals(k.region);
    }
    @Override public int hashCode() { return region.hashCode(); }
}

var map = new HashMap<OrderKey, Order>();
var key = new OrderKey("EU");
map.put(key, order);                        // hash("EU") -> bucket 3

key.region = "US";                          // the field the hash is derived from

map.get(key);                    // null  -- looks in bucket 11, entry is in bucket 3
map.containsKey(key);            // false
map.get(new OrderKey("EU"));     // null  -- looks in bucket 3, but equals() now fails
                                 //          because the STORED key says "US"
map.size();                      // 1     -- it is still in there
map.remove(key);                 // null  -- and it cannot be removed either

// The entry is now unreachable by any key: a genuine leak in a long-lived map.

// FIXES, in order of preference:
// 1. Make the key immutable. This is the real answer.
record OrderKey(String region) { }
// 2. Derive the hash only from fields that never change (a natural id).
// 3. If it must mutate: remove(), mutate, put() again — and accept that
//    every caller has to remember, which is why 1 is better.

Note that size() still reports 1. The entry has not been deleted — it has become invisible, which is why this shows up as a slow memory leak in a cache rather than as an obvious lookup bug.

Land it "Entry visible on iteration but invisible to get" is the fingerprint of a hashing bug, and the cure is making hashCode and equals read the same fields.

Likely follow-ups
"You added hashCode and the map still misses some keys. What next?"

Then I check whether the fields are stable and whether equals and hashCode really read the same fields. First, log key.hashCode() for a failing key at insertion time and at lookup time.

If the two numbers differ for the same instance, a field it reads was mutated after insertion, which is the mutable-key bug.

If they match, I compare the field sets: a common mistake is equals comparing customerId case-insensitively while hashCode hashes the raw string, so "abc" and "ABC" are equal but hash apart.

I also check for a nullable field that Objects.hash treats as zero but equals handles differently. EqualsVerifier's test catches all three in one assertion.

"Why does the entry still show up when iterating if get cannot find it?"

Because iteration and lookup use different paths through the table. entrySet().iterator() walks the bucket array from index zero to the end and follows every chain, so it visits every stored node regardless of which bucket the node is in or what hash it carries.

get does the opposite: it computes the hash of the key you pass now, jumps straight to one bucket, and inspects only that bucket.

If the stored key's hash placed it in bucket 7 but the lookup key hashes to bucket 12, the iterator finds it and get never looks in the right place.

That asymmetry is the fingerprint I use to separate a hashing bug from a genuinely missing entry.

"Is Objects.hash the right choice for a key that is hashed on every request?"

Probably not at very high rates. Objects.hash(Object...) allocates a varargs Object[] and boxes the long orderNo into a Long on every call. On a hot path doing a few million lookups per second, that is measurable allocation and shows in an allocation profile.

The fix is either a record, whose generated hashCode uses an ObjectMethods bootstrap that hashes components without boxing, or the manual form 31 * customerId.hashCode() + Long.hashCode(orderNo).

If the key is immutable, caching the result in a field is the next step, which is what String does. I would only do the manual version after a profiler showed the boxing.

"What test would you add so this cannot regress?"

Two tests. A focused one: construct two OrderKey instances with the same values, assert they are equal, assert hashCode matches, then put one into a HashMap and assert get with the other returns the value. That test fails on exactly this bug and reads as documentation.

And a generic one: EqualsVerifier.forClass(OrderKey.class).verify(), which also checks symmetry, transitivity, null handling and that all fields participate.

I would also enable the Error Prone EqualsHashCode check so a future class with the same mistake fails to compile, and add a review rule that any hand-written equals needs a justification for not being a record.

Q4 · Scenario. "An object was used as a HashMap key, then one of its fields was updated. Now containsKey returns false for that exact same object instance. What happened, and what designs prevent it?"

Reveal answer

The real test Do you know the bucket is chosen once, at insertion, and never re-chosen when the key changes?

Strong answer Here is what happened, step by step:

  1. At put time, the map computed the key's hash from its then-current field values and filed the entry in the bucket that hash pointed to. The map stores that hash with the entry but never watches the key afterwards.
  2. The field mutation changed the values that hashCode reads, so the key now produces a different hash.
  3. containsKey computes the new hash, walks to a different bucket, finds nothing there, and returns false — even though it is the very same instance. The entry is stranded in the old bucket: unreachable by lookup, still reachable by iteration, and unremovable by remove(key), which is a slow memory leak.

To confirm it, I iterate the entries and compare each stored key's current hashCode() against the bucket it sits in, or simply log the hash before and after the suspected mutation. The correct designs, in order of preference: make the key type deeply immutable — a record or a final class with final fields — so this state cannot exist; or key the map by an immutable identifier such as the entity's id string instead of the whole object; or, if mutation is truly unavoidable, remove the entry before mutating and re-insert after, and accept that this is fragile. Prevention is a team rule that map keys and set elements are immutable, enforced in review.

Land it A HashMap files the key by value but remembers it by position, so any key whose hash can change after insertion is a latent leak.

Likely follow-ups
"Does the same failure happen with HashSet, and with TreeMap?"

Yes for HashSet, since it is a HashMap of keys: mutating an element after add strands it in the old bucket, and contains and remove both fail while iteration still shows it.

TreeMap has the same disease with a different mechanism: the entry sits in the tree where the comparator once placed it, and after mutating a sort-key field the search goes left where the node is on the right.

Both structures share the rule: whatever fields decide placement must not change while the object is inside. Only IdentityHashMap is immune, because it hashes on identity, which cannot change.

"How would you find such stranded entries in a live heap without restarting?"

Take a heap dump with jcmd <pid> GC.heap_dump /tmp/h.hprof and open it in Eclipse MAT. Using OQL I select the map's table array and for each Node compare the stored hash field with a recomputation from the key's current fields; MAT's calculator cannot call hashCode, so in practice I check the fields that feed it against the stored hash for a sample.

Faster in a running service: expose a diagnostic that iterates entrySet() and counts entries where map.get(entry.getKey()) == null. Any positive count proves stranded entries. A growing count over time proves it is a leak and tells you the rate.

"The key must be mutable for business reasons. What is the least-bad design?"

Separate identity from state. Give the entity an immutable identifier, for example a String or UUID id, and key the map by that id, leaving the mutable object as the value.

If the object truly must be the key, use a Map keyed by identity, IdentityHashMap, when "same instance" is the semantic you want.

The last resort is a discipline: every mutation goes through a method that does map.remove(key), mutates, then map.put(key, value), which is fragile because one missed path reintroduces the leak.

I would make the record-style immutable copy the default and only accept the mutable key with a written justification.

"What happens to the stranded entry on the next resize?"

Resize uses the hash stored in the node, not a recomputation, so the stranded entry moves consistently with its old hash: it goes to old index or old index plus old capacity based on the stored value.

So it stays reachable by iteration and stays unreachable by lookup. It never fixes itself and it never gets collected, because the map holds a strong reference to the key. The only ways out are clear(), iterator-based removal, or the map being discarded.

That is why I call it a leak rather than a glitch: the entry survives every resize and every garbage collection for the life of the map.

Q5. "Is returning a constant from hashCode legal? What happens to a HashMap full of such keys?"

Reveal answer

The real test Separating "satisfies the contract" from "performs acceptably" — and knowing the Java 8 treeification detail.

Strong answer It is perfectly legal. The contract only demands that equal objects produce equal hash codes, and return 42; satisfies that trivially — it never demands that unequal objects differ.

But operationally it is a disaster: every key lands in the same bucket, so the map degenerates from a constant-time structure into a scan of one long chain, and every lookup runs equals against potentially every entry.

Since Java 8, a bucket holding eight or more entries converts into a red-black tree — a self-balancing search tree — which caps the damage at logarithmic time, but only fully when the keys implement Comparable, since the tree needs some ordering to branch on.

A good hashCode therefore mixes all the significant fields so that keys spread evenly across buckets; that spread is the entire performance story of hashing.

Land it The contract is a correctness floor, not a quality bar — hashCode quality is what buys you the O(1) that made you choose a HashMap in the first place.

Likely follow-ups
"What exactly does the tree do when keys are not Comparable?"

The tree bin still forms, but it needs some total order to decide left from right. HashMap.TreeNode first orders by the stored hash; on equal hashes it checks whether the key implements Comparable of its own class via comparableClassFor and uses compareTo.

If that fails, tieBreakOrder compares class names, then System.identityHashCode. Because identity hash is arbitrary, the tree becomes balanced but meaningless for search: a lookup with a fresh equal key cannot navigate by identity, so the code falls back to searching both subtrees, which is linear again.

So with a constant hashCode and no Comparable, the tree costs memory and buys nothing.

"How would a constant or weak hash be exploited, and how did the JDK respond?"

The attack is hash flooding: an attacker who knows the hash function sends thousands of request parameters whose keys collide, so a web framework building a HashMap of parameters spends quadratic time in chains and a single request pins a CPU for minutes.

It was demonstrated against most web platforms around 2011. Java's response in JDK 8 was treeification, so a flooded bucket costs logarithmic time, plus the requirement that String implements Comparable, which makes the tree effective for the common key type.

Servlet containers also cap parameter counts, for example Tomcat's maxParameterCount defaults to 10,000. So today the defence is layered rather than relying on hash quality alone.

"How would you measure whether your real key's hashCode spreads well?"

I load a representative sample of keys and compute bucket occupancy for a table of realistic size: apply the spreading function h ^ (h >>> 16) and mask with capacity minus one, then histogram the counts.

For good hashing at load factor 0.75, most buckets hold zero or one entry and almost none hold more than three.

A JFR recording will not show this directly, but a CPU profile with time inside HashMap.getNode walking chains, or the presence of TreeNode objects in a heap dump, are the production symptoms.

A quick unit-level check is the number of distinct hash codes divided by the number of distinct keys; anything under about 0.9 for a large sample is suspicious.

"Is there any legitimate reason to return a constant hashCode?"

Only as a temporary safety net. If a class must override equals and you cannot yet decide the hash fields, a constant keeps the contract technically satisfied so nothing is silently lost from a map while you finish the design, at the cost of performance.

Some teams use it deliberately in a mutable key class where the hash fields would otherwise change, accepting linear buckets to avoid stranding entries. Both are compromises I would flag with a comment and a ticket.

In a value type, there is no reason at all: a record gives a correct, well-spread hash in one line, so a constant is a smell that says the author did not want to think about it.

Q6. "How do you actually implement hashCode — Objects.hash, a manual computation, or a record? When does the choice matter?"

Reveal answer

Strong answer My default today is a record: it generates equals, hashCode, and toString from all components, keeps them mechanically in sync when fields change, and removes the entire class of drift bugs.

When the class can't be a record, Objects.hash(field1, field2) is my next choice for readability — with the caveat that it takes varargs, so every call allocates an Object[] and boxes any primitive arguments.

In ordinary code that cost is invisible; in a genuinely hot key — one hashed millions of times per second — I switch to the manual pattern, result = 31 * result + fieldHash per field, which allocates nothing.

And if the object is immutable and hashing dominates a profile, I cache the hash in a field the way String does. The choice matters only at the hot end; everywhere else, correctness and sync with equals matter more than nanoseconds.

Land it Records for value types, Objects.hash for the rest, hand-rolled only when a profiler says the boxing shows up.

Likely follow-ups
"How does a record's generated hashCode actually work — is it Objects.hash?"

No. The compiler emits an invokedynamic instruction bootstrapped by java.lang.runtime.ObjectMethods, which at first call builds a method handle that combines the component hashes.

It reads each component through its accessor, hashes primitives with the wrapper's static method such as Integer.hashCode(int), and combines them with the 31 * result + h pattern, without allocating a varargs array or boxing.

The specification deliberately says the exact algorithm is unspecified and may change between releases, so you must never persist a record's hash code or rely on it being stable across JDK versions. That is the same rule as for String hashes crossing processes, only more explicit.

"When is caching the hash in a field safe, and how do you avoid a race?"

It is safe only when the object is immutable, otherwise the cache goes stale. The JDK's String pattern is a benign race: a plain non-volatile int hash field, computed on first call and stored.

Two threads may both compute it, but they compute the same value, and writing an int is atomic, so a reader sees either zero and recomputes or the correct value.

The subtlety is the zero sentinel: a string whose real hash is zero recomputes every time, which is why JDK 13 added a hashIsZero boolean.

If I copy the pattern I use the same trick, and I never make the field volatile because that would add a memory barrier on every read for no benefit.

"Why 31 in the manual formula?"

Two reasons from the original design. It is an odd prime, so multiplying does not lose low bits the way an even multiplier would through overflow, and different field orders produce different results.

And 31 * x can be computed as (x << 5) - x, a shift and a subtraction, which mattered on 1990s hardware; modern JITs strength-reduce it anyway. The number is not magic; 37 or 17 work as well.

What matters is the structure: multiply-then-add so that field order contributes, and combining every field that equals reads. A weaker but common mistake is to XOR fields together, which makes (a, b) and (b, a) collide and zeroes out equal fields.

"Which fields should you leave out of hashCode, and is that ever right?"

You may leave out fields that equals also ignores, and you may leave out fields that equals uses, but never include a field that equals ignores.

Excluding an equals field is legal because the contract only demands equal objects hash equal, and it is occasionally sensible when a field is very expensive to hash, such as a large byte array, while the other fields already spread well.

Including a field equals ignores breaks the contract outright: two equal objects can hash differently. The design smell I look for is a derived or transient field, like a cached formatted string, sneaking into either method.

My rule: the same explicit list of fields for both, written once.

Q7. "What is the difference between == and equals for objects, and what extra wrinkle does the String pool add?"

Reveal answer

Strong answer For objects, == compares references — it asks whether two variables point at the same object in memory — while equals asks whatever logical question the class defines, which for well-written value types means "same contents".

Strings add a wrinkle called the string pool: a table the Java Virtual Machine (JVM) keeps of unique string instances.

Every string literal in the source is placed in that pool, so two "hello" literals anywhere in the program are the same object and == happens to return true. The compiler even folds constant expressions, so "hel" + "lo" is pooled too.

But a string built at runtime — by concatenating variables, reading a request, or calling new String("hello") — is a fresh object outside the pool, and == against a literal returns false while equals returns true.

intern() asks the pool for the canonical copy of a string's contents.

Land it The pool makes == on literals accidentally correct, which is exactly why it is dangerous — the habit works right up until the first runtime-built string.

Likely follow-ups
"Where does the string pool live, and what happens if it fills up?"

Since JDK 7 the pool lives on the ordinary Java heap, not in permanent generation, so pooled strings are collected like any other object once nothing references them.

What is native is the table itself, a fixed array of buckets sized by -XX:StringTableSize, default 65,536 as of JDK 21. The table does not fill up; it degrades. Interning millions of distinct strings makes each bucket chain long and every intern call slow.

Since JDK 11 the table rehashes automatically when chains get long, so the cliff is gentler than it used to be. You can inspect it with jcmd <pid> VM.stringtable, which prints entry counts and bucket statistics.

"Is 'hel' + 'lo' really pooled, and what about a final String variable?"

Yes. The compiler folds constant expressions at compile time, and a constant expression per the language specification includes string literals, final variables initialised with constants, and concatenations of those.

So final String a = "hel"; a + "lo" == "hello" is true, because a is a compile-time constant and the whole expression folds to the literal "hello".

Remove final and the same code produces a runtime concatenation through StringConcatFactory, a new object, and == is false. You can prove it with javap -c: the folded case shows a single ldc "hello" instruction.

This is why I say == on strings works until the first change in how a value was built.

"Does the JIT ever turn equals into a reference comparison for you?"

Partly. String.equals is an intrinsic in HotSpot: the JIT replaces the Java method with hand-written machine code that first checks reference equality, then length, then compares the byte arrays with vector instructions.

So calling equals on the same instance is nearly free, and comparing two different strings of different length is a couple of instructions.

This is why the "use == for speed" argument is wrong: the correct call is already as fast as the incorrect one in the identical-reference case, and correct in every other case.

The only cost equals adds is the null-check on the receiver, which the constant-first idiom "x".equals(s) makes safe.

"How do the compact strings changes affect any of this?"

They do not change semantics, only memory. Since JDK 9, String stores its characters in a byte[] with a coder flag: one byte per character for Latin-1 content, two for anything else.

That halves the footprint of typical ASCII-heavy heaps and is on by default with -XX:+CompactStrings. equals compares coders first and then the byte arrays, so mixed-coder strings are unequal immediately. The pool and intern work exactly as before.

The practical point for an interviewer is that a string's memory cost is now about 24 bytes for the object plus 16 plus length bytes for the array, which matters when you are deciding whether interning or deduplication is worth doing.

Q8 · Scenario. "A String comparison using == passes every unit test but fails intermittently in production. How is that possible, and how do you hunt it down?"

Reveal answer

Strong answer This is the string pool masking a reference comparison. My walk-through:

  1. Explain the mechanism first: the unit tests compare literal against literal — assertX("ACTIVE" == status) where status was also assigned from a literal — and both literals resolve to the same pooled instance, so == passes. In production the same value arrives built at runtime: parsed from a JSON payload, read from a database driver, produced by substring or concatenation. Those are fresh objects, so == compares two different references holding identical characters and returns false.
  2. Confirm it at the failure site by logging both the values and System.identityHashCode of each side — same text, different identity numbers proves the diagnosis in one log line.
  3. Fix it with equals, written as "ACTIVE".equals(status) — constant first, so a null status yields false instead of a NullPointerException — or Objects.equals(a, b) when both sides can be null.
  4. Prevent recurrence with static analysis: Error Prone's StringEquality check and the equivalent SonarQube rule flag every reference comparison of strings, and I would enable one of them in the build rather than rely on review.

Land it Tests exercised the pool, production exercised the heap — the bug was in the comparison operator all along, and a build-time check closes the class of bug, not just the instance.

Likely follow-ups
"The fix shipped and the same endpoint still fails sometimes. What now?"

Then either the fix did not reach the failing comparison, or there is a second comparison with the same bug.

I search the whole codebase for == and != between String operands, including inside switch-like ladders and assertions, using Error Prone's StringEquality as the search tool rather than eyeballing.

I also check enums built from strings: Status.valueOf(s) is fine, but a hand-written lookup that compares names with == is the same bug.

Then I verify in production with a canary: log System.identityHashCode on both sides at the comparison, and confirm failures now only occur when the text differs. If they still occur when text matches, a comparison is still using references.

"Why did the tests pass — what specifically about test code produces pooled strings?"

Test fixtures are usually literals, and every literal compiles to an ldc instruction that resolves to the pooled instance. A test that sets order.setStatus("ACTIVE") and then asserts against "ACTIVE" compares the same object with itself.

Even a test that reads JSON can pass, because some JSON libraries intern short field names, and Jackson's InternerFactory historically interned property names, though not values. Production input comes from new String(bytes, UTF_8), from JDBC drivers, from substring, all fresh objects.

The lesson I draw is to build at least one test that deserialises real input, because literal-only tests cannot exercise this path at all.

"What are the concrete pitfalls of the constant-first equals idiom?"

It hides a null that might be a bug. "ACTIVE".equals(status) returns false for a null status, which is safe for a comparison but can mask a missing value that should have failed loudly upstream.

So I use it where null legitimately means "not that value" and use Objects.equals where both sides can be null and null should equal null. For comparisons that must reject null, I prefer Objects.requireNonNull(status) at the boundary and then plain status.equals(...).

Case-insensitive comparisons need equalsIgnoreCase, and locale-sensitive text should go through a Collator, because equals compares code units, not what a user would consider the same word.

"Could intern() have been the fix instead?"

It would make the symptom disappear and leave the bug in place.

Interning every incoming value forces it into the pool so == against the literal becomes true, but now every request pays a hash-table lookup in the string table, the table grows with every distinct value you ever see, and the first code path that forgets to intern reintroduces the failure.

It also spreads the assumption "strings are compared by reference" further through the codebase. So no: the fix is equals at the comparison, and interning is a memory tool for closed sets of values, not a correctness tool.

I would say that explicitly in the incident review so nobody proposes it as a quick patch.

Q9 · Scenario. "This code prints true for 100 and false for 1000 when comparing two Integer variables with ==. Explain exactly why."

Reveal answer

Strong answer The mechanism is the Integer cache behind autoboxing — the compiler's automatic wrapping of a primitive int into an Integer object. Boxing compiles to Integer.valueOf(int), and that factory keeps a cache of pre-built objects for the values −128 through 127.

So two variables boxed from 100 receive the same cached instance, and ==, which compares references, happens to return true. Boxing 1000 falls outside the cache, so each side gets a freshly allocated Integer, and == compares two distinct objects and returns false.

The upper bound is even tunable with -XX:AutoBoxCacheMax, which means the failure threshold can differ between environments — a genuinely nasty property. The same small-value caches exist for Long, Short, Byte, and Character.

The fix is to compare wrappers with equals, or unbox to primitives and compare those.

the Integer cache boundaryruns offline
Integer a = 100,  b = 100;
Integer c = 1000, d = 1000;

System.out.println(a == b);   // true
System.out.println(c == d);   // false          <- the surprise
System.out.println(c.equals(d)); // true

// WHY: autoboxing calls Integer.valueOf(int), which returns a CACHED instance
// for values in [-128, 127]. Inside that range both variables reference the
// SAME object, so == compares identical references. Outside it, valueOf
// allocates a new Integer each time, so == compares two distinct objects.

// Roughly what valueOf does:
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];   // shared
    return new Integer(i);                                     // fresh
}

// The upper bound is tunable, which makes this even more treacherous —
// the same code can behave differently on two JVMs:
//   -XX:AutoBoxCacheMax=10000     // now c == d is true

// Long, Short, Byte and Character cache the same range. Boolean and the small
// Character values are always cached. Float and Double never are.

// THE RULE: never use == on boxed types. Use equals, or better, do not box —
// use int where you can, and Objects.equals when a value may be null.

The tunable cache is the reason this is dangerous rather than merely surprising. Code that works on a JVM with an enlarged cache fails on a default one, so the bug can be introduced by a deployment change rather than a code change.

Land it The cache is a memory optimization that leaks into identity semantics — correct code never lets == touch a wrapper type.

Likely follow-ups
"Which flag changes the cache, and what does changing it actually do?"

The HotSpot flag is -XX:AutoBoxCacheMax=<n>, which sets the system property java.lang.Integer.IntegerCache.high. It only raises the upper bound of the Integer cache; the lower bound stays at −128, and the flag has no effect on Long, Short, Byte or Character, whose caches are fixed.

Setting it to, say, 20,000 makes Integer.valueOf return cached instances for that whole range, which reduces allocation in code that boxes small counters but costs about 20,000 objects at startup.

The dangerous part is that it changes == outcomes between environments: a test box with the flag and a production box without will disagree on Integer.valueOf(1000) == Integer.valueOf(1000).

"Does new Integer(100) behave the same way?"

No. The constructor always allocates a fresh object and bypasses the cache, so new Integer(100) == new Integer(100) is false even inside the cached range.

That constructor has been deprecated since JDK 9 and marked for removal since JDK 16, precisely because it defeats the cache and because Project Valhalla wants wrapper classes to become value classes with no identity at all.

Compiled code should use Integer.valueOf or rely on autoboxing, which compiles to valueOf.

As of Aug 2026 the JDK still emits a compile warning rather than an error, but the direction is clear: identity of wrapper objects is something you must not depend on in either direction.

"How would you find every == on a wrapper type in a large codebase?"

With a compiler plugin rather than grep, because the operand types are what matter and grep cannot see types. Error Prone's ReferenceEquality check flags == between reference types that override equals, which includes all the wrappers, and its BoxedPrimitiveEquality check targets exactly this case.

SonarQube's rule S4973 and IntelliJ's "Number comparison using ==" inspection do the same. I would run it once in report mode to get the count, fix the hits, and then enable it as an error so the build fails on new ones.

For a legacy codebase with hundreds of hits, the mechanical fix is Objects.equals(a, b) or unboxing to primitives where nulls are impossible.

"Why does the cache exist at all — is it just an optimisation?"

It exists because the language specification requires it.

Section 5.1.7 of the specification says boxing of values in the range −128 to 127 for int, short, byte, and char up to 127, plus booleans, must yield identical references, so that programs boxing small common values do not allocate.

Above that range the behaviour is deliberately left to the implementation, which is why HotSpot can extend it with a flag.

So the cache is a specified guarantee at the low end and an implementation detail above, and the only correct posture for application code is to compare wrappers with equals or unbox, treating the guaranteed part as a memory optimisation you do not observe.

Q10 · Scenario. "Production shows a NullPointerException on a line that contains only a ternary expression assigning to an Integer — no method call, no field access in sight. What's going on?"

Reveal answer

The real test Knowing that the conditional operator can insert a hidden unboxing call.

Strong answer This is auto-unboxing hidden inside the conditional operator. My reasoning:

  1. Read the line, say Integer result = ok ? 42 : cachedValue; where cachedValue is an Integer that can be null. The two branches have different types — one is a primitive int, the other a wrapper Integer.
  2. The language resolves that mismatch with numeric promotion: when one operand is int and the other Integer, the whole expression's type becomes int, so the Integer branch must be unboxed by an invisible intValue() call. If that branch is chosen and holds null, null.intValue() throws the NullPointerException — on a line with no visible dereference. Running javap -c on the class shows the injected Integer.intValue() instruction and proves it.
  3. The fix is to make both operands the same reference type so no unboxing happens — ok ? Integer.valueOf(42) : cachedValue — or to handle the null explicitly before the ternary. The sibling bug to mention is int x = map.get(key); throwing when the key is absent, for the identical reason.

Prevention: keep nullable values in wrapper types end to end, and let the IDE's "unboxing of nullable expression" inspection flag these at write time.

Land it Mixing int and Integer in one ternary silently votes for the primitive, and null loses that vote at runtime.

Likely follow-ups
"How exactly does the JVM tell you it was an unboxing NPE rather than something else?"

Since JDK 14, helpful NullPointerException messages are on by default, controlled by -XX:+ShowCodeDetailsInExceptionMessages. The message for this case reads something like: Cannot invoke "java.lang.Integer.intValue()" because "cachedValue" is null.

That names the injected intValue() call and the variable that held null, so you no longer need javap to see the hidden dereference.

If the message says because the return value of "Map.get(Object)" is null, it is the sibling bug of assigning a map lookup to a primitive.

The feature works only for NPEs the JVM raises itself, not for explicit throw new NullPointerException(), and it needs the class compiled with local variable names for the friendliest wording.

"What are the other places where unboxing hides in plain sight?"

The ones I check in review: assigning map.get(k) or Optional.orElse(null) to a primitive; comparing a wrapper with <, >, or == against a primitive, since relational operators unbox; a switch on an Integer expression, which unboxes the selector; arithmetic such as total += item.getQuantity() when the getter returns Integer; and for (int x : listOfInteger), which unboxes each element.

Streams add mapToInt(Item::getQty) where the method returns a wrapper. Each compiles to an invisible intValue(). The common factor is a nullable wrapper meeting a primitive context, and the fix is always the same: decide what null means and handle it before the conversion.

"Why did the language promote to int instead of boxing 42?"

Because the conditional operator's typing rules in the specification, section 15.25, say that when one operand is a primitive numeric type and the other is a boxed numeric type, binary numeric promotion applies and the result is the primitive type.

The designers chose that for consistency with arithmetic, where int + Integer is an int, and so that cond ? 1 : someInteger could be used directly in numeric contexts. The consequence is that Integer x = cond ? 42 : maybeNull boxes after unboxing, which is both the NPE and a wasted allocation.

When I write ternaries with mixed types I make both branches reference types, or I hoist the null decision into an if.

"Can a static tool catch this before it ships?"

Yes, if the nullability is declared. IntelliJ's inspection "Unboxing of nullable expression" fires when the wrapper is annotated @Nullable or comes from a method known to return null, such as Map.get.

NullAway and the Checker Framework's nullness checker do the same at build time when the codebase uses JSpecify annotations, which as of Aug 2026 are the emerging standard with support in Spring Framework 7 and Guava.

Without annotations, tools can only guess, so the practical answer is to adopt @NullMarked at the package level so unannotated types are non-null by default, and annotate the few nullable returns. Then this ternary becomes a compile-time error rather than a production NPE.

Drill · Immutability, Strings & the value model

This group tests whether you can build objects that cannot go wrong — and whether you know what the language really does with values, references, and static state.

Q11. "Design a truly immutable class for me. What's on your checklist beyond 'make the fields final'?"

Reveal answer

Strong answer My checklist has five items, and each closes a specific hole:

  • Declare the class final — or make constructors private behind static factories — so no subclass can add mutable state or override methods to lie about the state.
  • Make every field private final and provide no setters, so state is assigned exactly once, in the constructor.
  • Take a defensive copy — my own private duplicate — of every mutable constructor argument such as a List, array, or Date, so a caller who keeps their reference cannot mutate my insides later.
  • Never return a mutable internal directly from a getter: return a copy, or an immutable snapshot like List.copyOf.
  • Never let this escape during construction — no registering with listeners, no starting threads from the constructor — so nobody observes a half-built object.

Final fields also carry a memory-model guarantee: once the constructor completes, any thread that sees the object sees those fields fully initialized.

Land it Immutability is a perimeter, not a keyword — the class is only immutable if state can neither leak in nor leak out.

Likely follow-ups
"Why is it not enough to make the class final — what does a subclass actually do to you?"

A subclass can add its own mutable fields and override methods, and because callers hold the parent type, they cannot tell.

A MutablePoint extends Point that overrides getX() to return a changing field passes every instanceof Point check and defeats every cache and every map that relies on Point being stable. That is why String, the wrappers, and records are all final.

The alternative of private constructors plus static factories gets the same protection while also letting you return cached instances or subtypes you control, which is what List.of does. Either way the goal is that "this object is a Point" implies "this object cannot change".

"How does the final-field guarantee break if 'this' escapes the constructor?"

The memory model's final-field rule only covers references obtained after the constructor completes.

If the constructor publishes this early, for example by registering itself as a listener or by starting a thread that reads its fields, another thread can obtain the reference before the constructor's writes are complete and see default values in final fields, zero or null.

The freeze action happens at the end of the constructor, so anything that leaks before that point is outside the guarantee. Common accidental escapes are calling an overridable method from the constructor, capturing this in a lambda passed elsewhere, and inner classes created in the constructor. My rule: a constructor assigns fields and validates, nothing else.

"What does immutability cost at scale, and when do you give it up?"

It costs allocation: every "change" is a new object, so a hot loop that builds a large value by repeated withers allocates once per step, and the garbage collector pays.

With a young generation that is mostly short-lived objects the cost is usually small, because allocation is a pointer bump and dead objects are free to collect.

It becomes a problem for large structures modified incrementally, where each copy is O(n); there I use a mutable builder inside a method and freeze at the end, which is the StringBuilder pattern, or a persistent data structure that shares unchanged parts.

I give up immutability only inside a confined scope with a measured allocation profile, never for a type that crosses threads.

"Does a record satisfy the whole checklist automatically?"

Most of it. A record is final, its fields are private final, and there are no setters, so items one and two come free.

It does not defensively copy for you, so a record with a List component is only shallowly immutable: the caller's list reference is stored as-is and the accessor returns it.

The compact constructor is where I add items = List.copyOf(items), and for arrays I would rather avoid the component entirely. Records also cannot escape this from the canonical constructor in the usual way, because the compact form runs before fields are assigned.

So the record gives the skeleton and the compact constructor is the one place the perimeter must still be written by hand.

"Is Date really mutable? What replaces it?"

Yes: java.util.Date has setTime, and Calendar is worse. Storing a Date passed by the caller means they can move your timestamp later.

The replacement since JDK 8 is java.time: Instant, LocalDate, ZonedDateTime and friends are all immutable, thread-safe, and return new instances from every plus or with call, so they need no defensive copy at all.

The same substitution applies to other legacy mutables: use List.copyOf instead of storing an ArrayList, Map.copyOf for maps, and String instead of a StringBuilder field.

Every field of an immutable type removes one copy from the checklist, which is the practical reason to prefer immutable types for fields.

Q12. "Why do we say immutable objects are inherently thread-safe? What does the memory model actually guarantee for them?"

Reveal answer

Strong answer Thread-safety problems come from one source: two threads where at least one is writing shared state.

An immutable object removes the writes — after construction there is nothing to change — so any number of threads can read it with no locks, no volatile, and no coordination, and every read is trivially consistent.

The memory model adds the crucial second half: safe publication, meaning the guarantee that another thread sees the object fully built rather than half-constructed.

For a properly constructed object whose state is in final fields, the model guarantees that once the constructor finishes, any thread that later obtains a reference sees the final fields' correctly initialized values.

That is why immutable objects can be shared through plain fields, cached freely, and used as map keys without a synchronization strategy — the object itself is the strategy.

Land it Every concurrency bug needs a mutation to exist, so designing the mutation away is the cheapest concurrency control there is.

Likely follow-ups
"What if the fields are not final — is the object still safely published?"

Not by construction alone. A non-final field written in the constructor is an ordinary write, and the memory model gives no ordering between that write and another thread's read of the reference unless something creates a happens-before edge.

So a second thread can see the reference and then see the field as zero or null.

To publish such an object safely you need one of the standard mechanisms: store the reference in a volatile field, publish it through a lock, hand it through a concurrent collection such as ConcurrentHashMap, or pass it to a thread at thread start.

That is why "immutable" in the strict sense requires final fields, and why an effectively immutable object with plain fields still needs a safe-publication idiom.

"Is an immutable object holding a reference to a mutable one still thread-safe?"

The holder is, the referent is not, and the final-field guarantee extends only as far as the constructor's reachable writes.

Formally, the freeze covers everything reachable from the final field that was written before the constructor finished, so a final int[] filled in the constructor is seen fully initialised. But if any thread later mutates that array, all bets are off again.

So a class with a final List field is only thread-safe if the list itself is never modified after construction, which is why I copy into List.copyOf.

The rule: immutability is transitive in practice only if every reachable object is also immutable or is never touched after publication.

"How do you verify safe publication is actually happening in production?"

You mostly cannot observe it directly, because the failures are timing-dependent and rare on x86, whose memory model is strong.

The honest approach is to test the code with the tool built for it: jcstress, the OpenJDK concurrency stress harness, runs a small publication scenario millions of times across cores and reports whether any run observed a half-built object.

It reproduces on ARM machines, which is relevant now that Graviton and Apple silicon are common deployment targets, since ARM allows more reordering than x86.

In review I look for the structural evidence instead: final fields, no this escape, and a volatile or lock at the hand-off point when fields are not final.

"Why does 'immutable means no locks' still leave room for a race?"

Because the race moves to the reference. If a configuration object is immutable and a service holds it in a plain field that is swapped on reload, readers may see a stale version indefinitely, which is a visibility problem, not a corruption problem.

Make the field volatile or use an AtomicReference, and every reader sees the latest complete object atomically. And check-then-act on two immutable values is still a race: reading limits and then pricing from two separate fields can observe an old limit with a new price.

The fix is to bundle both into one immutable snapshot and swap that single reference. Immutability removes torn objects; it does not remove torn reads across several references.

Q13. "Why was String designed to be immutable? Give me the real engineering reasons, not just 'safety'."

Reveal answer

Strong answer Four concrete reasons, each load-bearing. First, security: strings carry class names to class loaders, file paths, and hostnames — if a string could change after a permission check but before use, every such check would be a race.

Second, the string pool only works because strings can't change: the JVM can hand the same "ACTIVE" instance to a thousand call sites only if none of them can edit it under the others.

Third, hash caching: String computes its hash code once and stores it in a field, which is only sound because the contents never change — and it is a big part of why strings make fast map keys.

Fourth, free thread safety: strings cross thread boundaries constantly, and immutability means they need no synchronization anywhere. The cost is that every "modification" allocates a new string, which is exactly why StringBuilder exists for construction-heavy code.

Land it String immutability trades write-time allocation for the right to share, cache, and trust every string in the process — a trade the whole platform is built on.

Likely follow-ups
"Is a String really immutable — can reflection change it?"

Historically yes, and that door is now closed.

Before JDK 9 you could reflect on the private value field, call setAccessible(true), and overwrite the character array, changing a pooled literal for the whole JVM. Since strong encapsulation of the JDK became the default in JDK 16, java.lang is not opened to unnamed modules, so setAccessible throws InaccessibleObjectException unless you start with --add-opens java.base/java.lang=ALL-UNNAMED.

So immutability of String is now guaranteed by the module system, not just by convention. The JIT also relies on it: constant folding of String.length() and stable-array optimisations on the value field are only sound because nobody can write to it.

"Where does the hash cache live and what happens on the first call?"

Two fields on String: an int hash and, since JDK 13, a boolean hashIsZero.

The first call to hashCode computes the polynomial hash over the bytes and stores it; if the computed value is zero it sets hashIsZero instead, so a zero-hash string does not recompute forever. Later calls return the field.

The write is unsynchronised and that is fine: it is an idempotent write of an int, which is atomic, so a racing reader either recomputes or sees the correct value.

The effect is that a string used as a map key is hashed exactly once for its lifetime, which is a large part of why string-keyed maps are fast.

"How does immutability enable the JVM's own string optimisations?"

Several depend on it. The string table can share one instance across the whole process only because no site can change it.

substring once shared the backing array, and even now the JIT can eliminate a String allocation entirely through escape analysis when it proves the object never leaves a method, which requires that nothing could have mutated it in between.

G1's string deduplication can silently replace one string's byte[] with another identical array, which is only safe because the array will never be written. And @Stable-style trust on the value field lets the compiler treat a loaded string length as a constant. Each of those is unsound the moment a string can change.

"What would break if String became a value class under Valhalla?"

Very little in principle, because String is already designed to have no meaningful identity.

Value classes, which as of Aug 2026 have not shipped as a final feature, drop identity: == compares contents, synchronising on an instance is illegal, and the JVM may flatten or copy instances freely.

Code that synchronises on a string, which is already a known anti-pattern because pooled literals are shared locks across libraries, would fail. Code using == on strings would start being accidentally correct, which is not a reason to write it.

The JDK team has said String is a candidate but that the migration is delicate because so much code observes identity via System.identityHashCode.

Q14 · Scenario. "A report job that concatenates rows into one big String with += now takes eight minutes on large inputs. Why is it slow — doesn't the compiler already optimize string concatenation?"

Reveal answer

Strong answer The compiler optimizes each expression, not the loop, and that distinction is the whole bug:

  1. Establish what += does: strings are immutable, so report += row allocates a brand-new string and copies every character of the old report plus the new row into it. On iteration number n, that copy is proportional to everything accumulated so far.
  2. Do the arithmetic: total work grows with the square of the output size. Concatenating 100,000 rows of about 100 characters copies on the order of half a trillion characters across the run — that is where the eight minutes live, mostly in copying and garbage collection of the discarded intermediates.
  3. Answer the compiler question honestly: javac does optimize any single concatenation expression — since Java 9 it compiles a + b + c to one efficient invokedynamic call, and before that to a StringBuilder chain. But each loop iteration is a separate expression, so each iteration still builds a fresh string from scratch; no compiler removes the cross-iteration copying.
  4. Fix: create one StringBuilder before the loop, ideally pre-sized with an estimated capacity, append in the loop, and call toString() once at the end — turning quadratic work into linear. For joining with delimiters, String.join or Collectors.joining reads even better. StringBuffer is only the legacy synchronized variant and isn't needed here.
why String += in a loop is quadraticruns offline
// BROKEN — eight minutes for 50,000 rows.
String report = "";
for (Row r : rows) {
    report += r.toCsv() + "\n";      // NOT one append: a full copy, every time
}

// javac compiles each += into a fresh StringBuilder, because String is immutable:
//   report = new StringBuilder().append(report).append(r.toCsv()).toString();
//
// So iteration n copies the whole accumulated string of length L(n).
// Total work = 1 + 2 + 3 + ... + n  =  O(n^2) character copies.
// 50,000 rows of ~100 chars ~= 12.5 BILLION character copies, plus 50,000
// intermediate String objects for the GC.

// FIXED — one buffer, amortised O(n).
var sb = new StringBuilder(rows.size() * 100);   // pre-size it if you can
for (Row r : rows) {
    sb.append(r.toCsv()).append('\n');
}
String report = sb.toString();

// Or, for a stream:
String report = rows.stream().map(Row::toCsv).collect(joining("\n"));

// NOTE: += is perfectly fine OUTSIDE a loop. Since JDK 9, invokedynamic and
// StringConcatFactory make a single concatenation expression very efficient,
// often better than a hand-written StringBuilder. It is the LOOP that is fatal.

The distinction matters in review. Rejecting every + on strings is wrong — a single concatenation is optimised well by the JIT. The rule is specifically about accumulating across iterations, where each step copies everything that came before.

Land it The compiler optimizes within an expression, never across loop iterations — the moment concatenation sits in a loop, the builder is your job.

Likely follow-ups
"The StringBuilder fix shipped and it is still slow. What next?"

Then the quadratic copying is gone and something else dominates, so I profile rather than guess.

First I check the builder's growth: an unsized StringBuilder starts at 16 characters and grows by doubling plus two, so a 200 MB report still copies about 28 times, which is linear overall but allocates humongous arrays that stress G1; presizing with an estimate fixes that.

Second, the per-row work: if each row does its own formatting through String.format, that call parses the format string every time and is often ten times slower than concatenation.

Third, the output: building the whole report in memory and then writing it is itself the problem at that size, so I stream rows to a BufferedWriter and never hold the full string.

"What does the invokedynamic concatenation actually do, and can you turn it off?"

Since JDK 9, javac compiles a + b + c to one invokedynamic instruction bootstrapped by StringConcatFactory.

At first execution the JVM builds a method handle specialised for those argument types that computes the exact final length, allocates one byte[], and writes each piece directly into it, with no intermediate StringBuilder and no resizing.

That is faster than the old builder chain and it also means the strategy can improve in a JDK update without recompiling.

You can go back to the old code with javac -XDstringConcat=inline, which some teams did early on to reduce startup cost from bootstrap, but on modern JDKs the indy path is the right default.

"Why did garbage collection show up in the profile at all?"

Because each += creates a string whose byte array is the full accumulated size, and once that exceeds half a G1 region, by default regions are 1 to 32 MB depending on heap size, it is a humongous object allocated directly in the old generation.

Thousands of humongous allocations per second fragment the heap and force frequent concurrent cycles or even full collections, so GC time balloons even though the live set is small. The symptom in GC logs, enabled with -Xlog:gc*, is "Humongous Allocation" as the pause cause.

That is why the quadratic copy shows up twice: once as CPU in System.arraycopy, and again as GC pauses cleaning up the discarded intermediates.

"When would String.join or Collectors.joining be the wrong tool?"

When the pieces are not already strings, or when the output is too large to hold. String.join and Collectors.joining both build one StringBuilder internally and are linear, so for a list of ready-made strings they are ideal.

But if each piece must be formatted first, mapping every row to a string and then joining doubles the allocation compared with appending formatted values straight into one builder.

And both return a single string, so for a multi-gigabyte export they fail on the 2 GB array limit or exhaust the heap.

There the tool is a Writer with buffering, writing each row as it is produced, or a streaming CSV or JSON generator that never materialises the whole document.

Q15. "Is Java pass-by-value or pass-by-reference? Prove your answer with the classic swap method."

Reveal answer

Strong answer Java is strictly pass-by-value, always. The subtlety is what the value is: for primitives it is the number itself, and for objects it is the reference — the handle that points at the object — copied into the method's parameter.

That single rule explains both behaviors people find confusing. A method can call list.add(x) and the caller sees the change, because both the caller's variable and the parameter point at the same object; mutation travels through the copied reference.

But swap(a, b) written as Type tmp = x; x = y; y = tmp; does nothing to the caller, because it only reassigns the method's own copies of the references — the caller's variables never rebind.

If Java were pass-by-reference, that swap would work, as it does in C++ with reference parameters. It never does in Java.

pass-by-value, proved with the classic swapruns offline
static void swap(Object a, Object b) {
    Object t = a; a = b; b = t;     // reassigns the LOCAL COPIES of the references
}

var x = new StringBuilder("x");
var y = new StringBuilder("y");
swap(x, y);
System.out.println(x + " " + y);    // "x y"  -- unchanged. Swap is impossible.

// Java is ALWAYS pass-by-value. For an object, the VALUE being copied is the
// reference. So the method gets its own copy of the arrow, pointing at the
// same object. Repointing that copy cannot affect the caller's arrow.

// This is why MUTATION works and REASSIGNMENT does not:
static void mutate(StringBuilder sb) { sb.append("!"); }   // follows the arrow
static void reassign(StringBuilder sb) { sb = new StringBuilder("new"); }  // no effect

var s = new StringBuilder("hi");
mutate(s);     System.out.println(s);   // "hi!"   -- the OBJECT changed
reassign(s);   System.out.println(s);   // "hi!"   -- the caller's reference did not

// If Java were pass-by-reference, swap() would work — that is the whole test.

The single sentence that settles it: the object is not passed, and the reference is not passed — a copy of the reference is passed. Everything else in this question follows from that.

Land it Mutating through a parameter reaches the caller's object; reassigning the parameter never reaches the caller's variable — that asymmetry is the proof.

Likely follow-ups
"So how do you actually write a swap that the caller sees?"

You give the method something it can mutate in place. Pass an array and swap its two slots: void swap(int[] a, int i, int j) exchanges the contents, and the caller sees it because both sides refer to the same array object.

Or return a new pair: a record Pair(A first, B second) with a method returning new Pair(second, first) and let the caller reassign. Or use a mutable holder such as AtomicReference when the value must be shared.

What you cannot do is rebind the caller's local variables from inside a callee, and I would say in the interview that this limitation is a feature: it means a method can never silently change which object my variable points at.

"Where does this distinction cause real bugs in production code?"

The classic one is a builder or helper that does list = new ArrayList<>(list); list.add(x); intending to append to the caller's list, and the caller sees nothing because the parameter was rebound to a copy.

The mirror bug is the opposite assumption: passing a list to a method that "just reads" it and finding it sorted or cleared afterwards, because mutation through the copied reference does reach the caller.

A third is String helpers: s = s.trim() inside a method has no effect on the caller's variable, and people expect it to.

Each one is the same confusion about what was copied, and the fix is usually to return the new value explicitly rather than trying to modify through a parameter.

"Does the JIT ever pass an object by value, like a struct?"

Yes, invisibly. Escape analysis can prove that an object allocated in a method never escapes it, and then scalar replacement keeps its fields in registers with no heap object at all, so the "reference" you think you passed never existed at runtime.

That is an optimisation that preserves the language semantics exactly, so you cannot observe it except through allocation profiles.

Project Valhalla's value classes, still not a final feature as of Aug 2026, will make this explicit: instances without identity can be flattened into arrays and passed in registers.

Even then the language stays pass-by-value; what changes is that the value being copied can be the whole object rather than a pointer to it.

"What about the this reference and varargs — any surprises?"

Two small ones. this is passed as a hidden first argument by value, and it is effectively final: you cannot reassign it, so a method cannot make its receiver point elsewhere.

Varargs are passed as a single array reference, so a method that sorts or modifies its varargs array modifies an array the caller may have passed explicitly, which is why Arrays.asList(array) writes through to the caller's array.

And a lambda captures variables by copying their values at creation, which is why they must be effectively final: it is pass-by-value applied to capture.

All three are consequences of the one rule, and they are the examples I use to show the rule is not an abstraction but a mechanical fact.

Q16. "What's the difference between final and effectively final, and where does effectively final actually matter?"

Reveal answer

Strong answer final is an explicit, compiler-enforced promise of single assignment — on a local or field it means "assigned exactly once", on a method "cannot be overridden", on a class "cannot be subclassed".

Effectively final applies only to local variables and parameters: a variable that has no final keyword but is never reassigned after initialization, which the compiler can verify and treat as if it were final. It matters in exactly one place: capture.

Lambdas and anonymous classes may only capture local variables that are final or effectively final, so since Java 8 you no longer need to sprinkle final on locals just to use them in a callback — you only hit the rule when you try to reassign a captured variable and the compiler refuses.

One important caveat to say out loud: final on a reference freezes the binding, not the object — a final List can still be added to.

Land it Effectively final is the compiler meeting you halfway — the capture rule stays, the keyword ceremony goes.

Likely follow-ups
"Does adding final to a local variable change the bytecode or performance?"

No. The class file has no flag for a final local; the keyword is a compile-time check that vanishes after javac.

The one bytecode-visible effect is constant folding: a final int x = 5 initialised with a constant expression becomes a compile-time constant, so uses of x are inlined as the literal 5, and the same for final String constants.

That is why changing a public static final constant in a library requires recompiling its clients, since they baked the value in. For fields, final does matter: it enables the memory-model freeze and lets the JIT treat static finals as constants after class initialisation. For locals it is purely documentation and a guard against reassignment.

"Why did the language not just let lambdas capture mutable locals like some languages do?"

Because Java lambdas can run on other threads, and capturing a mutable local would be shared mutable state without any synchronisation, disguised as a plain variable.

Languages that allow it, such as C# or JavaScript, box the variable on the heap so both the method and the closure share one cell, and they mostly run closures on the same thread.

Java's designers chose to copy the value and forbid reassignment so the copy can never disagree with the original, and so a parallel stream cannot corrupt a counter by accident.

If you genuinely need mutable shared state, you say so explicitly with AtomicInteger or a mutable object, which makes the sharing visible in review.

"The compiler rejected my lambda with 'must be final or effectively final' but the variable is only assigned once. Why?"

Usually because it is assigned once in the source but not definitely assigned exactly once by the rules.

A variable declared without an initialiser and then assigned in both branches of an if is fine, but one assigned in a loop body is reassigned on each iteration, and one that is incremented anywhere, even after the lambda, loses the property.

The compiler checks the whole scope, not just the lines before the capture.

The fix is to copy the current value into a fresh local right before the lambda, final var snapshot = value;, which is the one honest way to capture "the value at this moment".

Loop variables in an enhanced for are already effectively final per iteration, which is why they capture cleanly.

"Does effectively final apply to fields or to the object a variable points to?"

Neither. It is a property of local variables and parameters only; fields are captured through this and read live, so a lambda in an instance method sees field updates made after the lambda was created.

And it says nothing about the referenced object: a captured effectively final List can still be added to inside the lambda, and doing that from a parallel stream is a data race. So the rule guards the variable binding, not the state.

In review I look for lambdas mutating captured collections or fields and ask whether the code runs on one thread; if it might not, the mutation must move into a collect or a concurrent structure.

Q17 · Scenario. "A static field is null when read, even though its initializer clearly assigns it — the stack trace is an ExceptionInInitializerError. Here's the trimmed class. What's happening?"

Reveal answer

The real test Do you know static initializers run top to bottom, once, and can observe each other half-done?

Strong answer This is a static initialization ordering bug. My diagnosis path:

  1. Decode the error: ExceptionInInitializerError means the exception happened during class initialization — the one-time phase where the JVM runs a class's static field initializers and static blocks, strictly in source order, the first time the class is actively used.
  2. Read the class in declaration order and simulate it:
Config.java
final class Config {
    static final Config INSTANCE = new Config();      // runs FIRST
    static final Map<String, String> DEFAULTS = loadDefaults();

    private final String region;

    private Config() {
        // DEFAULTS is still null here: static initializers run
        // top to bottom, and INSTANCE is declared above DEFAULTS.
        this.region = DEFAULTS.get("region");         // NPE -> ExceptionInInitializerError
    }
}
  1. Name the root cause: the constructor runs while the class is still mid-initialization, so it reads DEFAULTS before that field's initializer has executed and sees the default value, null. The sibling version of this bug is a cycle — class A's static initializer touches class B, whose initializer touches A back; the JVM sees A already "in progress" and lets B read A's half-initialized statics with no error at all.
  2. Fix: move INSTANCE below every field it depends on, or better, stop depending on order — use the lazy holder idiom, a private static nested class whose only field is the instance, so the singleton is built on first access, after the outer class is fully initialized. Prevention: keep static initializers trivial, and never call overridable or dependency-heavy code from them.

Land it Static initializers are a script that runs top to bottom exactly once — any code that runs during that script can see the class half-built.

Likely follow-ups
"You moved INSTANCE below DEFAULTS and it still fails in production. What next?"

Then the dependency is across classes, not within one.

The constructor may touch a second class whose static initialiser touches Config back, and from a single thread the JVM permits that cycle: it sees Config is already being initialised by this thread and lets the other class read Config's statics half-built.

The trace will show a nested <clinit> frame from the other class. I would run with -Xlog:class+init=info to print initialisation order and find which class was entered from inside Config.<clinit>.

The durable fix is to make the singleton lazy through a holder class or a Supplier, and to keep static initialisers free of calls into other application classes.

"What exactly triggers class initialisation, and what does not?"

The specification lists the triggers: creating an instance, invoking a static method, assigning or reading a static field that is not a compile-time constant, Class.forName with the default initialise flag, initialising a subclass, and being the main class.

Things that do not trigger it: referencing a constant like Config.VERSION when it is a static final primitive or String with a constant initialiser, because the compiler inlined it; loading the class via ClassLoader.loadClass; using Config.class as a literal; and creating an array of the type.

Those gaps matter because they explain why an initialiser sometimes runs far later than expected, or never, and why a static block with side effects is a trap.

"Why does the lazy holder idiom work without any synchronisation?"

Because the JVM already synchronises class initialisation. The idiom is a private static nested class Holder whose only member is static final Config INSTANCE = new Config(), and the outer class's get() returns Holder.INSTANCE.

Nothing loads or initialises Holder until get() is first called, and when it is, the JVM takes the per-class initialisation lock, runs <clinit> exactly once, and every other thread waiting on that lock sees the fully built instance afterwards.

So you get lazy, thread-safe, and after initialisation a plain static field read with no volatile cost. That is why it beats double-checked locking, which needs a volatile and is easy to get subtly wrong.

"What does the JVM do to the class after ExceptionInInitializerError?"

It marks the class as erroneous, permanently for the life of that class loader. The first use gets the ExceptionInInitializerError with the real cause attached. Every later use gets NoClassDefFoundError: Could not initialize class Config with no cause, because the JVM does not retry initialisation.

So in a service the first error is the only one with diagnostic value, and if it happened in a background thread whose exception was swallowed, the logs show only the unhelpful follow-ons.

JDK 17 improved this slightly by attaching an ExceptionInInitializerError as the cause of the later NoClassDefFoundError in some cases, but the advice stands: find the first occurrence.

Q18. "When would you actually call String.intern(), and what are the risks?"

Reveal answer

Strong answer intern() returns the canonical pooled instance for a string's contents, so its legitimate use is deduplication: when I load millions of records whose fields repeat heavily — country codes, status names, city strings — interning collapses each distinct value to one shared instance and can cut heap use dramatically.

The risks are real, though. The pool is a fixed-bucket hash table sized by -XX:StringTableSize, and pushing millions of distinct strings into it degrades its lookups; interned strings also live as long as they are referenced, so interning unbounded user input is a slow leak.

Two alternatives are usually better: the garbage collector's own -XX:+UseStringDeduplication on G1, which shares the underlying character arrays automatically, or an explicit canonicalization map in my own code using computeIfAbsent, which I control and can bound.

And never intern to make == comparisons work — that is fixing the wrong end of the bug.

Going deeper Two version facts worth stating precisely.

First, -XX:+UseStringDeduplication was G1-only when it arrived in JDK 8u20, but since JDK 18 it is supported by Serial, Parallel, ZGC and Shenandoah as well, so "the G1 trick" is now available on every production collector; it deduplicates the backing byte[] of strings that survive a few young collections, controlled by -XX:StringDeduplicationAgeThreshold, default 3, and it never changes string identity, so it cannot make == true.

Second, the intern table lives on the heap since JDK 7 and its bucket count is -XX:StringTableSize, default 65,536 on 64-bit JVMs; since JDK 11 the table grows itself when average chain length passes a threshold, so the old "set it to a large prime" advice is obsolete.

To see whether interning is helping or hurting, run jcmd <pid> VM.stringtable for counts and chain lengths, and jcmd <pid> GC.class_histogram before and after to compare byte[] totals.

Land it Intern for measured memory wins on a closed set of values; for anything unbounded, dedupe with the collector or your own map.

Likely follow-ups
"How would you measure whether intern() actually saved memory in your service?"

With a class histogram before and after, on the same workload. jcmd <pid> GC.class_histogram prints instance counts and bytes per class; the lines to watch are java.lang.String and [B, the byte arrays behind them.

If interning helps, the string count drops sharply while the live data set is unchanged. A heap dump in Eclipse MAT gives the precise view: the "Duplicate strings" report lists identical values and the retained bytes they waste.

I would also check the cost side, jcmd VM.stringtable for table size and the CPU profile for time in StringTable::intern. Only if the saving is a meaningful fraction of the heap do I keep the change.

"Why is a computeIfAbsent canonicalisation map better than intern for user data?"

Control.

My own ConcurrentHashMap<String, String> with computeIfAbsent(s, k -> k) returns a canonical instance just like intern, but it lives in ordinary heap, is visible in heap dumps under my class name, can be bounded or cleared, and can be scoped to one request or one batch so it dies with the work.

The JVM's table is global, shared with every library in the process, and grows for as long as the strings are referenced.

For user-supplied values, which are unbounded, the global table is a slow leak; for a batch that repeats the same city names ten million times, a per-batch map gets the deduplication and then disappears. That scoping is the whole difference.

"Does interning affect garbage collection pauses?"

It used to, and much less now. The string table is a GC root set that must be scanned to find dead entries, and before JDK 13 that scan ran during a stop-the-world pause, so a table with millions of entries added measurable pause time.

G1 moved string table cleaning to the concurrent phase in JDK 13, and the table became a concurrent hash table in JDK 11, so with current collectors the cost is mostly off the pause path.

What still costs is the memory the table itself occupies and the fact that every interned string stays alive until nothing references it. You can watch the cleanup with -Xlog:stringtable*=debug or -Xlog:gc+stringtable in older releases.

"When would you choose deduplication over interning, or neither?"

Deduplication when the duplicates are incidental and I do not control the code creating them, for example strings coming from a JSON parser inside a framework: I turn on -XX:+UseStringDeduplication, verify the effect with -Xlog:gc+stringdedup=info, and touch no code.

Interning or a canonical map when I control the creation point and the set of values is small and closed, because then I also save the string objects, not just the arrays, and I save the hash computations.

Neither when the strings are short-lived: young-generation garbage costs almost nothing, and both techniques add work on allocation for objects that would have died in milliseconds. A profile that shows strings in the old generation is the signal.

Q19 · Scenario. "A class you wrote as immutable — final class, final fields, no setters — is showing different state than it was constructed with. Where do you look?"

Reveal answer

Strong answer Final fields freeze the references, not the objects behind them, so I hunt for a mutable object that is shared across my perimeter:

  1. List the fields whose types are mutable — List, Map, arrays, Date, StringBuilder. Only those can carry this bug; a String or int field cannot.
  2. Check the constructor: if it stores a passed-in List directly, the caller still holds the same reference and can mutate my state from outside, any time later. That is a missing defensive copy on the way in.
  3. Check the getters: if one returns the internal list or array itself, every caller received a handle to my insides. That is the missing copy on the way out.
  4. Confirm by searching call sites for mutations of the returned or passed collection, or temporarily wrap the field with Collections.unmodifiableList and see who blows up with UnsupportedOperationException — the stack trace names the culprit.

The fix: copy on entry with List.copyOf — which makes a genuinely immutable snapshot and rejects nulls — and return either that snapshot or a fresh copy from getters; arrays always need clone() both ways since no unmodifiable view exists for them. Prevention: treat "final fields plus no setters" as necessary but not sufficient, and review every mutable-typed field crossing a constructor or getter boundary.

Land it The class wasn't immutable — it was a final-flavored wrapper around shared mutable state, and the copies at the boundary are what make the promise true.

Likely follow-ups
"You added copies on the way in and out and the state still changes. What is left?"

Three remaining doors. The elements themselves: List.copyOf copies the list, not the objects inside it, so a list of mutable Address objects still shares every address with the caller; deep immutability needs immutable element types.

Reflection or serialisation: a framework such as Jackson or Hibernate may write final fields through Unsafe or setAccessible after construction, so check whether the object is being deserialised into rather than constructed.

And identity confusion: the "changed" object may be a different instance that happens to be equal, which a log of System.identityHashCode resolves in one line.

If none of those apply, I set a field watchpoint in the debugger on the suspect field and let it break on the write.

"Can final fields be modified at all after construction?"

Through normal code, no.

Through reflection, only for instance fields and only outside the java.base module's strong encapsulation: Field.setAccessible(true) followed by set works on a final instance field of your own class as of JDK 21, though the JIT may have inlined the old value so the change is not reliably visible.

Static final fields cannot be changed reflectively, and record component fields are also rejected. Serialisation frameworks use Unsafe.putObject or ReflectionFactory to write finals when hydrating.

JEP draft work on integrity by default, tracked as of Aug 2026, aims to require an explicit --enable-final-field-mutation-style opt-in, so this loophole is closing. I treat any code doing it as a red flag.

"Why prefer List.copyOf over Collections.unmodifiableList or new ArrayList here?"

Because it is the only one that gives both a copy and immutability. new ArrayList<>(input) copies, so the caller's later edits are excluded, but the getter would then expose a mutable list unless wrapped.

Collections.unmodifiableList(input) blocks writes through the wrapper but is a live view of the caller's list, so it fails the on-the-way-in test entirely.

List.copyOf makes an immutable snapshot, rejects nulls, and, when the input is already an immutable list from the List.of family, returns it without copying, so repeated copies at layer boundaries are free.

The one thing to know is the null rejection: if nulls are legitimate in your data, you need Collections.unmodifiableList(new ArrayList<>(input)).

"How does this bug show up in a heap dump or a debugger?"

In a heap dump, look at the ArrayList instance referenced by your final field and ask the tool for its incoming references.

If there are two or more, one from your object and one from somewhere else, that somewhere else is the mutator, and MAT's "Path to GC roots" names it.

In a debugger, IntelliJ's field watchpoint on the list's elementData or on modCount breaks on any structural change with the mutating stack. In production without a debugger, temporarily store Collections.unmodifiableList and let the mutator throw UnsupportedOperationException; the stack trace is the diagnosis.

Any of the three takes minutes once you know the object is shared rather than changed by magic.

Q20. "Final field, immutable object, unmodifiable collection — three different guarantees. Untangle them for me."

Reveal answer

Strong answer They operate at three different layers. A final field freezes the binding: the variable will always point at the same object, but that object can be as mutable as it likes — final List still accepts add.

An immutable object freezes the object itself: no code path anywhere can change its state after construction, which is a property of the class's whole design, not of any keyword.

An unmodifiable collection — say Collections.unmodifiableList(inner) — freezes only one doorway: mutating through the wrapper throws, but anyone still holding inner mutates the contents and every reader of the wrapper sees the change. That is why unmodifiable views are read-only windows, not immutability.

List.of and List.copyOf are the genuinely immutable collections: there is no backing list to reach around. A senior states which guarantee a design needs and picks the mechanism that actually provides it.

Land it Final locks the pointer, unmodifiable locks one door, immutable locks the object — only the last one is a thread-safety guarantee.

Likely follow-ups
"How do you tell at runtime whether a List is one of the immutable ones?"

You cannot through the List interface, which is a known gap. The immutable implementations live in the package-private ImmutableCollections class, so getClass().getName() shows java.util.ImmutableCollections$ListN or $List12, and List.copyOf uses that check internally to skip copying. Application code should not depend on class names.

The practical approach is to stop asking: at boundaries, always call List.copyOf, which is a no-op for immutable inputs and a copy otherwise, so the outcome is immutable either way.

Guava's ImmutableList makes the property visible in the type, which is one reason teams still use it for public APIs where the guarantee is part of the contract.

"Does an unmodifiable view give any thread-safety at all?"

No. The wrapper adds no synchronisation and no visibility guarantees, so a reader iterating the view while the owner mutates the backing list gets a ConcurrentModificationException at best and a torn read at worst.

For a read-mostly structure shared across threads, the correct pattern is an immutable snapshot swapped through a volatile reference or AtomicReference: build the new list fully, then publish it, and readers always see a complete, consistent version. CopyOnWriteArrayList automates that for small lists with rare writes.

So when I hear "we return an unmodifiable list, so it is thread-safe", I correct it: unmodifiable is about who may write, not about when writes become visible.

"What do sequenced collections in JDK 21 add to these guarantees?"

They add order operations without changing mutability. JDK 21's SequencedCollection, SequencedSet, and SequencedMap give getFirst, getLast, reversed, addFirst, and addLast to List, Deque, LinkedHashSet, LinkedHashMap, and TreeMap.

The interaction with these three guarantees is straightforward: on an immutable list, addFirst throws UnsupportedOperationException, and on an unmodifiable view the same. reversed() returns a view, so it inherits the backing collection's mutability, which is the same live-view trap as subList.

One subtlety: Collections.unmodifiableSequencedCollection and its map and set variants exist for wrapping, so your wrapper does not lose the sequenced type.

"Give me a case where each of the three is the correct choice."

A final field is right when the binding must not change but the object legitimately does, for example a final ConcurrentHashMap cache field: the map mutates all day, and final guarantees every thread sees the same, fully constructed map.

An unmodifiable view is right when you deliberately want readers to see live updates without being able to write, such as a monitoring endpoint exposing a live queue's contents, documented as live.

An immutable object is right for anything that crosses a boundary and should mean the same thing forever: a request, a configuration snapshot, a map key.

Choosing among them is a design statement about who can change what and when, so I write that statement in the Javadoc.

Drill · Modern class design — interfaces, sealed types, records, enums

This group tests whether your design vocabulary has kept up with the language — and whether you can say when each modern construct is the wrong choice, not just the right one.

Q21. "With default methods and private methods in interfaces, why would you still ever write an abstract class?"

Reveal answer

Strong answer Default methods — method bodies in interfaces, added in Java 8 — closed the "interfaces can't carry code" gap, but three differences survive:

  1. State (the biggest): an interface cannot declare instance fields, because its fields are implicitly public static final constants. Any shared mutable or per-instance state therefore forces an abstract class.
  2. Constructors: an abstract class can enforce invariants and require arguments at construction. An interface cannot.
  3. Access control: abstract classes can have protected and package-private members and helper hierarchies. Interface methods are essentially public API — application programming interface — apart from private helpers.

So my rule of thumb is: interface for the contract, because a class can implement many of them across any hierarchy; abstract class for a skeletal implementation that carries state, the pattern the JDK itself uses with AbstractList behind the List interface.

Often the answer is both: a public interface plus an optional abstract base.

Picture it An interface field is one shared constant, while an abstract-class field lives inside every object, and the compiler refuses the first when you try to use it as state.

The setup: a hit counter written as an interface with a field, then the same idea as an abstract class.

the interface that cannot hold stateruns offline
interface Counter {
    int count = 0;                  // ❌ TRAP: implicitly public static final
    void hit();
}
class Page implements Counter {
    public void hit() { count++; }  // ❌ compile error: cannot assign a value to final variable count
}

Make the invisible visible: where the field actually lives in each design.

memory picture
interface Counter                       abstract class Counter
  Counter.count  (one slot, constant)     (no static slot)
  ── belongs to the TYPE ──
                                        heap
Page a   Page b                           a ──▶ [ Page | count=2 ]   own copy
  no per-object field at all              b ──▶ [ Page | count=0 ]   own copy

The trace: what each design lets you do with per-instance state.

design trace
declare per-object field in interface          ✗ it becomes a constant
assign to it from hit()                        ✗ cannot assign a value to final variable count
declare field in abstract class                ✓ protected int count;
require an id in the constructor               ✓ abstract class can; interface cannot
share the skeleton across subclasses           ✓ Page extends Counter

The fix: move the state into an abstract class and keep a small interface for the contract.

abstract class with stateruns offline
interface Hittable { void hit(); }                       // the contract

abstract class Counter implements Hittable {
    protected int count;                                  // ✅ FIX: per-instance state
    public void hit() { count++; }
}
class Page extends Counter { }

What you see now: two pages keep separate counts.

console
# illustrative output
Page a = new Page(); Page b = new Page();
a.hit(); a.hit(); b.hit();
a.count=2  b.count=1

Land it The moment shared code needs a field or a constructor, the interface has run out — that is the abstract class's remaining territory.

Likely follow-ups
"Why can't a default method override equals, hashCode or toString?"

Because the class always wins, and every class already has those three from Object.

The resolution rule says a method inherited from a superclass beats any interface default, and Object is every class's superclass, so a default equals would never be selected; the language forbids declaring it rather than let it silently do nothing.

There is also a design reason: equals and hashCode are about the state of an instance, and interfaces have no state, so an interface cannot know what equality means for its implementors.

If a family of types needs shared equality logic, that is exactly the abstract class's job, or you use a record for each leaf and let the compiler generate it.

"How does the JDK itself mix interfaces and abstract classes, and what does that teach?"

The collections framework is the model: List is the interface with the contract, AbstractList is the skeletal implementation that turns two methods, get and size, into a full read-only list with iterators, equals, hashCode and subList, and ArrayList extends it for the real thing.

The lesson is that the interface is what clients depend on, so it stays minimal and stable, while the abstract class is an optional convenience for implementors and can carry state such as modCount.

Since JDK 8, some of the skeletal behaviour moved into defaults, for example List.sort and Collection.removeIf, but anything needing a field stayed in the abstract class. I copy that split in my own APIs.

"What does the diamond problem look like for abstract classes, and why does Java avoid it?"

It does not arise, because a class can extend only one class.

The diamond is two parents each providing state or a method body for the same member, so a child inherits two copies and the language must decide which one wins; C++ needs virtual inheritance to solve it.

Java sidesteps it for state by allowing single class inheritance and for behaviour by making interface defaults stateless and forcing you to override on a conflict.

That is also why a default method cannot be final and cannot be synchronized: an interface cannot commit a class to a locking policy or forbid it from resolving a conflict. The single-inheritance rule is a constraint that removes an entire category of ambiguity.

"When would you replace an abstract base class with composition instead?"

When the shared code is a capability rather than an identity. An abstract BaseRepository that holds a JdbcTemplate and helper methods forces every subclass into one hierarchy and makes testing harder because the base's behaviour comes along.

The composition version is a small final helper class injected into each repository, which can be mocked, reused across unrelated hierarchies, and evolved without touching subclasses.

My rule: use an abstract class when subclasses genuinely are a kind of the base and the template-method pattern fits, where the base defines the algorithm and subclasses fill steps. Use composition when the "base" is a toolbox.

Interfaces with defaults cover the middle ground where the shared code needs no state.

Q22 · Scenario. "You add a second interface to a class and the build fails with 'inherits unrelated defaults for process() from types A and B'. What are the resolution rules, and what's the fix?"

Reveal answer

Strong answer This is the diamond — one class inheriting two default implementations of the same method — and Java resolves it with three ordered rules:

  1. A concrete method from a superclass always beats any interface default. Classes win over interfaces, full stop.
  2. Among interfaces, the most specific one wins: if B extends A and both provide the default, B's version is chosen and there is no conflict.
  3. If the two interfaces are unrelated — as here, neither extends the other — the compiler refuses to pick a winner and forces the class to override the method. That refusal is deliberate: silently choosing one contract over the other would be a behavior bug waiting to happen.

So the fix is to decide what process() should mean for this class and write the override. If one parent's behavior is right, I delegate explicitly with the special syntax A.super.process(), which names exactly which inherited default to run; I can even call both and combine them. Then I step back and ask the design question: two unrelated interfaces claiming the same method name on one class often signals the class has two jobs, and splitting it may be the real fix.

Picture it Class C inherits two unrelated defaults, the compiler stops, and A.super.process() is the explicit choice that resolves it.

The setup: two interfaces that both ship a default process(), and a class that implements both.

two unrelated defaultsruns offline
interface A { default void process() { System.out.println("A"); } }
interface B { default void process() { System.out.println("B"); } }

class C implements A, B { }          // ❌ TRAP: which process() does C inherit?

Make the invisible visible: the three rules as a decision picture for the inherited process().

inheritance picture
        A               B                  Rule 1: a class method wins   → none here
        └──── C ────────┘                  Rule 2: most specific wins    → A and B unrelated
   C inherits process() from BOTH          Rule 3: otherwise you decide  → compile error

What you see: the compiler refuses to build C.

javac output
C.java: error: types A and B are incompatible;
  class C inherits unrelated defaults for process() from types A and B

Why: silently choosing one contract over the other would be a behaviour bug waiting to happen, so the compiler makes the class author decide.

The fix: override in C and name the inherited default you want.

explicit resolutionruns offline
class C implements A, B {
    @Override public void process() {
        A.super.process();            // ✅ FIX: run A's default
        B.super.process();            // optional: run both, in the order you choose
    }
}

What you see now: the same call, now deterministic.

console
new C().process();
A
B

Land it Class wins, then most-specific interface wins, then you must choose — and A.super.process() is how you say your choice out loud.

Likely follow-ups
"What if only one of the two interfaces has a default and the other declares process() abstract?"

Still a compile error, and that surprises people. The rule that the more specific interface wins only applies when one interface extends the other.

Two unrelated interfaces, one with a default process() and one with an abstract process(), leave the class inheriting conflicting declarations, and the compiler requires an explicit override. You can resolve it with A.super.process() if you want the default behaviour to satisfy both.

The reason is that the abstract declaration in B is a contract with possibly different semantics, and the compiler will not assume A's implementation satisfies B. It is the same conservative stance as the two-defaults case: the class author must state the intended meaning.

abstract versus defaultruns offline
interface A { default void process() { } }
interface B { void process(); }
class C implements A, B { }                         // ❌ compile error: C must override process()
class D implements A, B {
    public void process() { A.super.process(); }    // ✅ FIX: say that A's default satisfies B
}
"Can you call A.super.process() from anywhere, or only inside the overriding method?"

Only from inside the class that directly implements A, and only in the form A.super.method() where A is a direct superinterface.

You cannot write it from a subclass two levels down, you cannot use it to reach a default that a more specific interface has already overridden, and you cannot call it on another object.

It exists solely for the conflict-resolution case and the "extend the default" case, where the override does some extra work and then delegates.

In the bytecode it becomes an invokespecial on the interface method, which is the same non-virtual dispatch as super.method() on a class, which is why it needs the interface to be a direct parent.

"How does this conflict interact with a superclass that already has process()?"

The superclass ends the argument. If the class extends a Base that has a concrete process(), that method wins over both interface defaults with no error, even if Base was written years before either interface existed and its process() means something unrelated.

That is the "class wins" rule in its most dangerous form: the compiler is satisfied, but the semantics may be wrong, and no override was ever written for either interface.

So when I add an interface with a default to an existing class hierarchy, I search the hierarchy for any existing method with the same signature before assuming the default will be used. A test that calls the method through each interface type catches it.

"The fix compiled. How do you make sure the other interface's contract is still honoured?"

By testing through each interface type separately.

If A's contract says process() is idempotent and B's says it must emit an event, a single override delegating to A.super.process() silently breaks B. I write one test that holds the object as an A and one as a B, each asserting that interface's documented behaviour.

If both cannot be satisfied by one method, the name clash is telling me the class should not implement both, and the fix is an adapter: a small inner class implementing B that delegates to the outer object with the right semantics.

The compile error was the easy part; the semantic question is what the interviewer is actually probing.

Q23. "Why did Java 9 add private methods to interfaces? What problem do they solve?"

Reveal answer

Strong answer They fix a hole that default methods opened. Once interfaces could carry real method bodies, larger interfaces naturally grew several default methods sharing common logic — validation, formatting, a common traversal.

Before Java 9 there was nowhere to put that shared code. Every helper had to be another default or static method, which made it public and therefore part of the interface's contract forever, visible to all implementors and callers and impossible to remove compatibly.

Private interface methods give that shared logic a home that stays invisible outside the interface:

  • Private instance methods: for default methods to call.
  • Private static methods: for the static helpers.

The result is default methods that read like ordinary well-factored code instead of copy-paste, without leaking implementation details into the published surface. It is the same encapsulation principle classes always had, arriving late to interfaces because interfaces only recently started owning behavior.

Picture it Before Java 9 a helper shared by two defaults had to be public and part of the contract; with private methods it disappears from the surface.

The setup: an interface with two default methods that share validation logic.

helper forced to be publicruns offline
interface Validator {
    default boolean isValidEmail(String s) { return clean(s).contains("@"); }
    default boolean isValidName(String s)  { return !clean(s).isEmpty(); }

    default String clean(String s) {          // ❌ TRAP (Java 8): helper is public API
        return s == null ? "" : s.trim();
    }
}

Make the invisible visible: what implementors and callers can see, before and after.

published surface
BEFORE (Java 8)                       AFTER (Java 9+)
public: isValidEmail                  public: isValidEmail
public: isValidName                   public: isValidName
public: clean   ← leaked, forever     private: clean    ← invisible outside the interface

What you see: a caller reaches the leaked helper and an implementor may override it.

javac output
// Java 8 shape: v.clean(" a@b ") compiles for every caller, and any class may override clean()
// Java 9 shape with the helper private:
v.clean(" a@b ");   // compile error: clean(String) has private access in Validator

The fix: declare the helper private so it can be changed or deleted later without breaking anyone.

private interface methodruns offline
interface Validator {
    default boolean isValidEmail(String s) { return clean(s).contains("@"); }
    default boolean isValidName(String s)  { return !clean(s).isEmpty(); }

    private String clean(String s) {              // ✅ FIX: private instance helper
        return s == null ? "" : s.trim();
    }
    private static String tag(String s) { return "[" + s + "]"; }   // private static helper for static methods
}

What you see now: only two methods remain in the public contract.

javap -p (excerpt)
interface Validator
  public default boolean isValidEmail(java.lang.String);
  public default boolean isValidName(java.lang.String);
  private java.lang.String clean(java.lang.String);

Land it Default methods made interfaces carry code; private methods let them carry it without publishing the scaffolding.

Likely follow-ups
"Why can't private interface methods be abstract or default, and what rules do they follow?"

A private method must have a body because nobody outside can implement it; the whole point is that it is invisible to implementors, so private abstract would be a contract with no possible implementor.

It cannot be default because default means "inherited by implementing classes", and private members are never inherited.

The rules: private instance methods can be called only from other default or private methods of the same interface, private static methods only from static or private methods there, and neither can be protected, since interfaces have no notion of package or subclass access.

They compile to ordinary private methods in the interface's class file, and JDK 11's nestmates change means they no longer need synthetic accessors.

"Does this make interfaces a replacement for utility classes?"

Partly, and I would be careful. Since JDK 8 an interface can hold public static methods, so Comparator.comparing lives on Comparator rather than a separate Comparators class, which is a real readability win. Private static helpers let those factories share code.

But an interface is still a type that classes can implement, so a bag of static utilities on an interface invites someone to implement it to "inherit" the constants, an old anti-pattern.

For utilities with no associated type, a final class with a private constructor remains the clearer choice. For factories that produce instances of the interface, putting them on the interface is now the idiom.

"How does a private interface method behave at runtime compared with a default?"

A default method is dispatched with invokeinterface, so it can be overridden and the JVM must look up the receiver's class to find the implementation.

A private interface method is invoked with invokeinterface too since JDK 11, but marked private, or invokespecial on older class files, and the JIT knows it cannot be overridden, so it inlines it directly.

There is no performance penalty for factoring a default into private helpers, and the helper does not appear in the implementing class's method table.

You can see the difference with javap -p -c on the interface: private methods show with the private flag and their call sites show the direct invocation.

Q24. "What are sealed classes and interfaces, and when do you as a senior actually reach for them?"

Reveal answer

Strong answer A sealed type — standard since Java 17 — declares exactly which classes may extend or implement it, listed in a permits clause, and each permitted subtype must itself declare final, sealed, or non-sealed.

That turns "who can be a subtype" from an open question into a closed, compiler-checked set. I reach for it when a domain concept has a known, finite set of shapes: a PaymentEvent that is exactly Authorized, Captured, or Refunded, usually with records as the leaves.

The payoff is exhaustive pattern matching: a switch over a sealed interface with a case per subtype needs no default branch, so when someone adds a fourth event next quarter, every switch in the codebase fails to compile until it handles the new case — the compiler finds every touchpoint for you.

It is also an API-control tool: a public interface whose implementations only I supply.

Picture it A sealed interface is a closed family tree, and adding a member makes every switch that forgot it fail to compile.

The setup: a payment event with exactly three permitted records, and one switch over it.

sealed hierarchy and switchruns offline
sealed interface PaymentEvent permits Authorized, Captured, Refunded { }
record Authorized(String id) implements PaymentEvent { }
record Captured(String id, long amount) implements PaymentEvent { }
record Refunded(String id, long amount) implements PaymentEvent { }

static String label(PaymentEvent e) {
    return switch (e) {                       // no default branch
        case Authorized a -> "auth " + a.id();
        case Captured c   -> "paid " + c.amount();
        case Refunded r   -> "back " + r.amount();
    };
}

Make the invisible visible: the closed set the compiler knows.

type picture
            PaymentEvent  (sealed, permits 3)
        ┌────────┼─────────┐
   Authorized  Captured  Refunded       each is a record, so implicitly final
   (closed set: nobody else can implement PaymentEvent)

The trace: next quarter someone adds a fourth event.

compile trace
add: record Disputed(String id) implements PaymentEvent; and add it to permits   ✓ compiles
label(...) switch has cases for 3 of 4 subtypes                                  ✗ not exhaustive
every other switch over PaymentEvent in the codebase                             ✗ same
add `case Disputed d -> ...` to each                                             ✓ build is green

What you see: the build breaks at every touchpoint instead of production breaking later.

javac output
Billing.java:14: error: the switch expression does not cover all possible input values
        return switch (e) {
               ^

Land it Sealing plus exhaustive switch turns "we forgot to handle the new case" from a production incident into a compile error — that trade is why seniors use it.

Likely follow-ups
"Which Java version do you need for the exhaustive switch to work, and what does the compiler check exactly?"

Sealed types are final in JDK 17, but exhaustive switching over them with type patterns, case Authorized a ->, became final in JDK 21 with pattern matching for switch, along with record patterns that deconstruct the leaf.

The compiler checks that the cases cover every permitted subtype, recursively through nested sealed types, and it does so only for switch expressions and for pattern switches; an old-style statement switch over an enum still compiles with missing cases.

If the sealed hierarchy gains a subtype, every exhaustive switch in the codebase fails to compile with "the switch expression does not cover all possible input values".

Separately compiled clients that were not rebuilt get a MatchException at runtime, which is the JVM's way of catching the stale binary.

"When is non-sealed the right choice, and when is it a smell?"

non-sealed re-opens one branch of a sealed hierarchy to arbitrary subclasses. It is right when a framework needs one extension point in an otherwise closed model, for example a sealed Shape with Circle, Square, and a non-sealed CustomShape that plugin authors extend.

The cost is that a switch over Shape still needs a case for CustomShape, and every subclass of it falls into that branch, so you have exhaustiveness at the top level but not below.

It becomes a smell when it is used to silence the compiler rather than to express a real extension point; if most leaves are non-sealed, the hierarchy is not really closed and sealing is theatre.

"How do sealed interfaces interact with records, and why is that pairing so common?"

Records are implicitly final, so they qualify as sealed leaves without any extra modifier, and they carry no behaviour, so a sealed interface of records is a pure data model: an algebraic sum type of product types, in functional-programming terms.

The switch then deconstructs directly, case Captured(var id, var amount) -> ..., and the compiler enforces both that every event kind is handled and that every field is named.

Because the records must be listed in permits or declared in the same file, the whole model is readable in one place. This is the shape I use for domain events, command results, and parser output, and it replaces visitor-pattern boilerplate almost entirely.

"What happens across module or package boundaries with sealed types?"

All permitted subtypes must be accessible to the sealed type at compile time and must live in the same module, or, if the code is in the unnamed module, in the same package.

The permits clause can be omitted only when all subtypes are in the same compilation unit. That constraint is deliberate: sealing is a promise about the complete set of subtypes, and the compiler can only verify it within a boundary it fully controls.

It also means a library can expose a sealed interface and guarantee that clients cannot implement it, which is the API-control use. Reflection reports the set through Class.getPermittedSubclasses(), which frameworks such as Jackson use to build polymorphic deserialisation without annotations.

Q25. "What does a record actually generate for you, and what is a compact constructor for?"

Reveal answer

Strong answer A record is a class declared as a transparent carrier for a fixed set of components — record Money(String currency, long amountMinor) — and the compiler generates the whole value-class boilerplate:

  • Fields and accessors: a private final field and a public accessor per component.
  • Canonical constructor: one constructor taking all components.
  • Value methods: equals, hashCode, and toString derived from all components.

The class is implicitly final and cannot extend another class, and the fields cannot be reassigned, so it is shallowly immutable by construction.

The compact constructor is the canonical constructor written without its parameter list — Money { ... } — whose body runs before the fields are assigned.

It exists for validation and normalization:

  • Validate: reject a negative amount with IllegalArgumentException.
  • Normalize: upper-case the currency.
  • Copy defensively: copy a mutable component like a list with List.copyOf, so the record's shallow immutability becomes deep where it matters.

Whatever the compact body leaves in the parameters is what gets stored.

Picture it A record is a class with fixed fields plus generated members, and the compact constructor is the checkpoint that runs before those fields are assigned.

The setup: a Money record with a compact constructor, and a Cart record holding a mutable list.

records with a compact constructorruns offline
record Money(String currency, long amountMinor) {
    Money {                                           // compact constructor: no parameter list
        if (amountMinor < 0) throw new IllegalArgumentException("negative");
        currency = currency.toUpperCase();            // reassigns the PARAMETER, then fields are set
    }
}
record Cart(List<String> items) {                     // ❌ TRAP: shallow immutability
    Cart { items = List.copyOf(items); }              // ✅ FIX: defensive copy
}

Make the invisible visible: what the compiler generates for Money.

what the compiler generatesruns offline
final class Money extends java.lang.Record {
    private final String currency;
    private final long amountMinor;
    Money(String currency, long amountMinor) {        // canonical constructor
        if (amountMinor < 0) throw new IllegalArgumentException("negative");
        currency = currency.toUpperCase();
        this.currency = currency;                     // assignments appended after your body
        this.amountMinor = amountMinor;
    }
    public String currency()    { return currency; }
    public long   amountMinor() { return amountMinor; }
    // plus equals, hashCode, toString derived from both components
}

The trace: the order of events inside new Money("eur", 1250).

constructor trace
new Money("eur", 1250)
 1 parameters currency="eur", amountMinor=1250          ✓
 2 compact body: amountMinor >= 0                       ✓
 3 compact body: currency = "EUR"                       ✓ parameter rewritten
 4 this.currency = currency, this.amountMinor = ...     ✓ fields frozen
 5 new Money("EUR", -5) throws at step 2                ✗ no object ever exists

What you see: the generated toString and equals use the normalised values.

console
# illustrative output
new Money("eur", 1250)                      -> Money[currency=EUR, amountMinor=1250]
new Money("eur", 1250).equals(new Money("EUR", 1250))   -> true
new Money("eur", -5)                        -> IllegalArgumentException: negative

Land it A record trades representation freedom for zero boilerplate, and the compact constructor is your one checkpoint to enforce invariants before state freezes.

Likely follow-ups
"Can a record have additional constructors, static fields, or instance methods?"

Yes to all three, with limits. You can add non-canonical constructors, but every one of them must delegate to the canonical constructor with this(...), so all state still flows through the one validated path.

Static fields and static methods are fine and common for constants and factories. Instance methods are fine, including overriding an accessor, though an overridden accessor must return exactly the component type and should not lie about the value.

What you cannot add are instance fields beyond the components, because a record's state is by definition its components, and you cannot declare a record abstract or extend another class. It can implement interfaces, which is how sealed hierarchies of records work.

"How does a record serialise and deserialise, and why is that safer than a normal class?"

Java serialisation treats records specially: on read it reconstructs the object by calling the canonical constructor with the deserialised components, rather than allocating an instance and stuffing fields directly.

That means the compact constructor's validation runs on every deserialisation, so a hostile or corrupted stream cannot produce an invalid record, which closes the classic gadget-chain hole where readObject bypasses invariants. Records also ignore writeObject, readObject, and readResolve customisations.

Jackson has supported records since 2.12 using the same constructor-based approach, and it matches components to JSON properties by name, so a record usually needs no annotations. The consequence: put validation in the compact constructor and it is enforced everywhere.

"What does the generated toString look like and should you rely on it?"

It prints the record name and each component as name=value in declaration order, for example Money[currency=EUR, amountMinor=1250], generated by the same ObjectMethods bootstrap as equals and hashCode. It is fine for logs and debugging.

I would not parse it or depend on its exact format, and I override it when a component is sensitive, a password or a token, because the default happily prints it into every log line.

The specification says the format is derived from components but does not promise the exact text between releases, so anything that compares strings against it, such as a golden-file test, is brittle. Use structured logging with explicit fields instead.

"Records are shallowly immutable — how do you handle a mutable component you cannot copy?"

Sometimes a record must carry a reference to a service or a stream that is inherently mutable.

The honest answer is that the record is then a transparent carrier of a reference, not a value, and its equals and hashCode will use that reference's identity, which is probably wrong.

I would either exclude the record pattern for that type and write a class, or override equals and hashCode to use only the value components and document why.

For collections and arrays there is no excuse: List.copyOf in the compact constructor for lists, and for arrays, either clone() in both the constructor and an overridden accessor, or better, change the component to a List.

Q26 · Scenario. "A teammate converted a JPA entity to a record and the persistence layer fell apart. Why is a record the wrong tool there, and where are records the right tool?"

Reveal answer

Strong answer The conversion fails because records refuse everything JPA — the Jakarta Persistence API, Java's standard object-relational mapping — depends on:

  1. JPA providers instantiate entities through a no-argument constructor and then populate the fields; a record has only its canonical all-arguments constructor and final fields, so hydration has nothing to work with.
  2. Lazy loading is implemented by subclassing the entity into a proxy that intercepts access; a record is implicitly final and cannot be subclassed.
  3. An entity's identity is its database id — two rows are "the same entity" if the ids match, even mid-edit — while a record's equals and hashCode use every component, which breaks entity semantics in sets and dirty-checking.
  4. Entities are mutable by design across their managed lifecycle; a record's whole point is that its state never changes.

So the fix is to revert the entity to a plain class and use records where they shine: the data transfer objects (DTOs) the service returns — JPA can even project query results straight into records via constructor expressions — plus API payloads, map keys, and small domain value objects like Money or DateRange. That split is the healthy architecture anyway: mutable entities at the persistence edge, immutable records flowing through the rest of the system.

Picture it An entity needs a no-arg constructor, a subclassable class and mutable state, and a record offers none of the three.

The setup: the entity the teammate converted, and the lazy-loading proxy the persistence provider wants to build.

entity as a recordruns offline
@Entity
public record Order(@Id Long id, String status) { }       // ❌ TRAP: final class, no no-arg constructor, final fields

class Order$Proxy extends Order { }                         // what lazy loading needs: a subclass

Make the invisible visible: how a provider hydrates an entity versus what a record allows.

hydration picture
JPA entity (works)                         record (fails)
 1 new Order()            no-arg ctor        ✗ only Order(Long, String) exists
 2 order.setStatus("NEW") fill fields        ✗ fields are final
 3 class Order$Proxy extends Order           ✗ a record is implicitly final
 4 dirty check: compare old vs changed       ✗ nothing can change

What you see: the compiler already rejects the proxy shape.

javac output
Order.java: error: cannot inherit from final Order
// the persistence provider also rejects a record annotated @Entity at startup;
// the exact message differs by provider and version

The fix: a mutable entity at the persistence edge and a record DTO for everything above it.

entity plus record DTOruns offline
@Entity
class Order {                                               // ✅ FIX: plain class, mutable
    @Id Long id; String status;
    protected Order() { }
}
record OrderSummary(Long id, String status) { }             // ✅ records belong here

// JPQL constructor expression fills the record straight from the query:
// select new com.acme.OrderSummary(o.id, o.status) from Order o

What you see now: each layer gets the type that matches its contract.

layer picture
 controller / service   ──▶  OrderSummary (record, immutable)
 repository (internal)  ──▶  Order (entity, mutable, tracked, proxied)
 database row           ◀──  Order

Land it A record models a value with no identity; an entity is identity with changing state — those are opposite contracts, and the record belongs one layer up.

Likely follow-ups
"Are there any places inside JPA where a record is now supported?"

Yes, two. Hibernate 6.2 and later accept a record as an @Embeddable, a value component stored in the owning entity's columns, because an embeddable has no identity and no lifecycle of its own; Hibernate instantiates it through the canonical constructor.

And query projections have worked for years: select new com.acme.OrderSummary(o.id, o.total) from Order o in JPQL, or Spring Data's interface and class-based projections, map result rows straight into a record. Jakarta Persistence 3.2 standardised record embeddables.

What remains off-limits is the entity itself, and that is by design: the persistence context tracks identity and dirty state, which are exactly the things a record refuses to have.

"The teammate insists entities should be immutable for safety. How do you respond?"

I agree with the goal and disagree with the mechanism. An entity is a row's lifecycle in memory: loaded, changed, flushed. That mutation is how dirty checking works, so an immutable entity would need a copy-and-replace model that JPA does not offer.

The safety you want comes from discipline instead: make setters package-private or expose intention-revealing methods like order.cancel(), keep entities out of controllers and services by mapping to records at the application boundary, and never let a detached entity travel through the system as data.

Hibernate also has @Immutable for reference-data entities that are never updated, which gives read-only optimisations without pretending the class is a value.

"The record conversion broke things other than JPA — what else typically fails?"

Anything that relied on a no-argument constructor plus setters or on subclassing. Older Jackson versions before 2.12 could not deserialise records. Bean-mapping libraries like MapStruct needed a version with record support, MapStruct 1.4 onwards.

Spring's @ConfigurationProperties handles records fine since Boot 2.6 with constructor binding, but earlier setups expected setters. Mockito cannot subclass a final record for a partial mock, and any proxy-based mechanism, including Spring AOP on a record-typed bean, fails for the same reason.

And equals changed meaning from identity to all components, which can alter Set behaviour and cache keys. My rule is to convert one type at a time and run the integration tests, not to convert a package wholesale.

"What would you do differently if designing the persistence layer from scratch?"

I would draw the line explicitly. Entities stay as mutable classes but private to the persistence module, with no public setters. The module's public API accepts and returns records: commands in, read models out, and the repository translates.

That gives immutability to every layer except the one that fundamentally needs mutation, keeps the entity graph and its lazy-loading proxies from leaking into services, and means the API can be tested without a database.

If the domain is simple enough, I would consider skipping JPA for jOOQ or Spring Data JDBC, where the aggregate is loaded and saved whole and the mapping to records is natural. The question I ask is whether change tracking earns its complexity for this domain.

Q27. "Why is an enum considered the safest way to write a singleton in Java?"

Reveal answer

Strong answer Because the JVM closes every loophole for you. Writing enum Registry { INSTANCE; } gives three guarantees that hand-rolled singletons have to fight for:

  1. Creation is thread-safe and lazy: enum constants are built during class initialization, which the JVM performs under its own lock, exactly once, on first use — so there is no double-checked-locking dance to get subtly wrong.
  2. Serialization is safe: enums serialize by name, and deserialization returns the existing constant instead of manufacturing a second instance, which plain singletons must prevent with a hand-written readResolve.
  3. Reflection is blocked: Constructor.newInstance explicitly refuses to instantiate enum types, closing the reflective back door.

The honest caveats: an enum cannot extend a class, and in a Spring-style application the container already manages singleton scope, so the enum idiom matters most for infrastructure code outside the container. The lazy holder idiom is the respectable alternative when enum feels off.

Picture it An enum constant is just a static final field built once under the JVM's class-initialisation lock, so two racing threads and one reflection attack all end at the same single object.

The setup: the singleton, and two threads that both ask for it first.

enum singletonruns offline
enum Registry {
    INSTANCE;                                // one constant = one object
    private final Map<String, String> data = new ConcurrentHashMap<>();
    void put(String k, String v) { data.put(k, v); }
}

Make the invisible visible: what the compiler generates and where the lock sits.

what the compiler generatesruns offline
final class Registry extends Enum<Registry> {
    public static final Registry INSTANCE;
    static {                                         // <clinit>: runs once, under the class init lock
        INSTANCE = new Registry("INSTANCE", 0);
    }
    private Registry(String name, int ordinal) { super(name, ordinal); }
}

The trace: two threads first touch Registry.INSTANCE at the same moment.

thread interleaving
step  thread T1                         thread T2
 1    touches Registry.INSTANCE
 2    takes class-init lock, runs <clinit>
 3                                      touches Registry.INSTANCE
 4                                      ✗ blocks: init lock held by T1
 5    INSTANCE built, lock released
 6                                      ✓ sees fully built INSTANCE, same object

What you see: reflection and serialization both fail to create a second instance.

console
# illustrative output
Constructor<Registry> c = Registry.class.getDeclaredConstructor(String.class, int.class);
c.setAccessible(true);  c.newInstance("X", 1);
java.lang.IllegalArgumentException: Cannot reflectively create enum objects

deserialize(serialize(Registry.INSTANCE)) == Registry.INSTANCE   -> true

Land it The enum wins because its guarantees are the JVM's, not the author's — serialization and reflection attacks die for free.

Likely follow-ups
"What exactly goes wrong with double-checked locking, and how does volatile fix it?"

The classic version checks instance == null, locks, checks again, then assigns instance = new Registry().

Without volatile, the JIT and the CPU may reorder the constructor's field writes after the write of the reference, so another thread can see a non-null instance whose fields are still default values and use a half-built object.

Declaring the field volatile makes the reference write a release and the read an acquire, so once you see the reference you see everything written before it.

It works correctly since JDK 5's memory model, but it is easy to omit the volatile, and every read pays for the volatile load. The holder idiom and the enum have neither the fragility nor the cost, which is why I prefer them.

"How would you test that a singleton survives serialisation and reflection attacks?"

Two small tests. For serialisation, write the instance through an ObjectOutputStream into a byte array, read it back, and assert with assertSame that the result is the original instance; a plain class fails unless it implements readResolve returning the singleton, and an enum passes automatically.

For reflection, get the declared constructor, call setAccessible(true) and newInstance(), and assert it throws; for an enum newInstance throws IllegalArgumentException with "Cannot reflectively create enum objects". For a hand-rolled singleton the constructor must itself throw if the instance already exists.

I also include a test that runs getInstance() from many threads under a CountDownLatch and asserts one identity, which exercises the lazy path.

the two testsruns offline
// serialization: expect the same object back
Object copy = new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();
assertSame(Registry.INSTANCE, copy);                 // enum: passes; plain class: fails without readResolve

// reflection: expect an exception, not a second instance
assertThrows(IllegalArgumentException.class, () -> ctor.newInstance("X", 1));   // "Cannot reflectively create enum objects"
"When is a singleton itself the wrong design, regardless of how you build it?"

Whenever the "one instance" is really "one instance per something": per test, per tenant, per configuration, per JVM but not per class loader.

A static singleton is global mutable state, so tests cannot isolate it, it cannot be replaced with a fake, and in a container with multiple class loaders it silently becomes several instances with separate state.

The modern answer is a container-managed singleton, a Spring bean with default scope, which is one instance per application context, injectable, mockable and shut down in order.

The enum idiom is for infrastructure that must exist before or outside any container, such as a JVM-wide registry in a library. Even there I usually expose it behind an interface so callers can substitute it.

"Are enum singletons lazy, and what does that cost at startup?"

They are lazy to the class, not to the JVM: the constant is created when the enum class initialises, which happens at first active use of Registry.INSTANCE, not at JVM start. So an enum singleton nobody touches costs nothing.

The caveat is that any use of the enum, including Registry.values() or a switch on it, triggers construction, so an expensive constructor runs at the first mention.

If the instance needs heavy resources, I keep the enum constructor trivial and initialise the resource lazily inside, or I let the container manage lifecycle.

Class initialisation also holds the class's init lock, so a slow enum constructor blocks every other thread that touches the enum until it finishes.

Q28 · Scenario. "A profiler shows millions of enum-array allocations per minute coming from one hot loop. The loop calls MyStatus.values(). Explain and fix."

Reveal answer

Strong answer This is a known cost of values() that most teams meet exactly this way:

  1. Read the allocation profile — Java Flight Recorder (JFR) allocation events or async-profiler in allocation mode — and it attributes the MyStatus[] churn to MyStatus.values() inside the loop.
  2. Explain why: values() must return a defensive clone of the internal constants array on every single call. Arrays are mutable, so if the method handed out the shared array, any caller could overwrite a constant slot and corrupt every future caller. Correctness forces the copy; the loop turns the copy into an allocation firehose that shows up as garbage-collection pressure.
  3. Fix: hoist it. Cache the array once in the enum itself — private static final MyStatus[] VALUES = values(); — and loop over the cached copy, taking care no caller ever mutates it; or cache List.of(values()) for an immutable version that is safe to expose. If the loop is doing membership or mapping work, switch to EnumSet or EnumMap, which are built on the constants' positions and allocate nothing per operation.
  4. Prevent: teach the review rule that values() in a loop or per-request path is an allocation per call, and re-profile to confirm the churn is gone.

Picture it values() hands every caller a fresh copy of one hidden array, so a hot loop allocates one array per call.

The setup: a hot loop that looks up a status by code with values().

values() in a hot loopruns offline
enum MyStatus { NEW, ACTIVE, CLOSED;
    static MyStatus fromOrdinal(int i) {
        for (MyStatus s : values())               // ❌ TRAP: new MyStatus[3] on every call
            if (s.ordinal() == i) return s;
        throw new IllegalArgumentException();
    }
}

Make the invisible visible: the generated values() and the heap after three calls.

memory picture
generated:  public static MyStatus[] values() { return $VALUES.clone(); }

heap
$VALUES ──▶ [ NEW | ACTIVE | CLOSED ]        (one hidden array, never handed out)
call 1  ──▶ [ NEW | ACTIVE | CLOSED ]        copy, garbage after the loop
call 2  ──▶ [ NEW | ACTIVE | CLOSED ]        copy, garbage after the loop
call 3  ──▶ [ NEW | ACTIVE | CLOSED ]        copy, garbage after the loop

What you see: an allocation profile pointing at the call site.

allocation profile
# illustrative output
jdk.ObjectAllocationSample  weight by top frame
  97%  MyStatus[]   at MyStatus.values()  <-  MyStatus.fromOrdinal()  <-  Loop.run()

Why: arrays are mutable, so handing out the shared array would let any caller overwrite a constant slot.

The fix: clone once into a private static final field, or index into it directly.

cached arrayruns offline
private static final MyStatus[] VALUES = values();       // ✅ FIX: one clone, at class init
static MyStatus fromOrdinal(int i) { return VALUES[i]; } // no allocation, never expose VALUES

What you see now: the same profile after the change.

allocation profile
# illustrative output
jdk.ObjectAllocationSample  weight by top frame
  (no MyStatus[] entries)

Land it values() clones because arrays can't be trusted read-only — cache the clone once and the hot path allocates nothing.

Likely follow-ups
"You cached values() and the allocation profile still shows enum arrays. Where else do they come from?"

The two hidden sources are valueOf and switch. Enum.valueOf(Class, String) uses an internal per-class map, so it does not clone, but many hand-written lookups do for (MyStatus s : values()) inside fromCode(String), which is the same clone in disguise.

Any library method that takes the class and enumerates constants, EnumSet.allOf for example, calls a shared cached array internally via SharedSecrets and does not clone, so that one is fine.

Old-style switch on an enum creates a synthetic $SwitchMap$ array once per switching class, not per call. So the remaining culprits are almost always custom lookup methods, and the fix is a static Map<String, MyStatus> built once.

"Why not just make values() return an unmodifiable list instead of cloning?"

Because the signature MyStatus[] values() is generated by the compiler and specified by the language, so it cannot change without breaking every caller, and arrays have no read-only form in Java.

The JDK team considered adding a List-returning alternative, and the general recommendation has been to write your own private static final List<MyStatus> VALUES = List.of(values()) and expose that. That gives an immutable, cached, allocation-free view.

The deeper lesson for an API designer is that returning an array is committing to either cloning per call or trusting callers; returning an immutable collection removes the dilemma, which is why modern APIs return List.

"How did you attribute the allocations to that call site in the profiler?"

With allocation sampling rather than a heap dump, because the objects die young and never appear in a dump.

In JDK Flight Recorder, the jdk.ObjectAllocationSample event, on by default since JDK 16, records a stack for a sample of allocations weighted by size; opening the recording in JDK Mission Control's allocation view and grouping by top frame shows MyStatus.values() and the loop above it.

Async-profiler's --alloc mode does the same with lower overhead and produces a flame graph. I confirm by comparing the allocation rate before and after the fix, using the jdk.GCHeapSummary events or simply the young-collection frequency in -Xlog:gc.

"Is a few million small arrays per minute actually a problem on a modern collector?"

Often not by itself, and I would say that honestly. G1 and ZGC allocate with a thread-local bump pointer and collect short-lived garbage cheaply, so a few million 40-byte arrays per minute is a few hundred megabytes per minute, which is modest.

It becomes a problem when it compounds: allocation rate drives young-collection frequency, each young collection has a fixed cost and promotes anything live at that moment, and in a latency-sensitive service more frequent pauses show up in p99.

The fix here is cheap and obviously correct, so I make it, but I would not claim it saved the service without measuring the GC pause count before and after.

Q29 · Scenario. "The same switch over an enum is copy-pasted in a dozen places; a new constant was added, one switch was missed, and it caused a production bug. What design fixes this class of bug?"

Reveal answer

Strong answer The bug class is "behavior about the enum living far from the enum", and there are three designs that kill it:

  1. Move the behavior into the enum with constant-specific method bodies: declare an abstract method on the enum — say abstract Money fee(Money amount); — and have each constant supply its own implementation in its own body. Now adding a constant without its behavior does not compile, and the dozen switches collapse into polymorphic calls like type.fee(amount).
  2. When the behavior doesn't belong inside the enum — for example it needs services the enum shouldn't know about — use a strategy table: an EnumMap from constant to handler, built in one place, with a startup check that every constant has an entry. The gap becomes a boot-time failure instead of a silent branch.
  3. Where a switch genuinely stays, use a modern switch expression with no default: the compiler requires it to cover every constant, so a new constant breaks the build at each remaining switch. It was the default branches — and old-style statements — that swallowed the new case silently.

The trade-off to name: behavior in the enum couples the enum to that logic, while the map decouples but needs the completeness check. Either beats scattered switches.

Picture it Twelve copies of a switch means twelve places that can forget a new constant, and moving the behaviour into the constant leaves only one place that can.

The setup: a fee rule copy-pasted in several switches, and then a new constant.

scattered switchesruns offline
enum Type { CARD, BANK }                      // later: + WALLET

Money fee(Type t, Money a) {
    switch (t) {                              // ❌ TRAP: statement switch, no default, silently does nothing
        case CARD: return a.percent(2);
        case BANK: return Money.ZERO;
    }
    return Money.ZERO;                        // WALLET lands here: wrong, and no error
}

Make the invisible visible: which switches notice the new constant.

switch audit
switch location        statement + default   switch expression, no default   constant-specific body
billing  fee()            ✗ silent           ✓ compile error                  ✓ compile error
export   label()          ✗ silent           ✓ compile error                  ✓ compile error
… ten more …              ✗ silent           ✓ compile error                  ✓ one place only

The fix: put the behaviour next to the constants so a missing implementation cannot compile.

constant-specific methodsruns offline
enum Type {
    CARD   { Money fee(Money a) { return a.percent(2); } },
    BANK   { Money fee(Money a) { return Money.ZERO; } },
    WALLET { Money fee(Money a) { return a.percent(1); } };   // ✅ FIX: forced to write this
    abstract Money fee(Money a);
}
// call sites: type.fee(amount)   // ✅ no switch left to forget

What you see now: forgetting WALLET's body is a compile error, and an old switch expression reports the gap.

javac output
// enum constant without a body for the abstract method: compile error (message names fee(Money))
// switch expression over Type with no default and no WALLET case:
error: the switch expression does not cover all possible input values

Land it Put the behavior where the constants live, or make every gap a compile-time or boot-time failure — never a silent default.

Likely follow-ups
"How does the compiler know a switch expression is exhaustive over an enum, and what about separately compiled code?"

At compile time it checks that every constant of the enum's current definition has a case, so if the enum and the switch are compiled together, adding a constant fails the build at each switch.

The runtime hole is separate compilation: if the enum lives in another jar that is upgraded without recompiling the switch, the compiled switch has no case for the new constant.

For that situation the compiler inserts a synthetic default that throws MatchException since JDK 21, or IncompatibleClassChangeError in earlier versions. So you get a loud failure rather than silent fall-through. That is strictly better than the old statement switch, whose missing case did nothing at all.

"What are the downsides of constant-specific method bodies?"

Three. Each constant with a body compiles to its own anonymous subclass, so MyStatus.ACTIVE.getClass() is not MyStatus.class, which trips code that switches on getClass() or uses it as a map key; use getDeclaringClass().

The enum can no longer be a simple value holder because it now depends on whatever the bodies call, so a Status enum in a shared model module can end up importing pricing logic.

And the bodies are hard to test in isolation and impossible to swap for a fake. So I use bodies for behaviour intrinsic to the constant, such as Operation.PLUS.apply(a, b), and the strategy map when the behaviour belongs to a service.

"How would you write the startup completeness check for the strategy map?"

Build the EnumMap in one place and then assert coverage before the application accepts traffic. Concretely: var missing = EnumSet.complementOf(EnumSet.copyOf(handlers.keySet())) and throw IllegalStateException naming the missing constants if it is not empty.

In Spring, that lives in a @PostConstruct method or a SmartInitializingSingleton, so a deploy with a gap fails its readiness check and is rolled back automatically. An equivalent unit test that iterates values() and asserts each has a handler catches it earlier.

The key property is that the check enumerates the constants mechanically rather than listing them by hand, so it cannot itself go stale.

"The enum is in a shared library and you cannot change it. What then?"

Then I centralise on my side.

I write one switch expression with no default in a single adapter class that converts the foreign enum into my own sealed interface or my own enum with behaviour, so there is exactly one place that must change when the library adds a constant, and the compiler flags that place.

Every other use in my code works with my type. I add a test that asserts ForeignStatus.values().length equals a known number, with a comment saying "if this fails, the library added a constant, update the adapter", which turns the dependency upgrade into a visible task.

That is the pragmatic version of sealing when you do not own the type.

Q30 · Scenario. "You maintain a widely implemented public interface and need to add a method without breaking dozens of implementors. What does a default method buy you, and what can still go wrong?"

Reveal answer

Strong answer A default method buys binary compatibility — the guarantee that already-compiled implementors keep linking and running. I add the method with a sensible body, existing classes inherit it, and nobody is forced to recompile; this is exactly how Java 8 added forEach and stream() to Collection without breaking twenty years of implementations. What can still go wrong is subtler:

  1. Silent capture: if some implementing class already declares a method with the same signature, the class's method wins over my default with no warning of any kind. Their method now fulfills my interface's contract without ever having been written for it — the code compiles, runs, and may quietly violate the semantics I documented.
  2. New diamonds: a class implementing my interface and another one that declares the same default now hits the unrelated-defaults compile error on its next recompile — source-level breakage even though binaries still run.
  3. Contract limits: a default can only be written in terms of the interface's other methods, since it has no state, and defaults cannot override Object methods like equals or toString. If the new method needs per-instance state, a default cannot honestly implement it, only fake it or throw.

So my process is: choose a default whose behavior is correct when expressed through existing methods, search major implementors for signature clashes before shipping, and document the default's contract explicitly.

Picture it Adding a default method keeps old binaries linking, but the class-wins rule can quietly route calls to an unrelated method that already had the same name.

The setup: a published interface gains a default, and two implementors react differently.

interface evolutionruns offline
interface Exporter {                                  // v1: only export()
    void export();
    default String format() { return "csv"; }         // v2: new default
}
class Plain implements Exporter { public void export() { } }
class Legacy implements Exporter {
    public void export() { }
    public String format() { return "PDF-LANDSCAPE"; } // ❌ TRAP: written years ago for another meaning
}

Make the invisible visible: who answers format() after the release.

dispatch picture
new Plain().format()   ──▶ Exporter.format()         "csv"             ✓ the default you wrote
new Legacy().format()  ──▶ Legacy.format()           "PDF-LANDSCAPE"   ✗ class wins, no warning
old Plain.class (compiled against v1)  links and runs  ✓ binary compatible

What you see: reflection tells you which implementors silently own the method.

startup checkruns offline
for (Class<?> c : implementors) {
    Method m = c.getMethod("format");
    System.out.println(c.getSimpleName() + " -> " + m.getDeclaringClass().getSimpleName()
        + (m.isDefault() ? " (default)" : " (own method)"));
}
console
# illustrative output
Plain  -> Exporter (default)
Legacy -> Legacy (own method)      <- review this one

Land it Defaults make interface evolution binary-safe, not semantics-safe — the class-wins rule means someone else's old method can silently become your new contract.

Likely follow-ups
"What is the difference between binary compatibility and source compatibility here?"

Binary compatibility means existing compiled class files keep linking and running against the new version of my interface without recompilation; the JVM specification defines which changes preserve it, and adding a default method does. Source compatibility means existing source code still compiles against the new version.

Adding a default can break source compatibility while keeping binary compatibility: a class implementing my interface and another interface that already declares the same method compiles fine today, links fine against the new jar, but fails to compile the next time someone builds it.

Adding an abstract method breaks both. The distinction matters because the failures arrive at different times: a binary break at deploy, a source break at the next build.

"How does the JDK avoid the silent-capture problem in its own interfaces?"

By choosing method names that are unlikely to collide and by searching. When Collection.stream() was added in JDK 8, the team scanned large corpora of open-source code for existing methods called stream() on collection implementors, and the same for forEach and removeIf.

Where collisions existed, the default was designed so the existing method's likely semantics were compatible, or the name was changed.

They also use the convention that a default should be expressible entirely in terms of the interface's existing abstract methods, so a correct implementor gets a correct default.

For my own APIs I do a cheaper version: search all known implementors in our monorepo and dependency graph for the signature before shipping.

"How would you verify in production that implementors are getting the default rather than their own method?"

Reflection at startup. For each implementing class, call clazz.getMethod("newMethod") and check method.isDefault() and method.getDeclaringClass(): if the declaring class is my interface, the default is in effect; if it is the implementing class, they have their own.

I would log the second case at warning level and, if the semantics matter, refuse to start. A lighter option is a unit test in the library that runs the same check over a list of known implementors.

And I add the interface's contract to the method's Javadoc with the phrase "implementations that override this must preserve...", so a reviewer reading the implementor's code has something to check against.

"When should you break the interface instead of adding a default?"

When the new method cannot be implemented correctly without state or knowledge the interface does not have, so any default would be a lie. A default that throws UnsupportedOperationException just moves the failure to runtime and hides it from the compiler.

In that case the honest options are a new sub-interface, ExtendedRepository extends Repository, that implementors opt into, or a major-version bump that adds the abstract method and forces everyone to implement it consciously.

The sealed alternative applies when I control all implementors: then there are no unknown implementors, and adding an abstract method is a compile-time task list rather than a compatibility concern.

Drill · Ordering, Optional, lambdas & copying

This group tests judgment — whether you know the contracts behind sorted collections, the intended lane for Optional and var, and what lambdas actually capture.

Q31 · Scenario. "A TreeSet built with a comparator on price reports fewer elements than were added — items are silently vanishing. Here's the comparator. Diagnose it."

Reveal answer

The real test Knowing that sorted collections define equality by compare, and never consult equals at all.

Strong answer My diagnosis:

  1. Reproduce and measure: pour the same elements into a HashSet and compare sizes. The HashSet holds more — so the loss is specific to the sorted structure, which points at the comparator, because a TreeSet uses only compare to decide both ordering and duplicates. It never calls equals or hashCode.
  2. Inspect the comparator: it compares price alone, so two different products with the same price compare as 0, the set treats the second as a duplicate of the first, and add returns false and drops it silently.
VanishingProducts.java
Set<Product> byPrice = new TreeSet<>(
        Comparator.comparing(Product::price));

byPrice.add(new Product("SKU-1", 999));
byPrice.add(new Product("SKU-2", 999));   // compare == 0 -> "duplicate", dropped
System.out.println(byPrice.size());       // prints 1

// Fix: break ties on a unique key, so 0 means "same product":
Set<Product> fixed = new TreeSet<>(
        Comparator.comparing(Product::price)
                  .thenComparing(Product::sku));

The rule being violated is consistency with equals: the ordering should return 0 exactly when equals returns true, and this comparator returns 0 for objects that are not equal. The fix is a tie-breaker on a unique key via thenComparing; alternatively keep uniqueness in a HashSet and sort only when displaying. Prevention: any comparator used inside a TreeSet or TreeMap must be total down to identity of the value, and that goes in the code-review checklist.

Picture it A TreeSet is a sorted tree where compare()==0 means 'this key is already here', so a price-only comparator makes the second product look like a duplicate. Use the VanishingProducts code above as the setup.

Make the invisible visible: the red-black tree before and after add(SKU-2), with the comparison that decides it.

tree picture
BEFORE                         add(Product("SKU-2", 999))        AFTER
                               compare(SKU-2, SKU-1)
   [SKU-1 / 999]               = Integer.compare(999, 999) = 0   [SKU-1 / 999]
   size = 1                    0 means "same key"                size = 1
                               → no new node, add returns false  (SKU-2 is gone)

The trace: what TreeSet.add does with each element, in order.

add trace
add(SKU-1, 999)  tree empty                     → root created            ✓ returns true
add(SKU-2, 999)  compare with root = 0          → treated as duplicate    ✗ returns false
add(SKU-3, 500)  compare with root < 0          → left child              ✓ returns true
hashCode / equals consulted anywhere?  never

What you see: the same three products in a HashSet and in the TreeSet.

console
# illustrative output
new HashSet<>(products).size()                       -> 3
new TreeSet<>(Comparator.comparing(Product::price)) ... addAll(products) -> size 2
byPrice.add(SKU-2) returned false

What you see now: after thenComparing(Product::sku), a tie on price falls through to the SKU.

tree picture
compare(SKU-2, SKU-1): price 999 = 999 → tie → compare sku "SKU-2" vs "SKU-1" > 0 → right child
   [SKU-1 / 999]
          └── [SKU-2 / 999]      size = 3 with the third product, nothing vanishes

Land it In a sorted collection, compare-equals-zero IS equality — a comparator on one field turns every tie into a silent deletion.

Likely follow-ups
"You added thenComparing on SKU and elements still vanish. What next?"

Then either SKU is not unique or something in the chain is unstable. First I check the data: two products with the same SKU are legitimately duplicates in a set keyed by SKU, so the vanishing may be correct behaviour that nobody expected.

Second I check for null: Comparator.comparing(Product::sku) throws NullPointerException on a null SKU rather than dropping the element, so silence points elsewhere.

Third I check whether price is a double compared by subtraction or a BigDecimal, where compareTo ignores scale so 9.99 and 9.990 tie; use BigDecimal::compareTo deliberately.

Finally I test the comparator directly on the missing element against each survivor and assert antisymmetry, which turns the vanishing into a failing test.

"What if the requirement is genuinely 'sorted by price, keep all products'?"

Then a TreeSet on price is the wrong structure, because a set by definition cannot hold two elements the comparator calls equal. The options: a TreeSet with a total comparator that ends in a unique key, price then SKU, which keeps everything and sorts by price with a deterministic tie order; or a List sorted with List.sort(Comparator.comparing(Product::price)), which is stable and keeps duplicates; or a TreeMap<BigDecimal, List<Product>> when you want to look up by price band. The interviewer wants to hear that "sorted" and "set" are separate requirements, and that a comparator is defining membership in a sorted set, not just ordering.

"Does the same bug happen with sorted streams or Collections.sort?"

No, and that is why it hides. List.sort, Collections.sort, and Stream.sorted use TimSort, which is stable and never drops elements: two products with equal price stay in their original relative order.

So a comparator on price alone works perfectly for display sorting, and the same comparator silently destroys data when reused in a TreeSet or as the key order of a TreeMap.

That mismatch is the trap: the comparator was probably written for sorting and then reused for a set.

My review rule is that a comparator passed to a sorted collection constructor must be total down to identity, and I check the last thenComparing for a unique field.

same comparator, two containersruns offline
List<Product> l = new ArrayList<>(List.of(p1, p2));                  // both price 999
l.sort(Comparator.comparing(Product::price));                        // ✅ stable sort keeps both
new TreeSet<>(Comparator.comparing(Product::price)).addAll(l);       // ❌ TRAP: size 1, one is dropped
"How would you write a test that catches a non-total comparator before it reaches a TreeSet?"

A property test: generate pairs of distinct products, and assert that compare(a, b) == 0 implies a.equals(b). With jqwik or a simple loop over a fixture list of a few hundred products, this fails immediately for the price-only comparator.

For contract violations more broadly, assert antisymmetry, sign(compare(a, b)) == -sign(compare(b, a)), and transitivity over triples.

Since JDK 7, TimSort also detects some inconsistent comparators at runtime and throws "Comparison method violates its general contract", so running the comparator over a large shuffled list in a test is a cheap extra check.

The test lives next to the comparator, so it travels with the reuse.

Q32. "Explain 'consistent with equals' for Comparable. When is it safe to violate, and when is it not?"

Reveal answer

Strong answer Comparable defines a class's natural order through compareTo, and its documentation strongly recommends that the order be consistent with equals: a.compareTo(b) == 0 exactly when a.equals(b).

The reason is that the two families of collections use different notions of sameness — hash-based collections use equals and hashCode, while TreeSet and TreeMap use only the comparison. When the two disagree, the same data behaves differently depending on the container.

The standard library's own offender is BigDecimal: 1.0 and 1.00 are not equals, because equals compares scale, but compareTo says 0 — so a HashSet holds both while a TreeSet keeps only one.

Violating is tolerable when the type will only ever be sorted — ordering a list for display — and the class documents the inconsistency, as BigDecimal does.

It is never safe when instances go into sorted sets or maps, where compare-zero silently becomes the definition of duplicate.

Picture it BigDecimal 1.0 and 1.00 are different keys to a hash table and the same key to a tree, so one HashSet and one TreeSet disagree about the same data.

The setup: the same two values added to a HashSet and to a TreeSet.

two containers, two answersruns offline
BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("1.00");
Set<BigDecimal> hash = new HashSet<>(List.of(a, b));   // ❌ TRAP: equals sees scale
Set<BigDecimal> tree = new TreeSet<>(List.of(a, b));   // compareTo sees only the numeric value
System.out.println(hash.size() + " " + tree.size());   // Result: 2 1

Make the invisible visible: what each BigDecimal holds and which test each container uses.

data picture
a = 1.0   unscaledValue=10   scale=1   hashCode = 31*10  + 1 = 311   → bucket 311 & 15 = 7
b = 1.00  unscaledValue=100  scale=2   hashCode = 31*100 + 2 = 3102  → bucket 3102 & 15 = 14

HashSet: [7] a    [14] b          equals(a,b) = false (scales differ)     → 2 elements
TreeSet: [ a ]                    compareTo(a,b) = 0  → "already present"  → 1 element

The fix: pick one meaning of equality and make both containers agree, by fixing the scale or normalising.

one scale everywhereruns offline
BigDecimal a = new BigDecimal("1.0").setScale(2, RoundingMode.HALF_EVEN);   // ✅ FIX: 1.00
BigDecimal b = new BigDecimal("1.00").setScale(2, RoundingMode.HALF_EVEN);  // 1.00
// or normalise before use: a.stripTrailingZeros()   (both become 1)

What you see now: both containers hold one element.

console
a.equals(b)        -> true
a.compareTo(b)     -> 0
hash.size() + " " + tree.size()   -> 1 1

Land it Sorting tolerates an inconsistent order; sorted collections do not — decide which world your type lives in and document it.

Likely follow-ups
"How do you compare BigDecimal values for equality correctly, then?"

Decide which notion you need and make it explicit. For numeric equality, where 1.0 and 1.00 are the same amount, use a.compareTo(b) == 0, or normalise with stripTrailingZeros() before calling equals.

For exact equality including scale, which matters if scale carries meaning such as currency minor units, use equals.

In a money type I would store amounts in a fixed scale, setScale(2, RoundingMode.HALF_EVEN) in the constructor, so equals and compareTo agree by construction and the type is safe in both hash and sorted collections.

Never put raw BigDecimal keys of mixed scale into a HashMap; that is the same value appearing as two keys.

"Where else in the JDK does compareTo disagree with equals?"

BigDecimal is the famous one. String.CASE_INSENSITIVE_ORDER is a comparator inconsistent with String.equals by design, so a TreeSet built with it merges "ACTIVE" and "active", which can be exactly what you want or a data-loss bug.

Double.compareTo is the opposite: it is consistent with equals, treating NaN as equal to itself and greater than everything, while the == operator says NaN != NaN; so Double boxes behave in sorted sets but a primitive comparison would not.

java.time types are consistent, but ZonedDateTime.compareTo orders by instant then zone, which surprises people expecting instant-only ordering. Each is documented, which is the standard I hold my own types to.

"Should a class implement Comparable at all, or just supply comparators?"

Implement Comparable only when there is one obvious natural order that every reasonable use agrees on: numbers, strings, dates, version numbers.

If there are several plausible orders, a product by price or by name or by SKU, implementing Comparable picks one arbitrarily and invites the sorted-set bug when someone assumes it is total.

For those types I provide named comparators as static fields, Product.BY_PRICE_THEN_SKU, and leave Comparable off, so the caller must state the order. Records do not get a generated compareTo for exactly this reason.

And when a natural order exists but is not consistent with equals, the Javadoc must say so, as BigDecimal does.

Q33. "What problem was Optional designed to solve, and how should a caller consume one properly?"

Reveal answer

Strong answer Optional was designed for one job: to be a method's return type when "no result" is a normal, expected outcome, so the possibility of absence is written into the signature instead of hidden behind a null that explodes three stack frames later.

A returned null is an invisible contract; a returned Optional<Customer> forces every caller to visibly decide what absence means for them.

Consuming one properly means staying in its fluent style:

  • Transform: map and filter.
  • Fall back: orElseGet or a lazily-built default.
  • Fail meaningfully: orElseThrow carrying a domain exception.
  • Act: ifPresent.

The anti-pattern is isPresent() followed by get(), which is just a null check wearing a costume and keeps the unsafe shape; bare get() is the same landmine as unchecked dereference, which is why orElseThrow() is now the preferred spelling even when you expect presence.

Picture it A method returning null hides absence behind a reference, while one returning Optional puts a visible box in the signature, and the fluent methods are the safe ways to open it.

The setup: a lookup that may find nothing, consumed in the unsafe and the safe style.

consuming an Optionalruns offline
Optional<Customer> found = repo.findById(42);

found.get();                                           // ❌ TRAP: NoSuchElementException when empty
if (found.isPresent()) { use(found.get()); }           // ❌ a null check in a costume

String city = found.map(Customer::city).orElse("n/a");        // ✅ transform, then default
Customer c  = found.orElseThrow(() -> new NotFound(42));      // ✅ domain error
found.ifPresent(this::welcome);                                // ✅ act only when present

Make the invisible visible: the three shapes a lookup result can take in memory.

memory picture
stack                  heap
found ──▶ [ Optional | value ──▶ [ Customer #42 ] ]     present: a 16-byte box
found ──▶ Optional.EMPTY  (one shared object, value = null)   empty
found ──▶ null                                        ✗ never return this from an Optional method

What you see: get() on the empty box.

stack trace
# illustrative output
Exception in thread "main" java.util.NoSuchElementException: No value present
    at java.base/java.util.Optional.get(Optional.java:143)
    at Shop.greet(Shop.java:21)

What you see now: with orElseThrow the failure is a deliberate, named exception.

stack trace
# illustrative output
Exception in thread "main" NotFound: customer 42
    at Shop.lambda$greet$0(Shop.java:21)      // the line number points at the decision, not at a bare get()

Land it Optional moves absence from the runtime into the type signature — consume it with the fluent methods or you've re-created the null check you were escaping.

Likely follow-ups
"What does Optional cost, and when does that matter?"

An Optional is an ordinary object with one reference field, so a present value costs 16 bytes plus a pointer indirection, and Optional.empty() is a shared singleton that costs nothing. In a request handler that is invisible.

It matters in tight loops and in collections: a List<Optional<X>> doubles the object count, and a stream with map(Optional::of) per element allocates per element.

The JIT's escape analysis usually removes an Optional that is created and consumed within one inlined method, so the fluent chain find(id).map(...).orElse(...) is often allocation-free after warm-up. OptionalInt, OptionalLong and OptionalDouble exist to avoid boxing for primitives.

So my rule: fine at API boundaries, avoided in hot inner loops and as collection elements.

"How should Optional interact with exceptions — when do you throw instead?"

Return Optional when absence is a normal outcome the caller must decide about: a lookup by an id that may not exist.

Throw when absence is a violated precondition or an infrastructure failure: the database is unreachable, or the caller passed an id that the system guarantees exists. The test I use is whether every caller would handle absence differently.

If they all do the same thing, such as respond 404, then a domain exception caught once at the boundary is simpler than an orElseThrow at every call site.

Never use Optional to signal errors with detail, since it carries no reason; and never return null from a method typed Optional, which is the one unforgivable combination.

"Why is Optional not Serializable, and why does that matter for you?"

The designers deliberately left Optional unserialisable to discourage using it as a field or in DTOs. It is meant to live briefly on the stack between a method return and its consumer.

The consequence is that putting an Optional into a session-scoped object, a Hibernate entity, or anything sent through Java serialisation fails with NotSerializableException. Jackson can serialise it with the jackson-datatype-jdk8 module, but that produces a wire format that mirrors an implementation detail.

So in practice: unwrap to a nullable field or a sentinel before storing, and return Optional from the accessor if you want the call-site clarity. That split keeps the type in its lane.

"What are or, flatMap, stream and ifPresentOrElse for?"

flatMap chains lookups that each return Optional without nesting: findOrder(id).flatMap(Order::customer) yields Optional<Customer> rather than Optional<Optional<Customer>>. or(() -> otherLookup()), from JDK 9, tries a second source lazily when the first is empty and returns an Optional so chaining continues. stream() turns an Optional into a zero-or-one-element stream, so list.stream().map(this::find).flatMap(Optional::stream) drops the empties in one pass. ifPresentOrElse(consumer, runnable) handles both branches with side effects, replacing the isPresent check. Knowing these removes almost every reason to call isPresent and get, which is what the interviewer is really checking.

Q34. "Why are Optional fields and Optional method parameters considered bad style, when Optional return values are encouraged?"

Reveal answer

Strong answer Because Optional's value is in communicating with a caller, and fields and parameters have no caller to inform.

An Optional field is strictly worse than a nullable field: it adds a wrapper allocation per instance, it is not serializable, frameworks that reflect over fields mishandle it, and it actually has three states — present, empty, and the Optional reference itself being null — so it reintroduces the null problem it was meant to remove.

Inside the class, the author already knows which fields may be absent and can just handle it.

An Optional parameter is worse than an overload: it forces every caller to wrap with Optional.of or pass Optional.empty(), and a hostile or careless caller can still pass null for the Optional itself, so the method must null-check the container anyway.

Two overloads, or a clearly annotated nullable parameter, state the same intent with less ceremony. The API's own authors, Brian Goetz included, describe the intended scope as return values only.

Picture it A nullable field has two states but an Optional field has three, and an Optional parameter lets the caller hide a null inside the box.

The setup: a class with an Optional field and a method with an Optional parameter.

Optional where it does not belongruns offline
class User {
    private Optional<String> nickname;                  // ❌ TRAP: field is Optional
    boolean hasNick() { return nickname.isPresent(); }  // NPE if the field itself is null
}
void send(Message m, Optional<Priority> p) { ... }      // ❌ TRAP: parameter is Optional
send(msg, null);                                        // compiles: the box itself is null

Make the invisible visible: every state the field can be in.

state picture
nullable String nickname           Optional<String> nickname
  null        → absent               null              → absent?   (the box is missing)
  "ann"       → present              Optional.empty()  → absent    (the box is empty)
                                     Optional.of("ann")→ present
2 states                            3 states, and an extra object per User

What you see: the exact failure the wrapper was meant to prevent.

stack trace
# illustrative output
Exception in thread "main" java.lang.NullPointerException
    at User.hasNick(User.java:5)       // nickname was never assigned, so isPresent() hit null

The fix: keep the field plain and nullable, return Optional from the accessor, and use overloads for optional inputs.

Optional only on the returnruns offline
class User {
    private @Nullable String nickname;                          // ✅ FIX: plain nullable field
    Optional<String> nickname() { return Optional.ofNullable(nickname); }
}
void send(Message m) { send(m, Priority.NORMAL); }              // ✅ FIX: overloads
void send(Message m, Priority p) { ... }

What you see now: no wrapper object per user and no third state.

state picture
nickname  null | "ann"                       2 states, no extra allocation
user.nickname()  → Optional built on demand  (short-lived, usually removed by escape analysis)

Land it Optional is a return-channel signal — everywhere else it adds a box, a third state, and no information the code didn't already have.

Likely follow-ups
"How do you express a nullable field or parameter, then?"

With a nullness annotation the tools understand. As of Aug 2026 the JSpecify annotations, @Nullable and @NullMarked, are the cross-tool standard, adopted by Spring Framework 7, Guava, and supported by NullAway, the Checker Framework, IntelliJ and Kotlin.

I mark packages @NullMarked so everything is non-null by default, and annotate the few nullable fields and parameters. The compiler plugin then reports a dereference without a null check as a build error, which is stronger than Optional ever was, because it covers fields and parameters.

For parameters, I additionally prefer overloads over a nullable parameter when the null case is really a different operation.

"Is there any exception to the 'no Optional fields' rule?"

One pragmatic case: a private field that caches the result of a lookup which can legitimately be absent, where the field must distinguish "not computed yet" from "computed and empty".

A nullable field cannot express three states, so an Optional field, or better an explicit small enum or a sentinel, is defensible. Even then I keep it private and never expose it.

Some teams also accept Optional in immutable records used purely inside one module to model absent components, and Jackson handles it.

I would not fight that in review, but I would point out that a record with a nullable component and an Optional-returning accessor gets the same clarity without the serialisation problems.

"Why is an Optional parameter worse than an overload in practice?"

Because it moves work to every caller and still fails to guarantee anything.

A method send(Message m, Optional<Priority> p) forces callers to write Optional.of(HIGH) or Optional.empty(), which is noise, and a caller can still pass null for the Optional itself, so the method must check for that too.

Two overloads, send(m) and send(m, priority), let each caller say exactly what it means and let the compiler enforce that priority is present in the second. For methods with several optional inputs, a builder or a parameter record with defaults scales better than either.

The Optional parameter is the worst of all options, which is why Sonar flags it.

Optional parameter in useruns offline
send(msg, Optional.of(Priority.HIGH));   // noise at every call site
send(msg, Optional.empty());             // noise
send(msg, null);                         // ❌ compiles; p.isPresent() inside send throws NullPointerException
send(msg);  send(msg, Priority.HIGH);    // ✅ FIX: two overloads say the same thing

Q35 · Scenario. "A metrics dashboard shows an expensive fallback query running on every request, even though the primary value is almost always present. The code uses Optional.orElse. What's wrong?"

Reveal answer

Strong answer The bug is eager evaluation of the fallback argument:

  1. Correlate the metrics: the fallback query count roughly equals total request count, not the miss count — so the fallback is executing even on hits. That pattern says the fallback is being computed unconditionally, though its result is usually discarded.
  2. Read the call: cache.lookup(id).orElse(loadFromDb(id)). In Java, arguments are evaluated before the method runs, so loadFromDb(id) executes on every single call — orElse only decides afterwards whether to use the result or throw it away. The database pays either way.
  3. Fix: switch to orElseGet(() -> loadFromDb(id)), which takes a supplier — a deferred piece of code — and invokes it only when the Optional is actually empty. Verify on the dashboard that fallback executions drop to the miss rate.
  4. Prevent: adopt the team rule that orElse is only for constants and pre-computed values — orElse(Collections.emptyList()) is fine — and anything involving a call, allocation of consequence, or a side effect like logging goes through orElseGet. IDE inspections can flag non-trivial orElse arguments automatically.

Picture it orElse(loadFromDb(id)) runs loadFromDb before orElse is even entered, so the query happens on every hit; orElseGet defers it behind a supplier.

The setup: a cache lookup with a database fallback, counted per call.

eager versus lazy fallbackruns offline
AtomicInteger dbCalls = new AtomicInteger();
Customer loadFromDb(long id) { dbCalls.incrementAndGet(); return db.select(id); }

Customer a = cache.lookup(id).orElse(loadFromDb(id));            // ❌ TRAP: argument evaluated first
Customer b = cache.lookup(id).orElseGet(() -> loadFromDb(id));   // ✅ FIX: runs only when empty

Make the invisible visible: the call order for one cache hit.

call trace
cache.lookup(id).orElse(loadFromDb(id))
 1 cache.lookup(id)        → Optional[Customer]            (a hit)
 2 loadFromDb(id)          → SELECT ... runs                ✗ evaluated BEFORE orElse
 3 orElse(result)          → ignores result, returns cached ✗ query thrown away

cache.lookup(id).orElseGet(() -> loadFromDb(id))
 1 cache.lookup(id)        → Optional[Customer]            (a hit)
 2 orElseGet(supplier)     → present, supplier never called ✓

What you see: 1000 requests with a 99 percent cache hit rate.

metrics
# illustrative output
orElse(loadFromDb(id))              : dbCalls = 1000     (equals request count)

What you see now: the same traffic after switching to orElseGet.

metrics
# illustrative output
orElseGet(() -> loadFromDb(id))     : dbCalls = 10       (equals miss count)

Land it orElse evaluates its argument always and uses it sometimes; orElseGet evaluates only when needed — cheap constants to the first, everything else to the second.

Likely follow-ups
"You switched to orElseGet and the fallback count did not drop. What next?"

Then the extra executions come from somewhere else, so I stop assuming and trace. First I confirm the deployed code is the new code, because a stale pod is the most common reason a fix "did not work".

Then I check whether the cache lookup itself is returning empty more than expected: a cache with a short TTL or a key mismatch, for example a trailing whitespace or a case difference in the key, makes every call a miss and the fallback is then correct behaviour.

I add a metric for cache hit ratio right at the lookup call and compare it with the fallback count. If hits are high and fallbacks are still high, I search for other call sites of loadFromDb, since the dashboard counts all of them.

"Is orElse ever preferable to orElseGet?"

Yes, for cheap, already-computed values, and for readability. orElse(0), orElse(""), orElse(List.of()) or orElse(defaultConfig) where the argument is a constant or a field cost nothing to evaluate and read more plainly than a lambda.

The JIT will also often optimise the trivial lambda away, so performance is not the deciding factor there.

Some style guides go further and mandate orElseGet everywhere to avoid the trap, which I think trades a small readability cost for safety and is a reasonable team rule.

What I will not accept in review is orElse with a method call, a constructor, or anything that logs, because the eager evaluation is then a bug in waiting.

"Does the same eager-argument trap exist elsewhere in the JDK?"

Everywhere Java has both a value and a supplier overload. Objects.requireNonNull(x, expensiveMessage()) builds the message on every call even when x is non-null; the Supplier<String> overload fixes it.

Logger.info("value: " + big.toString()) formats even when the level is disabled; the parameterised form or a supplier defers it. Map.getOrDefault(k, new ArrayList<>()) allocates every call; computeIfAbsent defers.

Optional.orElseThrow(new NotFound()) would construct the exception, with its stack trace, on every call, which is why the signature takes a supplier. CompletableFuture.completeExceptionally, assertion messages in test frameworks, same story.

The rule is that arguments are evaluated before the call, always, so anything conditional must be wrapped in a lambda.

eager versus deferred argumentsruns offline
Objects.requireNonNull(x, buildMessage());                  // ❌ TRAP: message built on every call
Objects.requireNonNull(x, () -> buildMessage());            // ✅ FIX: Supplier overload, built only on failure
map.getOrDefault(k, new ArrayList<>());                     // ❌ allocates on every call
map.computeIfAbsent(k, kk -> new ArrayList<>());            // ✅ allocates only on a miss (and stores it)
"How would you have caught this before it reached the dashboard?"

Three cheap layers. A static check: IntelliJ has an inspection for non-trivial orElse arguments and Sonar has a rule for it, so enabling one turns this into a build-time warning.

A unit test with a counting fake: the test asserts that when the primary returns a value, the fallback supplier is invoked zero times, which is a one-line assertion on a mock.

And a load test with the cache warmed, watching database query rate; if it equals request rate, something is bypassing the cache.

The dashboard did its job here, but the same metric, fallback rate versus request rate, belongs on a per-service alert so the next instance is caught in minutes rather than found in a review.

Q36. "What's your judgment call on var — where does it help readability, and where do you ban it?"

Reveal answer

Strong answer First the ground truth: var is local-variable type inference from Java 10 — the compiler deduces the exact static type from the initializer, so the code stays fully statically typed; nothing dynamic is happening.

My judgment rule is that var is good wherever the type is already on the line for the reader: constructor calls like var users = new ArrayList<User>(), obvious literals, and well-named factories — and it genuinely helps where generics noise buries the logic, like iterating Map.Entry pairs.

I avoid it where the reader would have to hover or dig:

  • Hidden return types: var result = service.process(order) hides the type exactly where a maintainer needs it.
  • Chained streams: the inferred type can differ from what you assume.
  • Numeric initializers: var n = 1 is an int when you may have wanted long.

The test I apply in review is simple: can the next engineer name the type without the IDE — an integrated development environment — telling them?

Picture it var is a spelling the compiler expands to the exact initializer type, so the table below shows what each line really declares.

The setup: five var declarations, some obvious and some not.

five var linesruns offline
var users = new ArrayList<User>();       // obvious: the type is on the line
var n = 1;                               // int, not long
var m = new HashMap<>();                 // ❌ TRAP: diamond with nothing to infer from
var r = service.process(order);          // ❌ TRAP: reader must open process() to know
var e = map.entrySet().iterator().next();

Make the invisible visible: what javac substitutes for each var.

what the compiler generates
var users = new ArrayList<User>();         →  ArrayList<User> users = ...    (not List<User>)
var n = 1;                                 →  int n = 1;
var m = new HashMap<>();                   →  HashMap<Object,Object> m = ...
var r = service.process(order);            →  (whatever process returns: invisible here)
var e = map.entrySet().iterator().next();  →  Map.Entry<String,Integer> e = ...

What you see: an int that was meant to be a long.

javac output
var total = 1;
total = 3_000_000_000L;
error: incompatible types: possible lossy conversion from long to int

The fix: spell the type where the initializer does not show it.

explicit typesruns offline
long total = 1;                                       // ✅ FIX: say what you mean
Map<String, Integer> counts = new HashMap<>();        // ✅ FIX: interface type, real generics
Receipt r = service.process(order);                   // ✅ FIX: the reader sees the type

What you see now: the same assignment compiles.

javac output
long total = 1;
total = 3_000_000_000L;        // compiles, no error

Land it var is for removing redundancy the reader can already see, never for hiding a type the reader would need to look up.

Likely follow-ups
"Does var change the bytecode or affect performance at all?"

No. var is resolved entirely by javac; the class file contains the inferred static type in the local variable table exactly as if you had written it, and the JIT never sees a difference.

It is not a keyword either, but a reserved type name, so old code with a variable called var still compiles, though a class named var does not.

The inferred type is the exact static type of the initialiser, which has one visible effect: var list = new ArrayList<String>() infers ArrayList<String>, not List<String>, so you lose programming-to-the-interface at the declaration. That is a readability and refactoring concern, not a runtime one.

"What are the surprising inferences, the cases where var infers something you did not intend?"

Four I have seen bite. var x = 1; is int, so a later x = 3_000_000_000L fails, and var d = 1 / 3; is integer division. var list = List.of(1, 2.0); infers List<Number & Comparable<...>>, an intersection type you could not write by hand.

var anon = new Object() { int x = 1; }; infers the anonymous class type, so anon.x compiles, which is neat but non-denotable. And var stream = list.stream().map(...) in a long chain can infer a wildcard-captured type that later refuses to be assigned.

Diamond with var, var m = new HashMap<>();, infers HashMap<Object, Object>, which is almost never what you meant.

surprising inferencesruns offline
var x = 1;                    // int
x = 3_000_000_000L;           // ❌ error: incompatible types: possible lossy conversion from long to int
var m = new HashMap<>();      // HashMap<Object,Object>
var list = List.of(1, 2.0);   // List<Number & Comparable<...>>, an intersection type
var anon = new Object() { int x = 1; };   // anonymous class type: anon.x compiles
"Can you use var for lambda parameters or fields, and why would you?"

Not for fields, method parameters, or return types; the designers limited it to locals, for-loop variables, and try-with-resources so that a type is always visible at API boundaries.

Since JDK 11 you can write var for lambda parameters, (var x, var y) -> x + y, which looks pointless until you need to annotate a parameter: (@Nullable var x) -> ... is the only way to attach an annotation without spelling the full type.

The rule is all-or-nothing within one lambda: you cannot mix var with explicit types or with bare names. That is the one place var adds capability rather than just brevity.

"How do you enforce your var policy across a team?"

With a written rule and a mechanical check, not with taste.

The rule, roughly: var is allowed when the initialiser is a constructor call, a literal, a cast, or a factory whose name contains the type; it is disallowed when the initialiser is a method call whose return type is not obvious from the name.

Checkstyle and Error Prone have configurable checks, and IntelliJ's "local variable type inference" inspections can be tuned to flag var on method-call initialisers.

In review the question I ask is the one from the JDK style guide: does the reader have enough information to understand the code without hovering? If a reviewer had to ask what the type was, that var comes out.

Q37. "Why can a lambda only capture local variables that are final or effectively final?"

Reveal answer

Strong answer Because a captured local is a copy, and copies of mutable variables lie.

Local variables live in the method's stack frame — the per-invocation scratch space that disappears when the method returns — while the lambda may run later, elsewhere, or on another thread, long after that frame is gone.

So the runtime copies the variable's value into the lambda object at creation time.

If reassignment were allowed, you would have two independent copies drifting apart while the code visually reads as one shared variable — the illusion of shared mutable state with none of the synchronization to make it safe.

Requiring the variable to be effectively final makes the copy indistinguishable from the original, so the model stays honest.

Instance fields have no such restriction because the lambda captures this and reads the live field — which is precisely why mutating a field from a lambda in a parallel stream is a real data race, and why the "one-element array" workaround for counters is a smell rather than a fix; AtomicInteger is the honest version.

why a lambda can only capture effectively final localsruns offline
// DOES NOT COMPILE
int count = 0;
list.forEach(item -> count++);      // "local variables referenced from a lambda
                                    //  expression must be final or effectively final"

// WHY: local variables live on the STACK FRAME of the enclosing method. A lambda
// can outlive that frame — it may be stored, passed to another thread, or run
// later. So the compiler COPIES the captured value into the lambda instance.
//
// If the variable could still change, there would be two copies that silently
// diverge, and no reasonable semantics for which one wins. Java forbids the
// question rather than answering it. (Instance FIELDS are captured through
// `this`, which is why they can be mutated — and why doing so is a data race.)

// THE WRONG WORKAROUND — a one-element array. It compiles because the ARRAY
// reference is effectively final; the contents are not. This is a data race
// waiting to happen if the lambda ever runs on another thread.
int[] count = {0};
list.forEach(item -> count[0]++);        // compiles, not thread-safe

// THE RIGHT ANSWERS:
long count = list.stream().filter(this::matches).count();       // just count
var count = new AtomicInteger();                                 // if truly concurrent
list.forEach(item -> count.incrementAndGet());
var total = list.stream().mapToInt(Item::size).sum();            // reduce properly

The array trick is the answer to watch for in review. It satisfies the compiler by moving the mutation behind a reference, which removes the error message without removing the reason the error existed.

Picture it A lambda carries a copy of each captured local, so the stack frame can vanish while the lambda lives on, and the compiler refuses any change that would make the copy and the original disagree. Use the first code block above as the setup.

Make the invisible visible: the stack and heap at the moment the lambda is created.

memory picture
stack (method frame)                    heap
  int base = 10  ───────copy────────▶  [ lambda | val$base = 10 ]
  list           ───────────────────▶  [ ArrayList ... ]
  (frame is popped when the method returns; the lambda object stays alive)

The trace: what would happen if reassignment were allowed.

divergence trace
int count = 0;
Runnable r = () -> System.out.println(count);   ✓ lambda holds a copy: 0
count = 5;                                      ✗ frame says 5, lambda copy still says 0
r.run();                                        two "count" values, one visible name

What you see: the compiler stops it at the assignment.

javac output
error: local variables referenced from a lambda expression must be final or effectively final

What you see now: with an effectively final local, the copy equals the original forever.

console
int count = 5;                                  // never reassigned afterwards
Runnable r = () -> System.out.println(count);
r.run();      // prints 5, from any thread, any time later

Land it The rule exists so a captured copy can never disagree with its original — the compiler is refusing to let you fake shared state.

Likely follow-ups
"How is a lambda actually compiled and where do the captured values go?"

javac desugars the lambda body into a private synthetic method on the enclosing class, named lambda$main$0 or similar, whose parameters are the captured variables followed by the lambda's own parameters. At the lambda expression it emits an invokedynamic instruction bootstrapped by LambdaMetafactory.

On first execution the JVM spins a small hidden class implementing the functional interface, with one final field per captured variable and a method that calls the synthetic method.

Each evaluation of a capturing lambda allocates an instance of that hidden class holding the captured values; a non-capturing lambda is created once and reused. You can see the synthetic method with javap -p, and the hidden classes with -Djdk.internal.lambda.dumpProxyClasses on older JDKs.

"Why does the one-element array workaround compile, and what is actually wrong with it?"

It compiles because the array reference is effectively final; only the contents change, and the rule is about the variable, not the object. What is wrong is that it recreates exactly the shared mutable state the rule was preventing, with no visibility or atomicity guarantee.

In a sequential forEach it works, but the same code under parallelStream loses increments and nobody sees a compile error. It also hides intent: a reader cannot tell whether the array is data or a hack.

AtomicInteger says "shared counter" in the type, is correct under parallelism, and costs a compare-and-swap. Better still is to not count by side effect at all and use count() or a collector, which is the stream-native shape.

"Do anonymous classes and local classes follow the same capture rule?"

Yes, since Java 1.1 anonymous and local classes could only capture final locals, and JDK 8 relaxed that to effectively final for both at the same time as lambdas.

The mechanism is identical: the compiler copies the captured value into a synthetic field, val$x, on the generated class via a hidden constructor parameter.

The differences are elsewhere: an anonymous class captures this as this$0 even when it does not use the enclosing instance, which has caused memory leaks in Android and in long-lived listeners, whereas a lambda captures the enclosing instance only if the body actually references it.

That difference in what gets retained is a real reason to prefer lambdas for callbacks stored long-term.

"What happens to captured values under virtual threads or when the lambda outlives the request?"

Nothing special, and that is the point of copying.

The captured values live in the lambda object on the heap, so the lambda can run on a virtual thread, a pool thread, or an hour later after the original frame is gone, and it still sees the same values.

The concern shifts to what was captured: capturing a request-scoped object such as a JPA session or a ThreadLocal-bound context and running the lambda later on another thread is a correctness bug, because the lambda holds a reference to something that is now closed or belongs to another request.

Scoped values, final in JDK 25, address the context part: a lambda run inside ScopedValue.where(...).run(...) sees the binding, and structured concurrency propagates it to children.

Q38 · Scenario. "An IDE conversion from an anonymous class to a lambda changed the program's behavior. The code used this. Explain what moved."

Reveal answer

Strong answer The meaning of this moved, and that is the one semantic difference the conversion cannot preserve:

  1. State the rule: an anonymous class is a real class, so inside it this refers to the anonymous instance itself, and reaching the outer object requires the qualified form Outer.this. A lambda is not a class and introduces no new this scope — inside a lambda, this is simply the enclosing instance.
  2. Map that to the failure: the anonymous listener called bus.unregister(this) to remove itself. As an anonymous class, this was the listener object, and unregistration worked. After conversion, this is the enclosing service object, which was never registered — the call silently removes nothing, the listener stays subscribed, and events double up. Any use of this for identity, logging, or passing "myself" shifts referent the same way; so does an unqualified call to a method the anonymous class had overridden.
  3. Fix: either keep the anonymous class, which is the correct tool when the code needs its own identity, or restructure — have the registration API hand back a subscription handle that the code stores and later cancels, removing the need for self-reference entirely.
  4. Prevent: treat "convert to lambda" hints as refactorings to review, not accept — the IDE checks syntax, and this difference is semantic.
the anonymous class that changed meaning as a lambdaruns offline
class Handler {
    private final String name = "handler";

    void register(Bus bus) {
        // ANONYMOUS CLASS: `this` is the anonymous class instance.
        bus.subscribe(new Listener() {
            @Override public void on(Event e) {
                System.out.println(this.getClass());   // Handler$1
                log(this);                             // passes the LISTENER
            }
        });

        // LAMBDA: `this` is the ENCLOSING instance. Lambdas do not introduce
        // a new scope for `this` — they are not objects with their own identity
        // in that sense.
        bus.subscribe(e -> {
            System.out.println(this.getClass());       // Handler
            log(this);                                 // passes the HANDLER
        });
    }
}

// This changes behaviour whenever `this` is used, and also:
//   - shadowing: an anonymous class may declare a field `name`; a lambda
//     cannot shadow an enclosing local at all (it is a compile error)
//   - a lambda has no meaningful getClass(), no instance initialiser,
//     and cannot be self-referential without a trick
//   - removing a listener by identity behaves differently, because the JVM
//     may reuse one lambda instance for a non-capturing lambda

The last point causes a real bug. A non-capturing lambda may be a single shared instance, so registering the "same" lambda twice and then unregistering once can remove both — whereas two anonymous class instances are always distinct objects.

Picture it Inside an anonymous class this is the anonymous object and inside a lambda it is the enclosing object, so a self-unregistering listener unregisters the wrong thing after conversion. Use the Handler code above as the setup.

Make the invisible visible: what this points at in each version.

memory picture
ANONYMOUS CLASS                          LAMBDA
heap                                     heap
[ Handler ]  ◀── this$0 ── [ Handler$1 ]    [ Handler ]   ◀── this (same object)
                              ▲ this
bus registered: Handler$1                bus registered: the lambda object
unregister(this) → Handler$1  ✓          unregister(this) → Handler   ✗ never registered

The trace: an event arrives and the listener tries to remove itself.

event trace
listener runs, calls bus.unregister(this)
  anonymous: this = Handler$1   → found in listener list   ✓ removed
  lambda:    this = Handler     → not in the list          ✗ nothing removed, no exception
next event: lambda listener still subscribed               ✗ handler runs twice

What you see: the class name printed from inside the callback.

console
# illustrative output
anonymous version: class Handler$1
lambda version:    class Handler

The fix: let registration return a handle and cancel the handle instead of using this.

subscription handleruns offline
Subscription s = bus.register(e -> handle(e));   // ✅ FIX: no self-reference needed
// later, from whoever holds s:
s.cancel();

What you see now: one cancel removes exactly one registration.

console
# illustrative output
events fired: 2, handler runs: 1       (cancelled after the first)

Land it An anonymous class owns a this; a lambda borrows the enclosing one — any code that needs its own identity must stay a class.

Likely follow-ups
"Besides this, what else can change meaning when converting to a lambda?"

Three more things. Shadowing: an anonymous class introduces a new scope, so a local x inside it may shadow the outer x; a lambda's body is in the enclosing scope, so the same declaration is a compile error, which is loud rather than silent.

Overload resolution: passing a lambda to an overloaded method such as submit(Runnable) versus submit(Callable) may pick a different overload than the explicit anonymous class did, especially when the body returns a value.

And identity: two evaluations of a non-capturing lambda may return the same instance, so code that used the anonymous object as a unique key in a map or set, for listener registration for instance, may collapse two registrations into one.

"The IDE suggested converting a listener that unregisters itself. What is the clean design?"

Give the registration a handle. Subscription s = bus.register(event -> ...) returns an object with cancel(), and the lambda can call s.cancel() via a holder, or the caller stores it. This removes the need for self-reference entirely and works for both lambdas and classes.

In the reactive world that is exactly what Disposable in Reactor and RxJava, and Flow.Subscription in the JDK, are for.

If the listener genuinely needs its own identity, for equality in a set for example, it should be a named class with explicit equals, not an anonymous class, because relying on the identity of an anonymous instance is the fragile assumption that broke here.

"How would you prove the referent of this changed, in a running system?"

Log System.identityHashCode(this) and this.getClass().getName() inside the callback before and after the conversion. In the anonymous version the class name is Service$1 and the identity differs from the service's; in the lambda version the class is Service and the identity equals the enclosing bean's.

Then check the bus: log what unregister received and whether the listener collection actually shrank. A unit test makes it durable: register, fire an event that triggers self-unregistration, fire again, and assert the handler ran exactly once.

That test would have failed the moment the IDE conversion was committed, which is the point of writing it.

proving what this refers toruns offline
// inside the callback, before and after the conversion
System.out.println(this.getClass().getName() + " @" + System.identityHashCode(this));
// anonymous: Service$1 @1163157884      lambda: Service @356573597   (the same as the enclosing bean)
"Does the memory-retention behaviour differ between the two forms?"

Yes, in the lambda's favour. An anonymous inner class always holds a reference to its enclosing instance through the synthetic this$0 field, whether or not it uses it.

A lambda only captures the enclosing instance if the body references this, an instance field, or an instance method; otherwise it is a non-capturing lambda with no link to the outer object.

So a lambda stored in a long-lived registry can be cheaper and can avoid pinning a large enclosing object, like a controller or a UI screen, in memory.

That was a well-known leak source in Android and in Swing listeners, and it is one argument for lambdas even when the code needs no functional style.

Q39. "Walk me through the four kinds of method references, and one behavioral difference between a method reference and the equivalent lambda."

Reveal answer

Strong answer The four kinds, each with its shape:

  • Static: Integer::parseInt — the parameters feed the static method directly.
  • Bound instance: myString::length — the receiver, the object the method runs on, is fixed to myString right now, and parameters feed the method.
  • Unbound instance: String::length — no receiver is fixed; the functional interface's first argument becomes the receiver at call time.
  • Constructor: ArrayList::new — parameters feed a constructor.

The behavioral difference worth naming is when the receiver expression is evaluated.

A bound reference like service::process evaluates service at the moment the reference is created — so if service is null, you get a NullPointerException immediately, at creation, and if the variable is later repointed the reference still targets the original object.

The lambda x -> service.process(x) evaluates service freshly on every invocation, so the failure surfaces later and rebinding is visible. Otherwise I choose by readability: a reference when the lambda merely forwards its arguments, a lambda the moment any logic appears.

Picture it Each of the four method-reference kinds has an equivalent lambda, and the bound kind fixes its receiver at the moment the reference is created.

The setup: the four shapes next to the lambda each one stands for.

four kinds and their lambdasruns offline
Function<String,Integer>  f1 = Integer::parseInt;      // static:   s -> Integer.parseInt(s)
Supplier<Integer>         f2 = myString::length;       // bound:    () -> myString.length()
Function<String,Integer>  f3 = String::length;         // unbound:  s -> s.length()
Supplier<List<String>>    f4 = ArrayList::new;         // ctor:     () -> new ArrayList<>()

Make the invisible visible: where the receiver comes from in each kind.

receiver picture
static    Integer::parseInt     args ──▶ parseInt(args)          no receiver
bound     myString::length      receiver = myString, FIXED NOW   args ──▶ method
unbound   String::length        receiver = FIRST ARGUMENT, at call time
ctor      ArrayList::new        args ──▶ new ArrayList(args)

The trace: a bound reference versus a lambda when the variable is null or repointed.

evaluation trace
Consumer<String> ref = service::process;     // service is null here
  creation time: receiver evaluated → null   ✗ NullPointerException right here

Consumer<String> lam = x -> service.process(x);
  creation time: nothing evaluated           ✓ creation succeeds
  first call:    service read now            ✗ NullPointerException later (or ✓ if service was set)
service = other;  → reference still targets the OLD object, lambda sees the NEW one

What you see: the failure moves from creation to first call.

stack trace
# illustrative output
reference: NullPointerException at Main.main(Main.java:8)     <- the line that built the reference
lambda:    NullPointerException at Main.lambda$main$0(Main.java:9)   <- the line that ran it

Land it A bound method reference captures its receiver at creation, a lambda looks it up per call — same shape, different moment of truth.

Likely follow-ups
"How does the compiler decide whether String::length is bound or unbound?"

By what is to the left of the ::.

If it is a type name, String::length, the reference is either static or unbound instance; the compiler resolves which by looking at the functional interface's parameter list: for Function<String, Integer>, the first parameter becomes the receiver, so it is unbound.

If the left side is an expression, myString::length or this::process or super::process, it is bound and the expression is evaluated once, at that point.

Ambiguity is possible: a class with both a static m(Foo) and an instance m() makes Foo::m ambiguous for a Function<Foo, R>, and the compiler reports it. That ambiguity is the one time I switch to an explicit lambda.

ambiguous method referenceruns offline
class Foo { static int m(Foo f) { return 1; }  int m() { return 2; } }
Function<Foo,Integer> f = Foo::m;               // ❌ compile error: reference to m is ambiguous
Function<Foo,Integer> g = foo -> foo.m();       // ✅ FIX: the lambda names the instance method
"Are method references faster than lambdas?"

No measurable difference after the JIT warms up; both go through invokedynamic and LambdaMetafactory, and both end up as a small hidden class calling the target.

A method reference to a static or unbound method is non-capturing, so it is allocated once and cached at the call site; a bound reference captures its receiver and allocates per evaluation, exactly like a capturing lambda.

One minor difference is that a method reference has no synthetic lambda$ method, so stack traces are one frame shorter and startup is a tiny bit cheaper per site.

If someone claims a performance difference, I ask for the JMH benchmark, because the answer is almost always "within noise".

"Can a method reference target a varargs method, a generic method, or a constructor with arguments?"

All three, with care. A varargs target works when the functional interface's parameters can be wrapped into the array, so String::format can be a BiFunction<String, Object, String>, but the boxing and array creation happen on each call.

A generic method can be referenced with explicit type arguments, Collections::<String>emptyList, when inference fails.

A constructor reference, ArrayList::new, picks the constructor matching the interface: as a Supplier it is the no-arg one, as an IntFunction it is the capacity one, which is why toArray(String[]::new) works, since array constructors accept a length.

When the overload chosen is not obvious, I write the lambda so a reader does not have to run inference in their head.

Q40. "People say clone() is broken. Make that case honestly, and tell me what you use instead."

Reveal answer

Strong answer The case has four counts:

  1. Back-to-front design: Cloneable is a marker interface — an interface with no methods — that doesn't declare clone at all. It merely flips the behavior of the protected Object.clone, which is an extralinguistic trick no other API uses.
  2. Shallow by default: Object.clone duplicates fields one by one, so every mutable field ends up shared between original and copy unless each class remembers to deep-copy it by hand.
  3. Bypasses constructors: invariants enforced there never run. Because final fields can't be reassigned inside clone, a final mutable field simply cannot be deep-copied correctly.
  4. Taxes the whole hierarchy: every subclass must call super.clone() and cooperate, plus swallow the checked CloneNotSupportedException.

What I use instead: a copy constructor, new Order(other), or a static factory like Order.copyOf(other) — explicit, constructor-based, final-field friendly, and free to choose copy depth. Best of all, immutable types need no copying, and for arrays specifically, clone() is actually fine.

Picture it clone() copies the outer object's fields one by one, so two objects end up pointing at the same mutable list.

The setup: an Order that is Cloneable and holds a list.

shallow cloneruns offline
class Order implements Cloneable {
    List<String> items = new ArrayList<>();
    @Override public Order clone() throws CloneNotSupportedException {
        return (Order) super.clone();                   // ❌ TRAP: items reference is copied, not the list
    }
}
Order a = new Order(); a.items.add("book");
Order b = a.clone();   b.items.add("pen");

Make the invisible visible: the heap after the clone.

memory picture
stack            heap
a ──▶ [ Order | items ─┐ ]
                       ├──▶ [ ArrayList: "book", "pen" ]    ONE list, two owners
b ──▶ [ Order | items ─┘ ]

What you see: a change through b shows up in a.

console
System.out.println(a.items);   // [book, pen]    ❌ a never got "pen"

The fix: a copy constructor that decides the depth explicitly.

copy constructorruns offline
class Order {
    private final List<String> items;
    Order() { items = new ArrayList<>(); }
    Order(Order other) { this.items = new ArrayList<>(other.items); }   // ✅ FIX: own list, final field OK
}

What you see now: two owners, two lists.

memory picture
a ──▶ [ Order | items ──▶ [ ArrayList: "book" ] ]
b ──▶ [ Order | items ──▶ [ ArrayList: "book", "pen" ] ]       System.out.println(a.items) -> [book]

Land it Prefer a copy constructor because it copies through the front door — the constructor — while clone climbs through a window the language never properly built.

Likely follow-ups
"How do you deep-copy an object graph with cycles or shared references?"

A copy constructor per class handles trees, but a graph with shared nodes or cycles needs an identity map: walk the graph, and for each object first check an IdentityHashMap<Object, Object> of already-copied originals to copies; if present, reuse the copy, otherwise create it, register it, then copy its fields.

That preserves sharing and terminates on cycles.

In practice I avoid the need: immutable objects can be shared instead of copied, and for the rare mutable graph, serialising through Java serialisation or a JSON round-trip is a slow but correct deep copy that handles cycles when the format supports references.

The interviewer wants to hear that "deep copy" is a graph problem, not a per-class one.

"Are there cases where clone is genuinely the right tool?"

Arrays. int[] copy = original.clone() is the fastest, clearest one-dimensional array copy, it preserves the exact runtime type, and it needs no cast since JDK 5.

Beyond arrays, the JDK's own collections implement Cloneable, so ArrayList.clone() returns a shallow copy, but new ArrayList<>(list) reads better and returns the interface-friendly type.

Some performance-sensitive libraries use Object.clone because it is an intrinsic memcpy that skips constructor logic, which can beat a field-by-field copy constructor for large flat objects. That is an optimisation to reach for after profiling, wrapped in a private method, not an API to expose.

"How do records fit into the copying story?"

Records mostly remove the need to copy: they are immutable, so sharing is safe and copying is pointless. When you need a modified version, you write a wither, order.withStatus(SHIPPED), returning new Order(id, SHIPPED, items).

Writing withers by hand is the boilerplate records still have, and JEP 468, derived record creation with with expressions, was in preview discussion as of Aug 2026 but is not yet a final feature, so the hand-written wither remains the idiom.

A record with a mutable component still needs a defensive copy in the compact constructor, but that is at construction, not a separate copy mechanism. So my copying story today is: immutable by default, withers for changes, copy constructors only for legitimately mutable classes.

"What goes wrong when a superclass implements Cloneable and a subclass adds a mutable field?"

The subclass inherits a clone() that copies its new field's reference shallowly, so the original and the copy share that field's object, and mutation through one appears in the other.

The subclass author must remember to override clone(), call super.clone(), cast, and deep-copy the new field, and there is no compiler help if they forget.

Worse, if the new field is final, it cannot be reassigned after super.clone(), so a correct deep copy is impossible without dropping final.

This is the strongest concrete argument against Cloneable in an inheritance hierarchy: it turns a private implementation detail of the base into an obligation on every subclass forever, which a copy constructor never does.

03 · CollectionsCollections Internals — Q41–Q75

Collections questions are where an interviewer measures whether nine years of Java means nine years of understanding or one year repeated nine times. Nobody asks a senior what a HashMap is; they ask what it does when it is resized, shared between threads, iterated while shrinking, or fed a broken comparator. This section drills the actual internals — the real constants and the real algorithms — and the production failures each one causes when it is ignored.

Drill · HashMap under the hood

Whether you can narrate what the JDK source actually does on a put, and predict every way a hash table fails when it is mistreated.

Q41. "Walk me through, step by step, what happens inside a HashMap when you call put(key, value)."

Reveal answer

The real test Whether you have actually read the implementation or only memorized "array plus linked lists".

Strong answer A HashMap<K,V> is an array of buckets — slots that each hold either nothing, a short chain of entry nodes, or a tree. On put:

  1. It calls the key's hashCode() and spreads it with h ^ (h >>> 16), mixing the high bits into the low bits.
  2. If the internal table has not been allocated yet, it is created lazily now — 16 slots by default.
  3. The bucket index is computed as (n-1) & hash, a bit mask rather than a division.
  4. If that slot is empty, a new node is written straight into it — that is the fast path.
  5. Otherwise it walks the chain, comparing the stored hash first, which is a cheap integer comparison, and only calling equals() when the hashes match. A match means the value is replaced and the old one returned.
  6. If no node matches, the entry is appended to the end of the chain. If the chain now holds 8 nodes, it is converted to a red-black tree — but only if the table already has at least 64 slots; below that it resizes instead.
  7. Finally size and modCount — a counter of structural changes that iterators use to detect mid-iteration modification — are incremented, and if size exceeds the threshold (capacity × 0.75) the table doubles and every entry is redistributed.
HashMap.put, step by stepruns offline
map.put(key, value);

// 1. HASH. Take key.hashCode() and spread the high bits down (see Q42):
//        h = key.hashCode();
//        hash = h ^ (h >>> 16);
//
// 2. BUCKET. Because the table length n is a power of two:
//        index = (n - 1) & hash;          // equivalent to hash % n, but a
//                                          // single AND instead of a division
//
// 3. EMPTY BUCKET -> store a new Node and go to step 6.
//
// 4. OCCUPIED -> walk the chain. For each existing node:
//        if (node.hash == hash && (node.key == key || key.equals(node.key)))
//            -> REPLACE the value, return the old one.  <- equals is only
//                                                          reached if the
//                                                          hashes match
//    The hash comparison first is why an inconsistent hashCode breaks lookup
//    before equals is ever consulted.
//
// 5. NO MATCH -> append. If the chain now has 8 nodes AND the table is at
//    least 64 entries, TREEIFY it into a red-black tree (O(log n) instead
//    of O(n) for a pathological bucket). Below 64, resize instead.
//
// 6. ++size; if (size > threshold) resize();
//        threshold = capacity * loadFactor  (default 0.75)
//        resize doubles the capacity and REDISTRIBUTES every entry.

Step 4 is the one to say out loud in an interview. The hash is compared before equals is called, which is precisely why an object whose hash changes — or whose hashCode is inconsistent with equals — becomes unreachable rather than merely slow.

Picture it One map, drawn as numbered buckets, before and after a put into an empty bucket, a put that collides, a replace, a treeify at a long chain, and a resize from 16 to 32 buckets.

The setup: a map that already holds 10 entries in its default 16-bucket table, then three puts.

three puts into the same mapruns offline
Map<String, Integer> map = new HashMap<>();    // table length n = 16, threshold = 16 * 0.75 = 12
// already inside (insertion order): Ann Bob Cy Fay Gus Hal Ivy Dee lime plum  -> size 10

map.put("apple", 1);    // lands in an EMPTY bucket        (fast path)
map.put("kiwi", 2);     // lands in an OCCUPIED bucket     (collision)
map.put("Bob", 99);     // key already present             (replace)

Make the invisible visible: the hash computation for one key, with real numbers.

hash to index for "kiwi"
key                   "kiwi"
h = hashCode()        3292336            = 0x00323CB0
h >>> 16                                 = 0x00000032
hash = h ^ (h>>>16)                      = 0x00323C82
n - 1 = 15                               = 0b1111
index = hash & 15     0x82 = 1000 0010   → low four bits 0010 = 2

Make the invisible visible: the same map before and after the three puts. Empty buckets are collapsed to dots.

buckets before and after
BEFORE  (n=16, size 10)        AFTER  (n=16, size 12)
[0]  Ann → plum                [0]  Ann → plum
[1]  ·                         [1]  apple                  ← put(apple): empty slot, node written
[2]  Hal                       [2]  Hal → kiwi             ← put(kiwi): collision, appended to chain
[3]  ·                         [3]  ·
[4]  Bob(7) → Gus              [4]  Bob(99) → Gus          ← put(Bob,99): same node, value replaced
[5]  Dee                       [5]  Dee
[6]  Cy                        [6]  Cy
[7]  lime                      [7]  lime
[8..12] ·                      [8..12] ·
[13] Ivy                       [13] Ivy
[14] ·                         [14] ·
[15] Fay                       [15] Fay

The trace: put("kiwi", 2), one line per step.

put trace
1 hash = 0x00323C82                              ✓
2 table allocated (n = 16)                       ✓ lazily created on the first put ever
3 index = 0x...82 & 15 = 2                       ✓
4 table[2] empty?  no, holds Hal                 ✗ not the fast path
5 Hal.hash 0x00011A72 == 0x00323C82 ?  no        ✓ hashes differ, equals() is never called
6 Hal.next == null → append kiwi after Hal       ✓ chain length 2 (treeify needs a much longer chain)
7 ++size = 12;  12 > threshold 12 ?  no          ✓ no resize yet

What you see: the return values and the final size.

console
# illustrative output
put(apple)    -> null     new key
put(kiwi)     -> null     new key, collided with Hal
put(Bob, 99)  -> 7        old value returned
size()        -> 12

Make the invisible visible: treeify: a long chain in a big table. Every key returns hashCode() = 42 here, so all land in bucket 42 of a 64-bucket table.

chain to tree
BEFORE put(k9)                           AFTER put(k9)   (table length 64 >= MIN_TREEIFY_CAPACITY)
[42] k1→k2→k3→k4→k5→k6→k7→k8            [42] TreeNode root           shape illustrative
     8 nodes, a chain                              ├ k4              equal hashes: ordered by
                                                   │  ├ k2 (k1,k3)   compareTo if Comparable,
loop: binCount 0..6 walk past nodes;               │  └ k6 (k5,k7)   else identityHashCode
binCount 7: p.next == null → append k9;            └ k8 → k9
  binCount >= TREEIFY_THRESHOLD - 1 (7) → treeifyBin()
table length 16 instead?  treeifyBin() calls resize() and builds no tree

Make the invisible visible: resize: the 13th entry Eve lands in bucket 5, size becomes 13 > 12, and the table doubles to 32 with threshold 24.

rule per node
oldCap = 16.   For each node:  (hash & 16) == 0 → stays at index j      (bit 4 of the hash is 0)
                               (hash & 16) != 0 → moves to j + 16      (bit 4 of the hash is 1)
chain order is preserved on both sides
resize 16 to 32
OLD  n=16                              NEW  n=32                       moved?
[0]  Ann → plum                        [0]  Ann → plum                 both stay
[1]  apple                             [17] apple                      MOVES  1 + 16
[2]  Hal → kiwi                        [2]  kiwi                       kiwi stays
                                       [18] Hal                        Hal MOVES  2 + 16
[4]  Bob → Gus                         [4]  Gus                        Gus stays
                                       [20] Bob                        Bob MOVES  4 + 16
[5]  Dee → Eve                         [5]  Dee                        Dee stays
                                       [21] Eve                        Eve MOVES  5 + 16
[6]  Cy                                [22] Cy                         MOVES  6 + 16
[7]  lime                              [7]  lime                       stays
[13] Ivy                               [13] Ivy                        stays
[15] Fay                               [31] Fay                        MOVES  15 + 16
13 entries: 6 moved (apple Hal Bob Eve Cy Fay), 7 stayed

Why: the index is hash & (n-1), so doubling n just adds one more bit of the hash to the mask, and that bit alone decides whether an entry stays or moves by exactly the old capacity.

The fix: if you know the size up front, size the table once so none of these resizes happen.

presizeruns offline
Map<String, Integer> map = HashMap.newHashMap(13);   // JDK 19+: capacity from expected count, 32 buckets
// older JDKs: new HashMap<>((int) (13 / 0.75f) + 1)
for (String k : keys) map.put(k, 1);                 // ✅ FIX: no resize while loading

What you see now: the table starts at 32 and the 13th put just fills a bucket.

buckets
# illustrative output
n=32, size 13, threshold 24:   no resize happened during the loop

Land it The fast path is one hash, one mask, and one array write — everything else in the class exists to keep that path fast when real-world keys misbehave.

Likely follow-ups
"What happens on put with a null key?"

HashMap allows one null key. The internal hash() method returns 0 when the key is null, so the null key always lives in bucket 0 with a hash of 0, and lookups take the same path with an identity check, since null.equals cannot be called.

The chain comparison is (k = e.key) == key || (key != null && key.equals(k)), which handles it.

ConcurrentHashMap and Hashtable reject null keys and values with NullPointerException, because in a concurrent map get returning null would be ambiguous between "absent" and "mapped to null", and TreeMap with natural ordering rejects null because compareTo would throw. So null-key support is a HashMap and LinkedHashMap feature only.

null key picture
put(null, "x"):  hash(null) = 0  →  index 0 & 15 = 0
[0]  Ann → plum → (null, "x")        the null key is a normal node in bucket 0
get(null):  same path, compared with  (k = e.key) == key   ✓ identity test, no equals call
"Walk me through get, and why it is usually one or two memory reads."

get calls getNode(hash(key)): it computes the spread hash, reads table[(n-1) & hash], which is one array load, then checks the first node's hash and key with the identity-or-equals test.

For a well-distributed map at load factor 0.75, most non-empty buckets hold exactly one node, so that first check is the answer and get has touched the table slot and the node, two cache lines, plus the key's own memory if equals runs.

Only if the first node does not match does it branch: if the node is a TreeNode it calls getTreeNode, otherwise it walks the chain. That short common path is why HashMap.get is usually tens of nanoseconds.

"How does ConcurrentHashMap's put differ from this?"

The structure is similar, a table of nodes with treeified bins, but there is no global lock. An empty bucket is claimed with a compare-and-swap on the array slot, so two writers to different buckets never contend.

A non-empty bucket is locked by synchronising on its first node, so the lock granularity is one bucket.

Resize is cooperative: threads that arrive during a resize help move buckets, tracked with a ForwardingNode placed in each moved slot, and readers follow the forwarding node to the new table. size() is kept in striped CounterCells to avoid a hot counter.

That design is why computeIfAbsent is atomic per key but must not touch other keys inside its function, which can deadlock or throw IllegalStateException: Recursive update.

"What does the memory footprint of a HashMap entry look like?"

With compressed object pointers on a 64-bit JVM, a HashMap.Node is 32 bytes: a 12-byte header, then int hash, and three 4-byte references for key, value, and next, padded to 8-byte alignment.

Add the table slot, 4 bytes amortised over the load factor, so about 37 bytes per entry before counting the key and value objects themselves. A TreeNode is larger, about 56 bytes, because it carries parent, left, right, prev pointers and a colour.

With compact object headers, -XX:+UseCompactObjectHeaders, a product feature in JDK 25 but off by default as of Aug 2026, the header drops to 8 bytes and the node to 24.

For a map with millions of entries those bytes are the difference between fitting in cache and not.

Q42. "Why does HashMap XOR the hash with itself shifted right by 16 bits, and why must the table length always be a power of two?"

Reveal answer

The real test Whether you understand the two design choices are one decision — the cheap mask forces the cheap mixing.

Strong answer The bucket index is computed as (n-1) & hash, where & is bitwise AND. That replaces an expensive modulo division with a single mask instruction, but it only works when n is a power of two, because only then is n-1 a solid block of one-bits: for capacity 16 the mask is binary 1111, which keeps exactly the low four bits of the hash.

The cost of that trick is that every bit above the mask is thrown away, so two hash codes that differ only in their high bits would land in the same bucket every time — a pattern real data produces, for example Double keys or hashes built by repeated multiplication.

The spread step h ^ (h >>> 16) folds the top sixteen bits into the bottom sixteen with one shift and one XOR, so high-bit information still influences the index.

The authors deliberately chose the cheapest possible mixing rather than a full scrambling function, because since Java 8 the red-black-tree fallback catches the truly pathological cases.

Picture it Real bits for one key whose information sits in the high bits, the table size that makes the mask cheap, and the table with and without the XOR-shift.

The setup: eight Double keys, which are whole numbers, in a default 16-bucket HashMap.

Double keysruns offline
Map<Double, String> m = new HashMap<>();      // n = 16, mask = n - 1 = 0b1111
for (double d = 1.0; d <= 8.0; d++) m.put(d, "v" + d);

Make the invisible visible: the hash of 3.0 bit by bit, with and without the spread.

bits of 3.0
doubleToLongBits(3.0)  = 0x4008000000000000
Double.hashCode        = hi ^ lo = 0x40080000
h                      = 0100 0000 0000 1000 | 0000 0000 0000 0000
h >>> 16               = 0000 0000 0000 0000 | 0100 0000 0000 1000
h ^ (h >>> 16)         = 0100 0000 0000 1000 | 0100 0000 0000 1000
mask 15                =                                      1111
without spread: h & 15      = 0000 = bucket 0
with spread:    hash & 15   = 1000 = bucket 8

Make the invisible visible: why the table length is a power of two: compare two masks.

mask picture
n = 16   n-1 = 15 = 1111   index uses bits 3,2,1,0   → all 16 buckets reachable
n = 12   n-1 = 11 = 1011   bit 2 is always 0         → buckets 4,5,6,7 can never be chosen
hash & (n-1) equals hash % n only when n is a power of two

What you see: with no spread, all eight keys fall into one bucket.

buckets without the spread
# computed by hand from Double.hashCode
key  Double.hashCode  idx = h & 15
1.0  0x3ff00000       0
2.0  0x40000000       0
3.0  0x40080000       0          [0] 1.0→2.0→3.0→4.0→5.0→6.0→7.0→8.0   one chain of 8
4.0  0x40100000       0          every other bucket empty
5.0  0x40140000       0
6.0  0x40180000       0
7.0  0x401c0000       0
8.0  0x40200000       0

Why: the mask keeps only the low bits, and these hashes differ only in their upper 16 bits, so the mask throws away every bit that tells the keys apart.

The fix: this is exactly what HashMap already does: fold the high half into the low half before masking.

HashMap.hashruns offline
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);   // ✅ FIX: one shift, one XOR
}

What you see now: the same keys spread over four buckets, so the longest chain is 4 instead of 8.

buckets with the spread
# computed by hand
key  hash (spread)   idx = hash & 15
1.0  0x3ff03ff0      0       [0]  1.0 → 2.0 → 4.0 → 8.0
2.0  0x40004000      0       [4]  5.0
3.0  0x40084008      8       [8]  3.0 → 6.0
4.0  0x40104010      0       [12] 7.0
5.0  0x40144014      4       the rest empty; with tree bins as the safety net for worse cases
6.0  0x40184018      8
7.0  0x401c401c      12
8.0  0x40204020      0

Land it Power-of-two capacity buys a one-instruction index, the XOR-shift repairs the information that mask discards, and the tree bins insure the residual risk — three small decisions that only make sense together.

Likely follow-ups
"What happens if I pass a non-power-of-two initial capacity?"

The constructor rounds it up with tableSizeFor, which returns the smallest power of two greater than or equal to the request, computed since JDK 11 as -1 >>> Integer.numberOfLeadingZeros(cap - 1) plus one. So new HashMap<>(100) gets a 128-slot table and a threshold of 96.

Nothing is stored in a non-power-of-two table, ever, so the mask trick is always valid. The subtle part is that the request is a capacity, not an expected entry count: new HashMap<>(100) resizes when the 97th entry goes in.

That is why JDK 19 added HashMap.newHashMap(int numMappings), which computes the capacity from the expected count and the load factor for you.

tableSizeFor for 100
new HashMap<>(100):  numberOfLeadingZeros(99) = 25   -1 >>> 25 = 127   +1 = 128
table = 128 buckets, threshold = 128 * 0.75 = 96   → the 97th put triggers the resize
HashMap.newHashMap(100): capacity = ceil(100 / 0.75) = 134 → 256 buckets, threshold 192, no resize
"Why not use a better mixing function like MurmurHash?"

Cost versus benefit.

The JDK 7 HashMap used a heavier four-step mixing function, and the JDK 8 rewrite replaced it with the single shift-and-XOR after measuring that, with tree bins protecting the worst case, the heavier mixing bought little on real workloads and cost on every operation.

Most key types in practice, String, Integer, Long, records, already produce reasonably distributed hashes, so the mixing only needs to rescue the high-bit-only cases. ConcurrentHashMap uses the same spread plus a mask to clear the sign bit, because it reserves negative hashes for internal node types.

If you need a stronger hash, the right place is your key's hashCode, not the map.

"Show me a key type whose hashCode has all its information in the high bits."

Double is the textbook case: Double.hashCode XORs the two halves of the 64-bit IEEE representation, and for small whole numbers such as 1.0, 2.0, 3.0 the low 32 bits of the representation are zero, so the hash is just the high word, where the exponent and top mantissa bits live.

Those differ only in the upper bits, so without the spread step, keys 1.0 through 8.0 in a 16-slot table would all mask to the same few buckets. Hashes built by repeated multiplication by 31 for long strings also push older characters into the high bits.

The XOR with h >>> 16 folds that information back within reach of the mask.

"Does the power-of-two table have a downside?"

Yes: memory granularity and pathological keys.

Because the table only doubles, a map holding 1.6 million entries needs a 4-million-slot table, since 2 million times 0.75 is 1.5 million, so the slot array can be much larger than a prime-sized table tuned to the count; that is a fixed cost of the design.

And keys whose hashes share their low bits collide systematically, for example pointers or ids that are all multiples of 1024, which a modulo by a prime would have scattered.

The spread step and tree bins mitigate the second problem, and the first is usually acceptable since the slot array is only 4 bytes per slot with compressed pointers. Hashtable and the old IdentityHashMap used other schemes, and neither is faster.

Q43. "What does the load factor of 0.75 actually control, and what happens during a resize?"

Reveal answer

Strong answer The load factor is the fill ratio at which the map grows: the resize threshold is capacity × load factor, so a default map with 16 slots resizes when the 13th entry goes in.

The value 0.75 is a measured compromise between memory and collisions.

With random hashing at that fill level, bucket lengths follow a Poisson distribution: the average chain is well under one node, and the odds of any bucket reaching 8 entries are about six in a hundred million.

A higher factor saves memory but lengthens chains; a lower one wastes slots for little gain.

On resize the table doubles, and since Java 8 each bucket is split in place:

  1. One more bit: the capacity gained exactly one bit (16 becomes 32), so the index mask hash & (cap - 1) now looks at one more bit of the hash.
  2. Test that bit: hash & oldCapacity decides each node. Zero means it stays at index i; non-zero means it moves to i + oldCapacity.

The whole operation is linear in the number of entries and preserves each chain's relative order.

Picture it the same 16-bucket map before and after the 13th put, so you can watch the resize move exactly two entries.

The setup: sixteen buckets, a threshold of 12, and thirteen Integer keys chosen so some buckets hold chains.

HashMapResize.javaruns offline
Map<Integer, String> m = new HashMap<>();   // table of 16 buckets, threshold 16 x 0.75 = 12
// Integer.hashCode() is the value itself, and small values are unchanged by the hash spread
int[] keys = {5, 21, 3, 37, 19, 8, 40, 9, 10, 12, 14, 15};
for (int k : keys) m.put(k, "v" + k);       // 12 puts: size 12, and 12 > 12 is false, so no resize
m.put(1, "v1");                             // 13th put: size 13, and 13 > 12 is true -> resize()

Make the invisible visible: the table before the 13th put, drawn as numbered buckets with their chains (index = hash & 15).

HashMap table before: capacity 16, size 12
table[16]   index = hash & 15
 [0]  empty
 [1]  empty            <- key 1 will land here
 [2]  empty
 [3]  (3) -> (19)
 [4]  empty
 [5]  (5) -> (21) -> (37)
 [6]  empty
 [7]  empty
 [8]  (8) -> (40)
 [9]  (9)
 [10] (10)
 [11] empty
 [12] (12)
 [13] empty
 [14] (14)
 [15] (15)
size = 12   threshold = 16 x 0.75 = 12

The trace: the 13th put inserts first, then compares size with the threshold, then splits every chain by one bit.

load-factor arithmetic and the hash & oldCap split
capacity 16 x 0.75 = threshold 12
put #12: ++size = 12   12 > 12 ?  no   -> no resize
put #13: ++size = 13   13 > 12 ?  yes  -> resize: capacity 32, threshold 32 x 0.75 = 24

split with oldCap = 16 (binary 10000):
 bucket [5]:  5 = 000101  & 10000 = 0      -> low  list, stays at 5
              21 = 010101  & 10000 = 10000  -> high list, moves to 5 + 16 = 21
              37 = 100101  & 10000 = 0      -> low  list, stays at 5   (37 & 31 = 5)
 bucket [3]:  3  -> low, stays;  19 = 10011 & 10000 != 0 -> high, moves to 19
 bucket [8]:  8  -> low, stays;  40 = 101000 & 10000 = 0 -> low, stays at 8
 every other node is alone in its bucket and has bit 16 clear -> stays
 next resize: put #25 (25 > 24)

What you see: the same map after the resize, with the two moved entries marked.

HashMap table after: capacity 32, size 13
table[32]   index = hash & 31
 [1]  (1)
 [3]  (3)
 [5]  (5) -> (37)        <- 21 left; relative order of 5, 37 preserved
 [8]  (8) -> (40)
 [9]  (9)    [10] (10)    [12] (12)    [14] (14)    [15] (15)
 [19] (19)               <- moved from [3]   (3 + 16)
 [21] (21)               <- moved from [5]   (5 + 16)
 all other buckets empty
size = 13   threshold = 32 x 0.75 = 24

Why: doubling the capacity adds exactly one index bit, so a node either keeps its index or gains the old capacity, and the stored hash means no node is rehashed.

Land it 0.75 is not folklore — it is the point where the mathematics says chains stay near length one while three quarters of the memory is actually used.

Likely follow-ups
"When would you change the load factor, and in which direction?"

Almost never, and if pushed, downward.

A lower factor such as 0.5 halves the average chain length at the cost of double the slot array.

That can be worth it for a read-heavy lookup table where the entries are small and the table is hot in cache; the gain is usually a few percent.

A higher factor such as 1.0 saves table memory but lengthens chains and increases the chance of treeification; it is only sensible for a huge map that is rarely read.

The honest answer is that the constructor argument exists mostly so LinkedHashMap's LRU constructor and HashSet can pass it through, and that presizing the capacity has far more effect than tuning the factor.

"Why does the low/high split during resize preserve chain order, and why does that matter?"

Because JDK 8's resize walks each old chain in order and appends each node to the tail of one of two new chains.

The low list stays at index i and the high list moves to i + oldCap, chosen by one bit test on hash & oldCap.

Appending to tails keeps relative order; JDK 7 inserted at heads, which reversed chains and, under concurrent misuse, produced cycles.

Order preservation matters for two reasons:

  1. One linear pass: the resize needs no rehashing, since the stored hash is reused.
  2. No reversal: a resize never changes the relative order of nodes within a bucket, so any iteration-order shift after a resize comes only from the split.
"Can a resize happen during a get or during iteration?"

Not from get, which never modifies the table; only structural insertions trigger resize, plus putAll, merge, compute, and computeIfAbsent when they add a key.

During iteration, any of those from the same thread bumps modCount, and the iterator throws ConcurrentModificationException on its next step.

There are two legal mutations during iteration: Iterator.remove, and since JDK 8 entry.setValue. Neither resizes.

The trap is computeIfAbsent inside a loop over the same map: it compiles, runs for a while, and throws once it crosses the threshold, so the failure looks intermittent and data-dependent.

computeIfAbsent inside a loop over the same mapruns offline
for (String k : map.keySet()) {
    map.computeIfAbsent(k + "x", s -> 1);   // ❌ TRAP: adds a key, so modCount++ behind the iterator
}
// Result: the next iterator step throws
// java.util.ConcurrentModificationException
//     at java.base/java.util.HashMap$HashIterator.nextNode(...)
"How would you see resize cost in a profiler, and what number tells you it is a problem?"

In a CPU profile from JFR or async-profiler, HashMap.resize appears as its own frame under putVal. For a map filled once and read many times it should be a negligible fraction.

If it is more than a few percent of the time in a load phase, the map was undersized. The allocation view shows it too: each resize allocates a new Node[], and large ones show up as humongous allocations in G1's log.

My rule of thumb is that a map grown from default to N entries performs about 2N node moves in total, so if the fill phase is dominated by map work, presizing removes roughly half the map cost and all the transient array garbage.

Q44. "Why does a bucket turn into a tree at 8 entries but only turn back into a list at 6, and why should keys ideally implement Comparable?"

Reveal answer

The real test Whether you know treeification is a defense mechanism, not an optimization for normal use.

Strong answer A red-black tree is a binary search tree — smaller keys left, larger keys right — with coloring rules that keep it balanced.

Lookups therefore cost O(log n): the number of steps grows with the logarithm of the size instead of the size itself.

Why the threshold is 8:

  • Rarity: under decent hashing, the probability of 8 keys sharing a bucket is roughly one in ten million.
  • Meaning: reaching it means the hash function is poor or someone is deliberately feeding colliding keys, a hash-flooding denial-of-service attack that turns a map into a giant O(n) list.

The tree caps that worst case at O(log n).

Shrinking back happens at 6, not 8, deliberately: the gap is hysteresis, so a map hovering at the boundary does not expensively convert back and forth on every insert and remove.

Keys should implement Comparable because a search tree needs a total ordering; without it, the tree falls back to comparing class names and identity hash codes, which still works but balances worse.

And treeification only happens at all once the table has 64 slots — below that the map just resizes, because spreading entries is cheaper than building trees.

Picture it nine colliding keys in one bucket, first in a 16-slot table (resize instead of a tree), then in a 64-slot table (a tree).

The setup: strings built from the blocks "Aa" and "BB" all have the same hashCode (2112 per block pair), so they pile into one bucket on purpose.

TreeifyDemo.javaruns offline
// every string made of "Aa" / "BB" blocks has the SAME hashCode
List<String> keys = new ArrayList<>();
for (int i = 0; i < 9; i++) {
    String s = "";
    for (int b = 3; b >= 0; b--) s += (((i >> b) & 1) == 0) ? "Aa" : "BB";
    keys.add(s);                              // AaAaAaAa, AaAaAaBB, AaAaBBAa, ...
}
Map<String, Integer> small = new HashMap<>();     // 16 buckets
Map<String, Integer> big   = new HashMap<>(64);   // 64 buckets
for (String k : keys) { small.put(k, 1); big.put(k, 1); }   // all 9 keys share one bucket

Make the invisible visible: the same bucket as a chain and as a tree, with the lookup cost of each.

one bucket: list versus tree
LIST (up to 8 nodes)                    TREE (TreeNode, ordered by compareTo)
bucket -> k0 -> k1 -> k2 -> k3          bucket ->         k3
          -> k4 -> k5 -> k6 -> k7                      /      \
                                                    k1          k5
 find(k7): equals() on 8 nodes                     /  \        /  \
                                                 k0   k2     k4    k6
                                                                      \
                                                                       k7
                                         find(k7): about 4 compareTo calls
# illustrative shape: colors of the red-black tree omitted

The trace: adding the 9th node to a bin that already holds 8 asks for a tree, but the table size decides what actually happens.

putVal and treeifyBin
bin holds 8 nodes, put a 9th colliding key  ->  treeifyBin(tab, hash)
 table length 16:  16 < MIN_TREEIFY_CAPACITY (64)  -> resize() to 32          ✗ no tree yet
 ... each further colliding put resizes again until the table has 64 slots
 table length 64:  64 >= 64                         -> nodes become TreeNodes  ✓ tree
 later, during a resize split, a bin of 6 or fewer nodes is turned back into a list (UNTREEIFY_THRESHOLD = 6)

Why: a long chain in a small table usually means too few buckets, so doubling is the cheaper cure, and the tree is reserved for chains that survive a big table.

Land it Say it plainly: if your buckets are treeifying, the tree is not helping you — it is telling you your keys' hashing is broken or hostile.

Likely follow-ups
"How does the tree bin order keys that have the same hash but are not Comparable?"

It falls back to tieBreakOrder: compare the class names as strings, and if those are equal, compare System.identityHashCode values, with ties treated as "left".

That gives the red-black tree a consistent order for insertion so it can stay balanced.

It gives lookups nothing, because a fresh equal key has a different identity hash.

So find in a tree bin with non-comparable, hash-equal keys searches both subtrees, which degenerates to a linear scan of the bin, with extra pointer chasing.

That is the precise reason the Javadoc recommends Comparable keys: the tree is only a real search tree when the keys can be ordered by something a lookup can reproduce.

"Is treeification a sign of an attack, and how would you detect it in production?"

It is a sign of either a bad hash or hostile input, and both deserve investigation.

Detection is indirect: a heap dump with jcmd GC.heap_dump opened in Eclipse MAT, then a histogram filtered on java.util.HashMap$TreeNode.

In a healthy service that count is zero or tiny; thousands means some map has degenerate buckets, and MAT's "immediate dominators" tells you which map. A CPU profile showing time in HashMap$TreeNode.find or putTreeVal is the same signal.

If the map is built from request input, parameters, headers, JSON keys, it may be flooding; if from internal keys, the key's hashCode is the bug, and I fix the key rather than tune the map.

"What about the Comparable check — does a class implementing Comparable of a different type count?"

No. The check in comparableClassFor requires the key's class to implement Comparable<C> where C is the key's own class exactly, verified by inspecting the generic interfaces reflectively.

It also requires that both keys in a comparison are the same class.

So a subclass of a Comparable base does not qualify, a key implementing Comparable<Object> does not qualify, and mixed key classes in one bin fall back to the tie-break. String passes because it implements Comparable<String>.

which keys pass comparableClassFor
String                                    implements Comparable<String>        ✓ tree can order by compareTo
Integer                                   implements Comparable<Integer>       ✓
class Base implements Comparable<Base>
class Sub extends Base                    key class is Sub, not Base           ✗ falls back to tieBreakOrder
class Odd implements Comparable<Object>   C is Object, not Odd                 ✗ falls back to tieBreakOrder
one bin holding a String and an Integer   classes differ                       ✗ falls back to tieBreakOrder

This reflective check is cached per class, so it does not cost on every operation, but it is another reason to keep key types simple and final.

"Why 64 for the minimum treeify capacity?"

Because in a small table, long chains are more likely to come from too few buckets than from bad hashing, and resizing is cheaper and more useful than building trees.

With 16 slots and 12 entries, two or three keys per bucket is normal, and a run of 8 is plausible with a mediocre hash; doubling the table spreads them out and benefits every bucket, whereas a tree only helps one.

The constant 64 was chosen as the point where the table is large enough that an 8-deep chain is genuinely anomalous.

As the source comment puts it, it is at least four times the treeify threshold, to avoid conflicts between resizing and treeification thresholds. Below it, treeifyBin just calls resize.

Q45 · Scenario. "A batch job loads two million rows into a HashMap and the profiler shows a surprising share of time inside HashMap.resize. What is happening and what do you change?"

Reveal answer

Strong answer The map was created with new HashMap<>(), so it starts at 16 slots and doubles its way up:

  1. Repeated doubling: growing from 16 slots to the roughly 4 million needed for two million entries takes about 18 doublings, and each one re-walks and redistributes every entry present at the time.
  2. Garbage: every doubling also allocates a fresh multi-megabyte array, which shows up as garbage-collection (GC) pressure alongside the CPU cost.
  3. Presize: size the map up front so the threshold clears the expected count. Capacity must be at least expected ÷ 0.75, so new HashMap<>((int) (2_000_000 / 0.75f) + 1).
  4. Java 19 and later: simply HashMap.newHashMap(2_000_000), which does that arithmetic for you.
  5. The classic near-miss: passing 2_000_000 directly as the capacity still resizes once, because the threshold becomes 2,000,000 × 0.75 and the map grows at 1.5 million entries.
  6. Why people hit it: they make this off-by-a-quarter mistake constantly.
  7. Verify with the same profile — the resize frames disappear and allocation drops.

Prevention: the same reasoning applies to HashSet, StringBuilder, and ArrayList — any growable structure being bulk-loaded with a known size deserves a presized constructor.

Picture it the resize ladder of a default map filling to two million entries, next to the presized one that never climbs it.

The setup: two ways to create the map that will receive two million rows.

BulkLoad.javaruns offline
int n = 2_000_000;
Map<Long, Row> slow = new HashMap<>();                         // ❌ TRAP: starts at 16, doubles 18 times
Map<Long, Row> near = new HashMap<>(n);                        // ❌ TRAP: rounds to 2,097,152; threshold 1,572,864 -> one resize
Map<Long, Row> fast = new HashMap<>((int) (n / 0.75f) + 1);    // ✅ FIX: 2,666,667 -> 4,194,304 slots, threshold 3,145,728
Map<Long, Row> j19  = HashMap.newHashMap(n);                   // ✅ FIX: same arithmetic on Java 19+

Make the invisible visible: each row is one resize of the default map, with the put that triggers it and the nodes it must re-walk.

resize ladder of new HashMap<>()
table            threshold   fires on put #   nodes re-walked
16  -> 32        12          13               13
32  -> 64        24          25               25
64  -> 128       48          49               49
128 -> 256       96          97               97
 ... (each row doubles) ...
2^20 -> 2^21     786,432     786,433          786,433
2^21 -> 2^22     1,572,864   1,572,865        1,572,865
total: 18 resizes, about 3.1 million nodes re-walked for 2 million entries
       the 18 abandoned tables add up to about 16 MB of garbage (4-byte slots)

What you see: the three constructor choices side by side, with real numbers.

Capacity argument versus resizes for two million entries
ConstructorTable after tableSizeForThresholdResizes while loading 2,000,000
new HashMap<>()16, then doubles12, 24, ... 3,145,72818
new HashMap<>(2_000_000)2,097,1521,572,8641 (at put #1,572,865)
new HashMap<>(2_666_667) or newHashMap(2_000_000)4,194,3043,145,7280

What you see now: the profile after presizing, same layout as before.

profiler excerpt (illustrative)
# illustrative output
before:  HashMap.putVal 100%  ->  HashMap.resize 38%   (18 calls, 3.1M node moves)
after:   HashMap.putVal 100%  ->  HashMap.resize  0%   (no frame)
allocation: 18 Node[] arrays, ~32 MB  ->  one Node[] of 16 MB

Land it Presizing costs one constructor argument and removes O(n) of repeated copying — one of the cheapest real optimizations in Java.

Likely follow-ups
"You presized the map and the job is still slow. What next?"

Then the resize frames are gone and the profile has moved, so I re-profile rather than guess. The usual next culprits, in order:

  1. Expensive key: the key's hashCode or equals, for example a key built from several strings concatenated per lookup, visible as time under getNode.
  2. Boxing: primitive ids boxed into Long keys allocate two million objects and show in the allocation profile; the fix is a primitive-keyed map from Eclipse Collections or fastutil.
  3. GC pressure from the values: a -Xlog:gc line count reveals it.

If the map fits but the heap is near its limit, promotion and old-generation collection dominate, and the fix is heap sizing, not map sizing.

"Two million entries — how much memory is that, and does it fit?"

Roughly, per entry: 32 bytes for the node, 4 bytes of table slot amortised at load factor 0.75 plus the doubling slack, so about 40 bytes of map overhead, before keys and values.

A Long key is 16 bytes and a typical small value object 24 to 48 bytes, so a realistic figure is 100 to 120 bytes per entry, or 200 to 250 MB for two million.

The table itself at 4 million slots is 16 MB, allocated as one humongous array.

That fits in most services but must be planned for; I check with jcmd GC.class_histogram after loading, and if the number matters I consider a primitive-specialised map, which cuts the per-entry overhead by two-thirds.

"What does HashMap.newHashMap actually compute?"

It calls the capacity constructor with (int) Math.ceil(numMappings / 0.75), so newHashMap(2_000_000) requests 2,666,667, which tableSizeFor rounds up to 4,194,304 slots with a threshold of 3,145,728, comfortably above two million. The same helpers exist as HashSet.newHashSet, LinkedHashMap.newLinkedHashMap, and LinkedHashSet.newLinkedHashSet, all added in JDK 19.

Before that, the idiom was Guava's Maps.newHashMapWithExpectedSize, which does the same arithmetic.

The point of the API is that the constructor argument was always misread as "expected size", so the JDK added a method whose name says what it means.

In a JDK 21 codebase I treat new HashMap<>(n) with a computed n as a review comment.

"Would a different map implementation be a better choice for a bulk load?"

If the map is built once and only read afterwards, an immutable map, Map.copyOf or a builder-based one like Guava's ImmutableMap, is exactly sized at construction, has no resize slack and no Node objects, and is safe to share across threads without synchronisation.

For primitive keys, fastutil's Long2ObjectOpenHashMap uses open addressing with parallel arrays, no node objects at all, and typically halves memory and improves cache behaviour.

If the two million rows only need to be joined once, sorting both sides and merging avoids the map entirely.

The choice depends on the access pattern after the load; the presized HashMap is the right general answer, and the alternatives are what I reach for when the profile or the memory budget says so.

Q46 · Scenario. "Years ago on Java 7, a service pinned a CPU core at 100% forever, and every thread dump showed threads inside HashMap.transfer or HashMap.get. What happened?"

Reveal answer

The real test Whether you can explain the most famous concurrency bug in Java folklore mechanically, not just name it.

Strong answer That is the classic concurrent-resize infinite loop, and the diagnosis reads straight off the dump:

  1. The threads are RUNNABLE, not BLOCKED, and jstack reports no deadlock — so nothing is waiting on a lock; something is genuinely spinning. Repeated dumps show the same frames in HashMap internals, which points at a corrupted data structure, not slow work.
  2. The cause: two threads called put on a shared plain HashMap and both crossed the resize threshold, so both ran transfer, the method that moves entries to the new table. Pre-Java-8 transfer moved each chain by head insertion, which reverses the chain's order.
  3. When two threads interleave that reversal on the same chain, one thread can end up with a node whose next pointer refers back to a node earlier in the same chain — a cycle. The resize completes and the map looks fine.
  4. Later, any innocent get whose key hashes into that bucket walks the chain, never reaches a null next, and loops forever — burning a full core per stuck thread with no exception and no log line.

The immediate fix is to replace the shared map with ConcurrentHashMap, or confine the map to a single thread.

Java 8 removed this particular failure by rewriting resize to preserve chain order with the low/high split. That fixed the symptom, not the misuse, which leads directly to the follow-up question every interviewer asks next.

Picture it the pre-Java-8 resize reversing a two-node chain while a second thread resumes with stale pointers, ending in a cycle.

The setup: two threads put into one shared Java 7 HashMap and both push it over the threshold, so both run transfer on the same chain.

Java 7 transfer (simplified)runs offline
// Java 7 HashMap.transfer, per bucket (head insertion reverses the chain):
do {
    Entry<K,V> next = e.next;               // (1) remember the rest of the chain
    int i = indexFor(e.hash, newCapacity);
    e.next = newTable[i];                   // (2) point e at the new bucket's head
    newTable[i] = e;                        // (3) e becomes the new head
    e = next;
} while (e != null);

Make the invisible visible: the chain before and after the faster thread finishes, and the pointers the slower thread still holds.

memory picture: bucket i
old table[i]:      A -> B -> null                 thread 1 paused after (1): e = A, next = B (locals)

thread 2 runs its whole transfer (head insertion reverses the chain):
shared nodes now:  B -> A -> null                 B.next = A,  A.next = null

The trace: thread 1 resumes with its stale locals and relinks nodes that thread 2 already reversed.

thread interleaving
step  thread 1 (own newTable1[i] = null)          result
 1    e = A, next = B  ... paused ...
 2    (thread 2 finishes: B.next = A, A.next = null)
 3    A.next = newTable1[i] (null); newTable1[i] = A; e = B       A -> null            ✓
 4    next = B.next = A; B.next = newTable1[i] (A);
      newTable1[i] = B; e = A                                      B -> A -> null       ✓
 5    next = A.next = null; A.next = newTable1[i] (B);
      newTable1[i] = A; e = null                                   A -> B -> A -> ...   ✗ cycle

What you see: a thread that never leaves HashMap internals.

thread dump excerpt
# illustrative output
"http-worker-7" prio=10 tid=0x00007f31a0001000 nid=0x3039 runnable [0x00007f3198f4d000]
   java.lang.Thread.State: RUNNABLE
        at java.util.HashMap.get(HashMap.java:...)
        at com.example.Cache.lookup(Cache.java:41)
# the same frames in three dumps 30 s apart; top -H shows this thread at 100% CPU

Why: head insertion reverses a chain, and two interleaved reversals can leave A pointing at B and B pointing at A, so a get walks forever.

The fix: a map built for sharing.

SafeCache.javaruns offline
// ❌ TRAP: private final Map<String, Entry> cache = new HashMap<>();
// ✅ FIX: per-bin locking and CAS, no shared chain reversal
private final Map<String, Entry> cache = new ConcurrentHashMap<>();

What you see now: no cycle and no spinning thread; CPU follows throughput again.

thread dump after the fix
# illustrative output
"http-worker-7" ... waiting on condition      # idle in the pool
top -H : no thread above its share, throughput back to normal

Land it An idle-looking service with a pegged core and RUNNABLE threads in library code means a corrupted structure being walked, and shared unsynchronized HashMap was the canonical way to get one.

Likely follow-ups
"How would you confirm the infinite loop from a thread dump today, if you saw it on an old JVM?"

Take three dumps thirty seconds apart with jstack <pid> or jcmd <pid> Thread.print.

A thread genuinely working shows changing stack frames.

A thread in a corrupted chain shows the same frames, HashMap.get or getEntry on the same line, in every dump, with state RUNNABLE and CPU time climbing.

confirming the spinning thread
$ top -H -p <pid>            # per-thread view: one thread id sits at 100% CPU
$ printf '%x\n' 12345        # convert that thread id to hex for the dump's nid=
$ jstack <pid> | grep -A 6 'nid=0x3039'
#   run it three times, 30 s apart: same frames, same line, state RUNNABLE
"worker-7" ... nid=0x3039 runnable
   java.lang.Thread.State: RUNNABLE
        at java.util.HashMap.get(HashMap.java:...)

Then a heap dump: in Eclipse MAT, find the map, expand the table, and look for a bucket whose chain revisits a node, which the tool shows as a node whose next points to an earlier node.

That is the physical proof, and it turns folklore into evidence you can put in an incident report.

"Why did the failure show up only under load and not in tests?"

Because it needs two threads to cross the resize threshold within the same few microseconds and interleave inside transfer. In a test with a handful of entries, the map never resizes after warm-up, and even if it does, the window is a couple of hundred nanoseconds.

Under production load with many threads inserting and the map growing through several doublings, the odds accumulate until one interleaving produces the cycle, and from then on the corruption is permanent because nothing ever repairs a chain.

So the bug looked like a random outage days after a deploy. The general lesson is that a data race may be probabilistically invisible in tests and still certain in production; the fix is the correct data structure, not a passing test suite.

"What was the actual JDK 8 change that removed the cycle?"

Two things changed.

  1. Resize shape: the algorithm switched from head insertion, which reversed each chain, to the low/high tail-append split that preserves order, so two racing resizes can no longer produce a next pointer that goes backwards.
  2. Tree bins: bins can become trees, which have their own structure.

The commit did not add any synchronisation; it changed the shape of the race so that its known catastrophic outcome no longer occurs.

Lost updates, corrupted size, and visibility failures all remain.

That is why I call it a coincidence fix, and why the follow-up "so is it safe now" deserves a firm no.

"What would you have put in place after that incident?"

Three things.

  1. Code fix: ConcurrentHashMap for the shared map, and a review of every other static or singleton-held HashMap, ArrayList and SimpleDateFormat in the service, because a team that made this mistake once usually made it elsewhere.
  2. Detection: an alert on per-thread CPU saturation with no corresponding throughput, which is the signature of a spinning thread, using JFR's jdk.ThreadCPULoad event or a periodic Thread.print diff.
  3. Static analysis: Error Prone and SpotBugs both have checks for non-thread-safe collections in static fields, and enabling them turns the next instance into a build failure rather than an outage.

Q47. "Java 8 fixed that resize loop — so on Java 21, is it acceptable to share a plain HashMap between threads?"

Reveal answer

Strong answer No — the famous symptom is gone, but every underlying data race remains.

Two threads writing into the same empty bucket can each read null, each create a node, and one write silently overwrites the other — a lost update you will never see in a log.

The size field and resize threshold can be corrupted by unsynchronized increments.

Concurrent structural changes during treeification or resize can still throw internal exceptions or leave the table inconsistent.

And even with no writes colliding, there is no memory-visibility guarantee: without synchronization, one thread's completed put may simply never become visible to another thread, which can read a stale null indefinitely.

The best case is a ConcurrentModificationException that at least tells you something is wrong; the worse cases are silent.

The Javadoc itself says the map must be synchronized externally.

Use ConcurrentHashMap, or keep the map confined to one thread, or publish it safely once and never mutate it again.

Picture it two threads putting into the same empty bucket of a shared plain HashMap on Java 21, with the lost update spelled out step by step.

The setup: two threads each insert 100,000 distinct keys into one plain HashMap.

SharedMapRace.javaruns offline
Map<Integer, Integer> map = new HashMap<>();   // ❌ TRAP: shared and unsynchronized
Runnable r1 = () -> { for (int i = 0;       i < 100_000; i++) map.put(i, i); };
Runnable r2 = () -> { for (int i = 100_000; i < 200_000; i++) map.put(i, i); };
Thread t1 = new Thread(r1), t2 = new Thread(r2);
t1.start(); t2.start(); t1.join(); t2.join();
System.out.println(map.size());

Make the invisible visible: the interleaving inside one empty bucket where a node is silently overwritten.

thread interleaving
step  thread 1: put(k1)                  thread 2: put(k2)                 bucket [i]
 1    tab[i] == null ? yes (reads null)                                    empty
 2                                        tab[i] == null ? yes (reads null) empty
 3    tab[i] = newNode(k1)                                                 (k1)           ✓
 4                                        tab[i] = newNode(k2)             (k2)           ✗ k1 lost
 5    ++size  (reads 0, writes 1)         ++size  (reads 0, writes 1)       size = 1       ✗ two puts, one count

What you see: fewer entries than puts, and no exception anywhere.

console
# illustrative output
200000 puts, expected size 200000
187342        <- run it again and the number changes; sometimes an internal exception instead

Why: the check "is the bucket empty" and the write that fills it are separate steps with nothing making them atomic, and nothing publishes either thread's write to the other.

The fix: a map designed for sharing.

SharedMapFixed.javaruns offline
Map<Integer, Integer> map = new ConcurrentHashMap<>();   // ✅ FIX: atomic puts per bin
// same two threads, same keys

What you see now: every put counted.

console
# illustrative output
200000

Land it "The bug I could see was fixed" is not a thread-safety argument — absence of the loop is not presence of a guarantee, and lost updates are worse than crashes because they lie quietly.

Likely follow-ups
"What about a HashMap that is written once at startup and only read afterwards — is that safe?"

Yes, if it is published safely and never modified again.

Build the map fully on one thread, then hand the reference to other threads through a mechanism that creates a happens-before edge:

  • a final field assigned in a constructor
  • a static final initialised in <clinit>
  • a volatile field
  • passing it into a thread before start()

After that, concurrent reads are pure reads and HashMap is fine. The risk is the "never modified" part, which is a promise nobody enforces, so I wrap it: Map.copyOf or Collections.unmodifiableMap makes an accidental write throw instead of racing.

The immutable copy is better because it also removes the resize slack and the node objects.

"When would you use Collections.synchronizedMap instead of ConcurrentHashMap?"

Rarely, and only when you need something ConcurrentHashMap does not offer: null keys or values, or a compound operation that must be atomic across several calls.

You can get that compound atomicity by synchronising on the wrapper itself, since it uses its own monitor as the lock.

synchronizedMap serialises every operation, including reads, through one lock, so it scales badly under contention, and iteration must be manually synchronised or it races.

ConcurrentHashMap gives lock-free reads, per-bucket write locking, atomic compute and merge, and weakly consistent iteration.

For a LinkedHashMap-based LRU there is no concurrent equivalent in the JDK, so synchronizedMap or a library like Caffeine is the answer there.

"Show me the lost-update race in ConcurrentHashMap too — what is still unsafe there?"

Individual operations are atomic, compound ones are not. Two classic bugs:

compound operations that raceruns offline
if (!map.containsKey(k)) map.put(k, v);   // ❌ TRAP: two threads both pass the check
map.put(k, map.get(k) + 1);               // ❌ TRAP: two threads read 5, both write 6: one increment lost
map.putIfAbsent(k, v);                    // ✅ FIX: one atomic step
map.merge(k, 1, Integer::sum);            // ✅ FIX: atomic increment

The fixes are the atomic methods: putIfAbsent, computeIfAbsent, merge(k, 1, Integer::sum), or a LongAdder as the value.

Two more traps. size() and isEmpty() are estimates while writes are in flight.

The function passed to compute must be short and must not touch the same map, because it runs under the bucket lock and a recursive update throws.

And of course the values themselves are not protected; a mutable value object still needs its own synchronisation.

"How would you detect an unsynchronised shared HashMap in a codebase you inherited?"

Statically first: search for HashMap and ArrayList fields on singletons, static fields, Spring beans with default scope, and anything reached from a thread pool. Error Prone's GuardedBy analysis and SpotBugs's IS2_INCONSISTENT_SYNC flag fields accessed both with and without a lock.

Dynamically, a ConcurrentModificationException in the logs from a HashMap iterator on a service thread is a certain sign. Under load testing, inconsistent size() results or values that disappear point the same way.

When I find one, I prefer to change the type to ConcurrentHashMap at the declaration rather than add synchronized around call sites, because the type change is visible and complete and the call-site fix is neither.

Q48 · Scenario. "This single-threaded batch job throws ConcurrentModificationException, and I can prove no other thread touches the list. Explain and fix it."

Reveal answer

The real test Whether you know the exception is about iteration, not concurrency — and can name all the correct fixes, not just one.

Strong answer The name misleads: the exception fires on any structural modification during iteration, threads or not. The mechanism, step by step:

  1. An Iterator: the for-each loop compiles down to an Iterator.
  2. A snapshot: when the iterator is created, it copies the list's modCount — the counter of structural changes — into its own expectedModCount.
  3. A bypass: orders.remove(o) goes around the iterator and increments modCount.
  4. The check: the very next next() call sees the two counters disagree and throws. It throws deliberately, because after an external removal the iterator's position is no longer trustworthy.

The correct fixes, in order of preference:

  1. orders.removeIf(Order::isCancelled) — the clearest and, on ArrayList, also the fastest, because it compacts the array in a single pass instead of shifting elements once per removal.
  2. An explicit iterator with it.remove(), which removes the current element and updates expectedModCount so the iteration stays valid — the right tool when the loop does more than filtering.
  3. Collect the victims into a separate list during the loop and call orders.removeAll(toDelete) afterwards.

Worth adding: this bug can hide. Removing the second-to-last element makes hasNext() return false before the check runs, so the loop ends silently and skips the last element — the exception is actually the friendly outcome.

Picture it modCount against expectedModCount, step by step, for a four-element list where B is cancelled, then for the case where the exception never comes.

The setup: the loop below (code moved here from the answer) run on orders = [A, B, C, D] where only B is cancelled.

CancelledOrderPurge.java
List<Order> orders = loadOrders();
for (Order o : orders) {
    if (o.isCancelled()) {
        orders.remove(o);   // throws ConcurrentModificationException
    }
}

Make the invisible visible: what the compiler generates for the enhanced for, with the two counters beside it.

what the compiler generatesruns offline
for (Iterator<Order> it = orders.iterator(); it.hasNext(); ) {   // it: cursor = 0, expectedModCount = modCount
    Order o = it.next();            // next() starts with checkForComodification()
    if (o.isCancelled()) {
        orders.remove(o);           // ❌ TRAP: list.modCount++, the iterator is not told
    }
}

The trace: one line per call, with both counters.

call trace: removing B
list = [A, B, C, D]   modCount = 0
it created            cursor=0  expectedModCount=0
hasNext()             0 != 4 -> true
next() -> A           modCount 0 == expected 0 ✓   cursor=1
hasNext()             1 != 4 -> true
next() -> B           modCount 0 == expected 0 ✓   cursor=2
  orders.remove(B)    list = [A, C, D]  size=3  modCount=1
hasNext()             2 != 3 -> true
next()                modCount 1 != expected 0 ✗   -> ConcurrentModificationException

What you see: the exception, thrown from the iterator and not from the remove.

console
# illustrative output
Exception in thread "main" java.util.ConcurrentModificationException
        at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:...)
        at java.base/java.util.ArrayList$Itr.next(ArrayList.java:...)
        at CancelledOrderPurge.main(CancelledOrderPurge.java:3)

Why: the list changed behind the iterator, so the iterator's snapshot of modCount went stale and its check refused to continue.

The trap inside the trap: cancel C instead, the second-to-last element, and nothing throws.

call trace: removing C (second-to-last)
list = [A, B, C, D]   modCount = 0
next() -> C           check ✓   cursor=3
  orders.remove(C)    list = [A, B, D]  size=3  modCount=1
hasNext()             cursor 3 != size 3 -> false      ✗ loop ends, check never runs
result: D is never visited, no exception

The fix: all three safe patterns, plus the trap, in one block (code moved here from the answer).

ConcurrentModificationException on one threadruns offline
// This throws, and there is only one thread. The name of the exception is
// misleading: it means "modified during iteration", not "modified concurrently".
var orders = new ArrayList<>(List.of(a, b, c));
for (Order o : orders) {              // enhanced for = an Iterator
    if (o.isCancelled()) {
        orders.remove(o);             // ❌ TRAP: structural modification behind the iterator
    }
}                                     // Result: ConcurrentModificationException on the next next()

// MECHANISM: the list keeps a modCount, incremented on every structural change.
// The iterator snapshots it as expectedModCount and checks on every next():
//     if (modCount != expectedModCount) throw new ConcurrentModificationException();
// remove() bumped modCount without telling the iterator.

// ✅ FIX 1 — the iterator's own remove(), which updates expectedModCount.
var it = orders.iterator();
while (it.hasNext()) {
    if (it.next().isCancelled()) it.remove();
}

// ✅ FIX 2 — removeIf. Clearest, and it is what I would write.
orders.removeIf(Order::isCancelled);

// ✅ FIX 3 — collect into a new list rather than mutating.
var live = orders.stream().filter(o -> !o.isCancelled()).toList();

// ❌ TRAP (THE SUBTLE ONE): removing the SECOND-TO-LAST element does NOT throw.
// hasNext() is `cursor != size`; after the removal cursor happens to equal
// the new size, the loop exits early, and the last element is silently skipped.
// Result: no exception, one element skipped. A wrong answer with no exception is worse than the exception.

Read the last paragraph. Removing the second-to-last element produces no exception and silently skips an element — which is why relying on the exception to catch this class of bug is not safe.

What you see now: the same four orders, B and C cancelled, every element visited.

console after the fix
orders.removeIf(Order::isCancelled);
System.out.println(orders);        // [A, D]   B and C removed, D still visited, no exception

Land it Mutating a collection behind its own iterator's back is the bug; removeIf is the fix; and the truly dangerous version is the one that does not throw.

Likely follow-ups
"Why does removing the second-to-last element end the loop silently rather than throwing?"

Because the check lives in next(), and the loop asks hasNext() first. ArrayList.Itr.hasNext() is just cursor != size.

Suppose the list has five elements and the loop removes the fourth, at index 3, while the cursor is already 4.

After removal size is 4, so cursor == size, hasNext() returns false, and the loop ends without ever calling next() where the modCount comparison happens. The fifth element is never visited and nothing signals it.

call trace: five elements, fourth removed
list = [A, B, C, D, E]
next() -> D           cursor=4          body: list.remove(D)  -> size=4, modCount 0 -> 1
hasNext()             cursor 4 != size 4 -> false     ✗ loop ends
E is never visited, nothing signals it

So a test that happens to have the cancelled order in that position passes while skipping data. That is the strongest argument for removeIf: it has no such position-dependent hole.

"How does removeIf on ArrayList achieve a single pass?"

It runs the predicate over every element first, recording matches in a bit set.

Then it compacts the surviving elements toward the front in one pass with a write cursor, nulling out the tail.

So each survivor moves at most once, and total work is O(n) regardless of how many are removed.

Iterator.remove in a loop shifts everything after each removed element: O(n) per removal and O(n²) overall.

It also checks modCount at the end and throws if the predicate itself modified the list, which catches a predicate with side effects.

LinkedList and other lists inherit the default Collection.removeIf, which uses the iterator and it.remove(), correct but not compacted.

"What if the loop needs to add elements while iterating?"

Then no iterator-based fix helps, because ListIterator.add is the only legal insertion during iteration and it inserts at the cursor, which is rarely what you want.

The clean patterns: collect the additions into a separate list and addAll after the loop; iterate over a copy, for (Order o : List.copyOf(orders)), and mutate the original freely; or use an index-based loop with an explicit bound captured before the loop, which processes only the original elements.

For a work-queue shape, where processing an item can generate more items, an ArrayDeque with poll() in a while loop is the right structure. The choice depends on whether new items should themselves be processed.

"Can this exception occur without any remove at all?"

Yes, with any structural change. Each of these bumps modCount:

  • Lists: list.add inside the loop, list.clear(), and list.sort().
  • Maps: map.put of a new key, computeIfAbsent, and in access-ordered LinkedHashMap even get.

It can also come from a different collection view of the same data: iterating map.keySet() and calling map.remove throws, because both share the map's modCount.

And the mirror trap is subList: modifying the parent list makes every operation on an existing sublist throw, because the sublist snapshots the parent's modCount.

Setting an existing element or value, list.set(i, x) or entry.setValue(v), is not structural and is allowed.

Q49. "What is the difference between fail-fast and fail-safe iterators?"

Reveal answer

Strong answer A fail-fast iterator — the kind ArrayList and HashMap hand out — detects structural changes made behind its back using the modCount comparison.

It throws ConcurrentModificationException rather than continue over a structure it can no longer trust.

The so-called fail-safe kind is better named what the Javadoc calls it: weakly consistent.

A ConcurrentHashMap iterator never throws. It makes three promises:

  • you see every element that existed when the iterator was created;
  • it never returns the same element twice;
  • it may or may not reflect changes made during iteration.

CopyOnWriteArrayList goes further with snapshot semantics: its iterator walks the exact array that existed at creation, so concurrent modifications are guaranteed invisible.

Its iterator's remove() is unsupported.

The trade is precision for availability — fail-fast surfaces bugs loudly; weakly consistent keeps concurrent readers running at the cost of a fuzzy view.

Picture it the same "add D while looping over A, B, C" run on a fail-fast list, a snapshot list and a weakly consistent map.

The setup: one shared example under three collections.

ThreeIterators.javaruns offline
var list = new ArrayList<>(List.of("A", "B", "C"));
for (String s : list) { if (s.equals("A")) list.add("D"); }          // fail-fast

var cow = new CopyOnWriteArrayList<>(List.of("A", "B", "C"));
for (String s : cow) { if (s.equals("A")) cow.add("D"); System.out.print(s + " "); }   // snapshot

var chm = new ConcurrentHashMap<>(Map.of("A", 1, "B", 2, "C", 3));
for (String k : chm.keySet()) { if (k.equals("A")) chm.put("D", 4); }                 // weakly consistent

Make the invisible visible: what each iterator holds while the writer adds D.

memory picture
ArrayList            list.modCount = 1   iterator.expectedModCount = 0      -> next() throws ✗
CopyOnWriteArrayList iterator ---> array v1 [A B C]
                     cow.array --> array v2 [A B C D]   (add copied the array)   -> iterator never sees D ✓
ConcurrentHashMap    iterator walks the live table; D may land before or after the iterator's position -> maybe ✓

What you see: three outcomes for three structures.

Adding D while iterating A, B, C
ActionArrayListCopyOnWriteArrayListConcurrentHashMap
Next step after add("D") or put("D", 4)Fails: ConcurrentModificationExceptionWorks: prints A B CWorks: no exception
Does the running loop see D?Not applicable, it threwNeverMaybe
Contents after the loop[A, B, C, D] (the add itself succeeded)[A, B, C, D]A, B, C, D
it.remove()WorksFails: UnsupportedOperationExceptionWorks

Why: the first compares a counter, the second iterates a frozen array, the third iterates the live structure with no counter.

Land it Choose by intent: in single-threaded code a throw means you have a bug to fix, while in concurrent code you pick a structure whose fuzziness you have consciously accepted.

Likely follow-ups
"What does weakly consistent actually promise, in terms I could test?"

Three properties:

  1. The iterator never throws ConcurrentModificationException.
  2. Every element present when the iterator was created and not removed during the traversal is returned exactly once.
  3. Elements added or updated during the traversal may or may not be seen.

There is no snapshot: if a writer changes a value you have not reached yet, you may see the new value.

A test can assert the first two properties deterministically, by starting an iteration, removing nothing, and checking the count matches the pre-iteration size.

It can only check that the third does not violate the first two.

ConcurrentHashMap, ConcurrentSkipListMap, ConcurrentLinkedQueue and the Concurrent* family all use this term in their Javadoc.

"When would you accept CopyOnWriteArrayList's cost, and when is it a mistake?"

Accept it when the list is small, read very frequently from many threads, and written rarely: listener lists, subscriber registries, a handful of configuration entries. Reads are then plain array reads with no locking and iteration is a stable snapshot.

It is a mistake when writes are frequent or the list is large, because every add copies the whole array under a lock.

A list of ten thousand entries written a hundred times a second copies a megabyte per second and generates garbage to match.

It is also a mistake when readers need to see the latest writes, since an in-progress iteration will never see them.

For those cases, ConcurrentLinkedQueue or a synchronised structure fits better.

"Are the JDK's immutable collections fail-fast, fail-safe, or something else?"

Something else: they are simply immutable, so there is nothing to fail on. An iterator over List.of(...) cannot observe a modification because none can occur, and it never checks modCount.

That is why an immutable snapshot is the ideal thing to hand to multiple readers: no exception, no fuzziness, and no lock.

The pattern I use for a read-mostly shared list is a volatile List<X> field replaced wholesale with a new immutable list on each change, which is what CopyOnWriteArrayList does internally, but with the copy step under my control.

Readers get snapshot semantics, writers pay the copy, and neither the fail-fast nor the weakly consistent trade-off applies.

Q50. "The Javadoc says fail-fast behavior is only best-effort. Why can't it be guaranteed?"

Reveal answer

Strong answer Because the mechanism is a plain, unsynchronized int.

modCount is not volatile and is read without any locking.

When the modification comes from another thread, there is no guarantee the iterating thread ever sees the updated value: the check itself is a data race, and the iterator may march on over a corrupted structure without throwing.

Even single-threaded, the check only runs inside next().

Remove the second-to-last element mid-loop and hasNext() returns false first, ending the iteration silently and incorrectly. So the exception can be absent when the bug is present.

The practical consequences:

  • A debugging aid: treat ConcurrentModificationException purely as a debugging aid that usually catches mistakes.
  • No logic on it: never write program logic that catches it.
  • No false comfort: never conclude from a clean test run that no concurrent modification exists. Use the right concurrent collection instead of relying on the alarm.

Picture it why the alarm can stay silent: the check and the element read are separate steps, and a second thread can slip between them.

The setup: a reader loops over an ArrayList while a writer thread removes elements.

BestEffortCheck.javaruns offline
List<String> list = new ArrayList<>(List.of("A", "B", "C", "D"));
// reader thread:  for (String s : list) process(s);
// writer thread:  list.remove(0);        // ❌ TRAP: unsynchronized structural change, modCount is a plain int

Make the invisible visible: what ArrayList.Itr.next() does, in order, and the gap between its two halves.

what next() doesruns offline
public E next() {
    checkForComodification();               // (1) modCount != expectedModCount ? throw
    int i = cursor;                         //     the check passed here ...
    if (i >= size) throw new NoSuchElementException();
    Object[] elementData = ArrayList.this.elementData;   // (2) ... the array is read here
    cursor = i + 1;
    return (E) elementData[lastRet = i];
}

The trace: the writer lands between (1) and (2), so the reader gets the wrong element without an exception.

thread interleaving
step  reader (cursor = 2, list [A,B,C,D])        writer
 1    next(): (1) check: modCount == expected ✓
 2                                                list.remove(0): list = [B,C,D], modCount++
 3    next(): (2) i = 2, reads elementData[2]  -> D     ✗ C skipped, no exception yet
 4    next(): (1) check: modCount != expected  -> ConcurrentModificationException (a step late)
 --   if the removal had come after the last next(), the alarm never fires at all
 --   modCount is not volatile: the reader may keep seeing the old value

What you see: the single-threaded version of the same hole is fully deterministic.

console
list = [A, B, C, D, E];  loop removes D when it is visited
visited: A B C D          <- E skipped, no ConcurrentModificationException

Why: the counter is an unsynchronized int checked at one point in next(), so it can only notice a change that happened before the check and was visible to this thread.

The fix: do not rely on the alarm.

NoAlarmNeeded.javaruns offline
list.removeIf(s -> s.equals("D"));                 // ✅ FIX single thread: no iterator, no hole
var shared = new ConcurrentHashMap<String, Integer>();   // ✅ FIX shared across threads: weakly consistent, defined behaviour

What you see now: all elements handled, behaviour defined by the structure and not by luck.

console after the fix
after removeIf: [A, B, C, E]       every element examined exactly once, nothing skipped

Land it Fail-fast is a smoke detector, not a sprinkler system — it usually alerts you, it never protects you, and silence proves nothing.

Likely follow-ups
"Why did the JDK not make modCount volatile to strengthen the check?"

Because the check was never meant to be a concurrency mechanism.

A volatile write on every structural modification would add a memory barrier to every add and remove in single-threaded code, which is nearly all uses.

Even with volatile, the check would still be racy: a modification between the modCount read and the element read would go undetected.

So the guarantee would still be best-effort.

The design decision was to keep fail-fast as a cheap debugging aid for the programmer errors it catches deterministically, the single-threaded ones, and to tell people to use the concurrent collections for cross-thread cases.

The Javadoc wording, "should be used only to detect bugs", is exactly that stance.

"Give me a case where catching ConcurrentModificationException seemed reasonable and was wrong."

A cache eviction loop that iterated a shared HashMap and wrapped the loop in a retry on ConcurrentModificationException, on the theory that the writer would finish and the retry would succeed.

Under load the writer never paused, so the loop retried for seconds and burned CPU.

Worse, on iterations that did not throw, the reader had already walked a partially resized table and processed some entries twice and others not at all, because the exception is not guaranteed.

The right fix was to switch to ConcurrentHashMap, whose iterator is weakly consistent and never throws, and to make eviction a single removeIf on the entry set, which is atomic per entry.

Catching the exception had turned an occasional alarm into a silent data corruption.

"How would you find real concurrent modification if the exception cannot be trusted?"

By reasoning about ownership, then by tooling. First, I list every collection reachable from more than one thread and check each for a lock or a concurrent type; anything shared and plain is a bug regardless of symptoms.

Then I use a race detector: Java has no production-grade equivalent of ThreadSanitizer, but jcstress can exercise a suspected pair of operations under stress, and running the test suite with -XX:+UseSerialGC and few cores versus many cores sometimes flushes out timing-dependent failures.

In production, JFR's jdk.JavaMonitorEnter events show where locks are taken, and their absence around a shared structure is the evidence. The exception is a bonus when it fires, never the detection strategy.

Drill · Lists, deques, and lists that lie

Whether you choose sequence types on mechanical grounds — memory layout and copy cost — and know which "lists" are really views over someone else's data.

Q51. "How does ArrayList grow, and why do we still call add an O(1) operation when growing copies the whole array?"

Reveal answer

Strong answer ArrayList stores its elements in a plain Object[]. When an add finds the array full:

  1. Allocate: a new array 1.5 times as large — the source computes oldCapacity + (oldCapacity >> 1).
  2. Copy: everything over with Arrays.copyOf.

The default sequence runs 10, 15, 22, 33 and so on.

Note that new ArrayList<>() starts with a shared empty array and only allocates the first 10 slots on the first add.

Add is amortized O(1): amortized means we charge the occasional expensive operation across all the cheap ones.

Because capacity grows geometrically, the total number of element copies over n adds is bounded by a constant multiple of n, so the average cost per add is constant even though an individual add is occasionally linear.

When the final size is known, presize with new ArrayList<>(n) or call ensureCapacity and the copies disappear entirely.

Picture it the backing array of an ArrayList filling up and growing 10 to 15 to 22, with size and capacity shown before and after each growth.

The setup: an empty list that receives 100 integers one at a time.

ArrayListGrowth.javaruns offline
List<Integer> list = new ArrayList<>();      // elementData = shared empty array, capacity 0
for (int i = 1; i <= 100; i++) list.add(i);  // ❌ TRAP (mild): about 6 grows and 202 element copies
// ✅ FIX when the size is known: new ArrayList<>(100) -> one allocation, zero copies

Make the invisible visible: the array before and after the 11th add, the first growth.

backing array: size versus capacity
new ArrayList<>()   elementData = shared empty array     size 0    capacity 0
add #1              grows to 10 slots
add #10             [ 1  2  3  4  5  6  7  8  9 10 ]                     size 10   capacity 10   full
add #11             newCapacity = 10 + (10 >> 1) = 15, Arrays.copyOf copies 10 references
   BEFORE           [ 1  2  3  4  5  6  7  8  9 10 ]                     size 10   capacity 10
   AFTER            [ 1  2  3  4  5  6  7  8  9 10 11  .  .  .  . ]      size 11   capacity 15
add #16             15 + (15 >> 1) = 22          copies 15
add #23             22 + (22 >> 1) = 33          copies 22

The trace: which adds are cheap, which pay for a copy (marked in the trace), and what the copies add up to.

growth trace for 100 adds
add #1      allocate 10                       ✗ (no copy, first allocation)
add #2..10  write one slot                    ✓
add #11     10 -> 15   copy 10                ✗
add #16     15 -> 22   copy 15                ✗
add #23     22 -> 33   copy 22                ✗
add #34     33 -> 49   copy 33                ✗
add #50     49 -> 73   copy 49                ✗
add #74     73 -> 109  copy 73                ✗
all other adds: one array write               ✓
total copies = 10+15+22+33+49+73 = 202 for 100 adds, about 2 per add: amortized O(1)

Why: capacity grows by a constant factor, so each copy is paid for by the many cheap adds since the previous one.

Land it Geometric growth is the whole trick — grow by a constant amount instead of a constant factor and appending n items degrades to O(n²).

Likely follow-ups
"Why 1.5 and not 2, and what does that trade?"

Growth factor controls two things: how many copies you do, and how much memory sits unused. Doubling means fewer copies, at most log2(n) grows, but on average 25% of the array is empty and the worst case is nearly half.

Growing by 1.5 does about 70% more grows for the same final size, but the average slack is smaller.

There is also a well-known argument that with a factor below the golden ratio, roughly 1.618, freed blocks from earlier arrays can be coalesced to fit the next one, which mattered for C allocators more than for a moving GC.

The JDK chose 1.5 as a memory-leaning compromise. StringBuilder uses 2n + 2, and HashMap must double because of the power-of-two table.

"What is the maximum size of an ArrayList, and what happens near it?"

The backing array is a Java array, so its length is bounded by Integer.MAX_VALUE, and in practice by SOFT_MAX_ARRAY_LENGTH, which is Integer.MAX_VALUE - 8, because some JVMs reserve header words in the array object.

ArraysSupport.newLength handles the growth arithmetic: if the 1.5 growth overflows, it clamps to the soft maximum, and if even that is insufficient it throws OutOfMemoryError: Required array length too large.

So an ArrayList holds at most about 2.1 billion references, 8 GB of pointers with compressed oops off, and growth near the limit stops being geometric.

Anything that large should be a chunked structure or off-heap, and the interviewer wants to hear that the int index is a real ceiling.

"What does the ensureCapacity or presize actually save, in numbers?"

Starting from the default 10 and growing to a million elements takes about 29 grows.

The total number of element copies is bounded by roughly 3n, so about three million reference copies plus 29 array allocations totalling around 12 MB of garbage with compressed pointers. Presizing to a million does zero copies and one allocation of 4 MB.

On a modern machine the copies cost a few milliseconds, so this is rarely the bottleneck. The more important saving is the transient garbage and the largest intermediate arrays, which in G1 can be humongous allocations.

For a list built once per request, presizing when the size is known is free and I do it; for a list that grows unpredictably, I leave the default.

"Does trimToSize matter, and when would you call it?"

It replaces the backing array with one exactly the current size, releasing the slack.

It matters only for long-lived lists that were built large and then shrank, or that have up to a third of wasted capacity and are held in the millions.

A cache of a hundred thousand lists each with 30% slack is real memory.

I would call it after the build phase of a long-lived structure, or better, convert to an immutable List.copyOf, which is exactly sized and also signals that construction is finished.

Calling it on a list that will grow again is counterproductive, because the next add triggers another grow and copy. It is a footnote in most services and a meaningful lever in memory-bound ones.

Q52 · Scenario. "A teammate switched a hot path from ArrayList to LinkedList because it does many inserts in the middle, and the benchmark got slower. Explain why — and tell me honestly when you would ever use LinkedList."

Reveal answer

The real test Whether your mental cost model includes memory hardware, or stops at textbook big-O.

Strong answer The textbook says linked-list insertion is O(1), but that price only applies once you are already holding the node.

To insert at position i you must first walk i nodes from the head, which is O(n) by itself. So list.add(i, x) is linear for both structures, and the constant factors then decide it:

  1. Cache locality — the CPU (central processing unit) reads memory in 64-byte cache lines, so consecutive array elements arrive nearly free, while each linked node lives at a scattered heap address and every hop risks a cache miss costing on the order of a hundred cycles. ArrayList's shift is a System.arraycopy over contiguous memory, which hardware executes extremely fast; the list walk is a chain of dependent pointer loads, which is close to the worst access pattern modern hardware has.
  2. Memory overhead — every LinkedList node is a separate object carrying a header plus three references, roughly 40 bytes per element against the array's single reference slot, which triples the footprint and adds garbage-collection work.

The honest answer to "when would you use it": almost never.

  • The one defensible case: holding a ListIterator and splicing elements in or out during a single sequential traversal, where you genuinely are at the node already.
  • Stacks and queues: ArrayDeque beats it too.

In nine years I have not shipped a LinkedList that survived a code review with a benchmark attached.

Picture it inserting at index 4 of a ten-element list, once as linked nodes with the pointer hops counted, once as an array with the shift counted.

The setup: a ten-element list and one insert in the middle.

MiddleInsert.javaruns offline
List<String> linked = new LinkedList<>(List.of("N0","N1","N2","N3","N4","N5","N6","N7","N8","N9"));
List<String> array  = new ArrayList<>(List.of("N0","N1","N2","N3","N4","N5","N6","N7","N8","N9"));
linked.add(4, "X");     // ❌ TRAP: "O(1) insert" is preceded by a walk of 4 hops
array.add(4, "X");      // one System.arraycopy of 6 contiguous references

Make the invisible visible: the nodes with prev and next arrows, the hops to reach index 4, and the four pointer writes after it.

LinkedList nodes and hops
first                                                                  last
  v                                                                      v
 [N0] <-> [N1] <-> [N2] <-> [N3] <-> [N4] <-> [N5] <-> ... <-> [N9]
     hop1     hop2     hop3     hop4
  node(4): 4 < size/2 (5), so walk from first: 4 dependent pointer loads, each may miss the cache

insert X before N4 (linkBefore): 4 pointer writes
 X.prev = N3     X.next = N4     N3.next = X     N4.prev = X
 [N3] <-> [X] <-> [N4]

The trace: the array does one bulk move instead of a chain of loads.

ArrayList shift
before   index  0  1  2  3  4  5  6  7  8  9 10 ...      size 10  capacity 15
                N0 N1 N2 N3 N4 N5 N6 N7 N8 N9  .
arraycopy(elementData, 4, elementData, 5, 6)             six references = 24 bytes, inside one cache line
after    index  0  1  2  3  4  5  6  7  8  9 10 ...      size 11  capacity 15
                N0 N1 N2 N3  X N4 N5 N6 N7 N8 N9
LinkedList: 4 hops + 4 writes, scattered     ArrayList: 1 contiguous copy of 6 slots

What you see: at a million elements both are linear, and the linked one pays for every hop.

JMH excerpt
# illustrative output  (1,000,000 elements, insert at a random index)
Benchmark                   Mode  Cnt     Score    Error  Units
InsertAt.arrayListAddAt     avgt   10   180.4 ±   6.1  us/op     # average 500,000 slots shifted
InsertAt.linkedListAddAt    avgt   10  1450.7 ±  55.9  us/op     # average 250,000 hops, each a likely cache miss

Why: the walk is a chain of dependent loads from scattered addresses, which the hardware cannot overlap, while the shift is a streaming copy.

Land it Big-O counts operations but hardware charges for memory access patterns — and on that bill, contiguous arrays win almost everything.

Likely follow-ups
"What are the exact per-node and per-element memory costs, with and without compressed oops?"

A LinkedList.Node has a header plus three references: item, next, prev.

With compressed oops, the default on heaps under about 32 GB, that is 12 + 12 = 24 bytes per node, so the list costs 24 bytes per element beyond the elements themselves.

Without compressed oops, references are 8 bytes and the header is 16, giving 40 bytes.

With compact object headers, a product feature in JDK 25 enabled by -XX:+UseCompactObjectHeaders but off by default as of Aug 2026, it drops to 20 bytes.

An ArrayList costs 4 bytes per element in the array plus up to 50% slack, so 4 to 6 bytes. That is a four-to-six-fold difference before counting cache behaviour, and it is why the "many inserts" benchmark still loses.

"The teammate says they measured LinkedList winning once. When could that be real?"

Two honest cases.

  1. The front of a very large list: ArrayList.add(0, x) shifts the entire array on every call, O(n) per insert with a large constant, while LinkedList.addFirst is O(1) with no traversal. But ArrayDeque beats both there.
  2. Many insertions in one traversal: holding a ListIterator, each it.add(x) is O(1) on LinkedList and O(n) on ArrayList, so a pass that inserts a separator after every element is linear versus quadratic.

If their benchmark did either of those, it is real.

If it called add(i, x) with a random index, it is measurement error, and I would ask to see the JMH code.

"How would you benchmark this properly rather than argue about it?"

With JMH, the OpenJDK microbenchmark harness, because a hand-timed loop gets folded away by the JIT.

I would write a state class that builds each list to a realistic size, say 10,000 and 1,000,000 elements, and benchmark methods for the actual operations the hot path does: iteration, indexed get, insert at a random index, insert via iterator.

I would run with -prof gc to see allocation per operation, and with -prof perfnorm on Linux to see cache misses per operation, which is where the linked list loses.

And I would report the throughput with error bars, not a single number.

The result usually settles the argument in ten minutes and gives a number to put in the review.

"At 10 million elements, what changes about this choice?"

The array's contiguity becomes both its strength and its risk.

A 10-million-element ArrayList needs a single 40 MB array with compressed pointers, which G1 must allocate as a humongous object in contiguous regions, and growing it copies 40 MB at a time. A fragmented old generation can fail that allocation and trigger a full GC.

The linked list spreads across 240 MB of small nodes, which allocate anywhere but make every traversal a cache-miss festival and burden the GC with 10 million objects to trace.

Neither is good. At that scale I look at chunked lists, off-heap buffers via the Foreign Function and Memory API, final since JDK 22, or primitive arrays, and I ask whether the whole collection needs to be in memory at once.

Q53. "Why is ArrayDeque the default recommendation for stacks and queues instead of Stack or LinkedList?"

Reveal answer

Strong answer java.util.Stack is legacy on two counts:

  • Locking: it extends Vector, so every operation takes a lock you almost never need.
  • Leaky abstraction: being a List, it exposes indexed access that breaks the stack abstraction entirely.

LinkedList works as a Deque but pays the per-node allocation and pointer-chasing costs from the previous question on every single operation.

ArrayDeque is a ring buffer — a plain array where head and tail indexes wrap around the ends.

Pushing and popping at either end is an amortized O(1) array write with no allocation, and the elements sit contiguously for the cache.

Two caveats worth naming:

  • No nulls: it rejects null elements, because null is its internal marker for an empty slot.
  • Not thread-safe: for cross-thread handoff you reach for ArrayBlockingQueue or ConcurrentLinkedQueue instead.

Picture it a circular array of eight slots with head and tail, going through a wrap-around and the growth that follows.

The setup: a deque with an eight-slot array, filled, drained a little, and filled again until the tail wraps and the array fills.

RingBuffer.javaruns offline
Deque<String> dq = new ArrayDeque<>(7);      // array of length 8 (numElements + 1)
dq.addLast("A"); dq.addLast("B"); dq.addLast("C");
dq.pollFirst(); dq.pollFirst();               // A and B leave, head moves to index 2
for (String s : List.of("D", "E", "F", "G", "H")) dq.addLast(s);   // tail runs off the end and wraps to 0
dq.addLast("I");                              // written at index 0
dq.addFirst("Z");                             // head steps back to 1, meets tail -> array is full -> grow
System.out.println(dq);                       // Result: [Z, C, D, E, F, G, H, I]

Make the invisible visible: the array after every step, with the head index (first element) and the tail index (next free slot).

circular array: head and tail
step                       0 1 2 3 4 5 6 7     head tail
new ArrayDeque<>(7)        . . . . . . . .       0    0
addLast A, B, C            A B C . . . . .       0    3
pollFirst x2               . . C . . . . .       2    3     slots are nulled, head moves right
addLast D E F G H          . . C D E F G H       2    0     tail ran past index 7 and wrapped to 0
addLast I                  I . C D E F G H       2    1     I sits at index 0, BEFORE head in the array
addFirst Z                 I Z C D E F G H       1    1     head == tail: the array is full ✗ grow

The trace: growth allocates a longer array and keeps the logical order; the head and tail positions below follow the current JDK source, which slides the wrapped part to the end of the new array.

growth from 8 to 18 slots
newCapacity = 8 + 10 = 18          (small arrays grow by oldCapacity + 2, larger ones by 50%)
idx      0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17
after    I  .  .  .  .  .  .  .  .  .  .  Z  C  D  E  F  G  H      head=11  tail=1
reading order from head: Z C D E F G H, wrap to index 0: I   ✓ (matches the printed deque)

Why: head and tail are just two indexes that wrap, so both ends are plain array writes, and the cost is one occasional copy when they meet.

The fix: what to use instead of Stack, since Stack even allows indexed reads.

StackVersusDeque.javaruns offline
Stack<Integer> old = new Stack<>();          // ❌ TRAP: Vector locking on every call
old.push(1); old.push(2);
old.get(0);                                  // ❌ TRAP: indexed access on a "stack" compiles and works

Deque<Integer> stack = new ArrayDeque<>();   // ✅ FIX: array writes, no lock, no get(int)
stack.push(1); stack.push(2);
stack.peek();                                // Result: 2   (no get(0) exists on Deque)

Land it For single-threaded LIFO or FIFO work the decision is settled: ArrayDeque, and the other two only appear in interviews and old code.

Likely follow-ups
"How does the ring buffer grow, and what does that cost?"

ArrayDeque keeps head and tail indexes into an array and wraps them with a modulo or a mask; when head catches tail the buffer is full.

It then allocates a larger array, growing by 50% for larger sizes and by doubling for small ones.

It copies the elements in two System.arraycopy calls to straighten out the wrap, resetting head to zero.

The elements are copied with System.arraycopy so the wrapped part keeps its order; the picture above shows where head and tail end up. Current JDKs do this with one copy that slides the wrapped part to the end of the new array.

So growth is amortised O(1) like ArrayList, with a similar geometric series of copies.

The default initial capacity is 16 plus one, and you can presize with new ArrayDeque<>(n).

It never shrinks, so a deque that once held a million elements keeps the array; if that matters, create a new one.

"If ArrayDeque is not thread-safe, what do you use for a work queue between threads?"

It depends on whether producers should block when the queue is full. The options:

  • ArrayBlockingQueue: a bounded ring buffer with one lock and two conditions, giving backpressure by blocking the producer, which is usually what a work queue needs.
  • LinkedBlockingQueue: separate locks for put and take, so it scales slightly better under contention, and it is optionally bounded.
  • ConcurrentLinkedQueue: lock-free and unbounded, good for handoffs where blocking is unacceptable but with no backpressure at all.
  • LinkedTransferQueue and SynchronousQueue: direct handoff.

In an ExecutorService, the queue choice determines whether a burst grows memory without limit, so I always pick a bounded queue and a rejection policy for request-path executors.

"Why does null being rejected matter in practice?"

Because poll() and peek() return null to signal an empty deque, so a stored null would be indistinguishable from emptiness.

The implementation also uses null as its internal empty-slot marker.

null in a dequeruns offline
Deque<String> d = new ArrayDeque<>();
d.push(null);                          // ❌ TRAP: NullPointerException, null marks an empty slot
new LinkedList<String>().push(null);   // Works: LinkedList accepts null, so a swap can change behaviour

The practical effect is that a work queue carrying Optional-like results cannot store "no result" as null; you need a sentinel object or wrap the payload.

It also means code migrating from LinkedList, which accepts nulls, can start throwing NullPointerException on push(null) where it previously worked silently.

I regard that as an improvement, since a null in a queue is almost always a bug upstream, but it needs a test when you swap implementations.

Q54. "What does Arrays.asList actually return, and what are its classic traps?"

Reveal answer

Strong answer It returns a private class — java.util.Arrays$ArrayList, not the real ArrayList — which is a fixed-size view directly backed by the array you passed in. Nothing is copied. That produces three traps:

  1. Fixed size: add and remove throw UnsupportedOperationException, because the backing array cannot change length.
  2. Write-through: set works and writes straight through to the original array, and edits to the array show through to the list. It is a live two-way bridge, which surprises anyone treating the result as an independent copy.
  3. Primitives: Arrays.asList(someIntArray) compiles but returns a List<int[]> of size one, because the varargs type parameter cannot bind to a primitive, so the whole int[] becomes the single element. Box to Integer[] first, or use IntStream.of(a).boxed().toList().

Picture it the array and the list sharing one object, so a write on either side shows on the other, and the int[] case where the whole array becomes one element.

The setup: the code below (moved here from the answer) shows the calls, the two traps and the alternatives.

what Arrays.asList actually returnsruns offline
List<String> list = Arrays.asList("a", "b", "c");

list.set(0, "z");    // Works: it is a fixed-size VIEW, set writes through
list.add("d");       // ❌ TRAP: UnsupportedOperationException
list.remove(0);      // ❌ TRAP: UnsupportedOperationException

// It returns java.util.Arrays$ArrayList — a different class from
// java.util.ArrayList — which wraps the array without copying it.

// ❌ TRAP 1 — it is a VIEW. Changing the array changes the list, and vice versa.
String[] arr = {"a", "b"};
List<String> view = Arrays.asList(arr);
arr[0] = "CHANGED";
System.out.println(view.get(0));      // Result: "CHANGED"

// ❌ TRAP 2 — primitives. int[] is a single object, not an array of Integer.
int[] nums = {1, 2, 3};
List<int[]> wrong = Arrays.asList(nums);        // size 1! A list of one int[]
// ✅ FIX: box first
List<Integer> right = Arrays.stream(nums).boxed().toList();

// THE THREE OPTIONS COMPARED:
Arrays.asList("a", "b")        // fixed-size, mutable elements, view, ALLOWS null
List.of("a", "b")              // fully immutable, REJECTS null, no view
List.copyOf(other)             // fully immutable snapshot of an existing collection
new ArrayList<>(List.of(...))  // ✅ FIX: what you usually actually want: growable

The null behaviour is the migration trap. Replacing Arrays.asList with List.of looks like a modernisation until a null reaches it, at which point a list that used to hold a null starts throwing NullPointerException at construction.

Make the invisible visible: which objects exist and who points at them.

memory picture
stack                          heap
arr  ----------------------->  String[2] { "CHANGED", "b" }  <------+
view ---> Arrays$ArrayList { a ------------------------------------+ }     no copy: same array object

nums  ---> int[3] { 1, 2, 3 }  <--- Object[1] { [0] } <--- wrong (Arrays$ArrayList { a })
           wrong.size() == 1      the list's only element is the whole int[]

The trace: calls on a list made from {"a", "b", "c"}.

  • Works: list.set(0, "z") writes into the original array.
  • Works: Collections.shuffle(list) and Collections.reverse(list), because they only use set.
  • Fails: list.add("d") throws UnsupportedOperationException.
  • Fails: list.remove(0) throws UnsupportedOperationException.
  • Silently wrong: Arrays.asList(nums).size() is 1, not 3.

What you see: the exception and the surprising size.

console
# illustrative output
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.base/java.util.AbstractList.add(AbstractList.java:...)
        at java.base/java.util.AbstractList.add(AbstractList.java:...)
wrong.size() = 1            view.get(0) = CHANGED

Why: the class wraps the array you gave it and only implements the operations a fixed-length array can support.

The fix: copy when you want an independent, growable list.

IndependentList.javaruns offline
List<String> copy = new ArrayList<>(Arrays.asList("a", "b", "c"));   // ✅ FIX: own array, growable
copy.add("d");                                                       // Result: [a, b, c, d]
String[] arr = {"x", "y"};
copy.set(0, "q");                                                    // Result: arr still {"x", "y"}

What you see now: no exception and no write-through.

console after the fix
[a, b, c, d]        add works
arr = [x, y]        the array is untouched

Land it Read Arrays.asList as "wrap this array with a List interface", never as "copy this array into a list", and all three traps become predictable.

Likely follow-ups
"Is the write-through behaviour ever useful?"

Yes, occasionally, and knowing that separates people who avoid it out of fear from those who understand it.

Because it is a live view, you can use Collections algorithms on a plain array without copying:

  • Collections.shuffle(Arrays.asList(array)) shuffles the array in place.
  • Collections.reverse reverses it.
  • Collections.fill fills it.

You can also sort a section of an array through Arrays.asList(a).subList(i, j).sort(cmp), though Arrays.sort(a, i, j, cmp) is clearer.

The point is that the view is a zero-copy adapter between the array world and the collection world, and that is exactly what the name "as list" is trying to say. Using it as a quick way to build a list is the misuse.

"What does Arrays.asList(1, 2, 3).add(4) throw, and why is that not a bug?"

It throws UnsupportedOperationException from AbstractList.add, because Arrays$ArrayList does not override add or remove.

It only overrides the operations a fixed-size array can support: get, set, size, indexOf, contains, toArray, sort, and forEach.

That is the contract of an "optional operation" in the collections framework, spelled out in the List Javadoc, where structural changes are optional and implementations that cannot support them throw.

The same design lets List.of and Collections.unmodifiableList exist as List implementations.

The trade-off is that the type system does not distinguish mutable from fixed-size lists, which is why the trap exists.

"How do you turn a primitive array into a proper List of boxed values, cheaply?"

The standard routes:

  • IntStream.of(ints).boxed().toList() gives an immutable list.
  • .collect(Collectors.toCollection(ArrayList::new)) gives a mutable one.

Both allocate one Integer per element except for cached small values, which is unavoidable if you want a List<Integer>.

If the goal is to avoid boxing at all, do not convert: keep the int[] and use IntStream or a primitive collection library such as Eclipse Collections' IntArrayList.

And if someone wrote Arrays.asList(ints) expecting a list of integers, the compiler did tell them, since the inferred type is List<int[]>; a var declaration would have hidden that, which is one of my anti-var examples.

Q55. "Compare Arrays.asList, List.of, and List.copyOf — when do you reach for each?"

Reveal answer

Strong answer They differ on three axes: mutability, null handling, and whether data is copied.

  • Arrays.asList: a fixed-size live view over your array — elements replaceable via set, nulls allowed, no copy.
  • List.of: from Java 9, truly immutable and detached from any input array. It rejects nulls aggressively — even contains(null) may throw NullPointerException — and uses compact specialized implementations for small sizes, so it is also the cheapest way to write constants.
  • List.copyOf: a null-hostile immutable copy of any collection.

List.copyOf has one elegant optimization: if the source is already one of those immutable implementations, it returns the same instance without copying.

That makes it the ideal defensive-copy idiom at API (application programming interface) boundaries: this.items = List.copyOf(items) in a constructor is cheap when callers pass immutable lists and safe when they do not.

Picture it one array wrapped three ways, and what each wrapper does to the same five actions.

The setup: one shared example run through all three factories.

ThreeFactories.javaruns offline
String[] arr = {"a", "b"};
List<String> view = Arrays.asList(arr);     // view over arr, no copy
List<String> imm  = List.of(arr);           // List.of(E...) copies the array into an immutable list
List<String> copy = List.copyOf(view);      // immutable copy of the view

Make the invisible visible: which one shares the array and which ones own their data.

memory picture
arr  ----> String[2] { "a", "b" } <---- view (Arrays$ArrayList)            shares the array
imm  ----> ImmutableCollections.List12 { e0 = "a", e1 = "b" }              own fields, no array
copy ----> ImmutableCollections.List12 { e0 = "a", e1 = "b" }              own fields, copied from view
List.copyOf(imm) == imm  ->  true        same instance, nothing copied

What you see: each row is one action, each cell its outcome.

The same actions on the three lists
Actionview (Arrays.asList)imm (List.of)copy (List.copyOf)
x.set(0, "z")Works: writes arr[0]Fails: UnsupportedOperationExceptionFails: UnsupportedOperationException
x.add("c")Fails: UnsupportedOperationExceptionFails: UnsupportedOperationExceptionFails: UnsupportedOperationException
arr[0] = "CHANGED", then x.get(0)"CHANGED" (live view)"a" (detached)"a" (detached)
x.contains(null)Works: falseFails: NullPointerExceptionFails: NullPointerException
build from "a", nullWorksFails: NullPointerExceptionFails: NullPointerException
List.copyOf(x) == xfalse (a copy is made)true (same instance)true (same instance)

Why: the three factories differ in who owns the data and whether null is a legal element, and the table is just those two rules applied to each call.

Land it My defaults: List.of for literals, List.copyOf at every constructor boundary, and Arrays.asList only when I explicitly want a live array view.

Likely follow-ups
"Why do List.of and friends reject null so aggressively, even in contains?"

It was a deliberate design decision in JEP 269.

The designers wanted the immutable collections to be usable as value types with clear semantics.

Null elements complicate everything: Map.get returning null becomes ambiguous, hashing and comparison need special cases, and most callers treat null in a collection as a bug anyway.

Rejecting null on construction was uncontroversial.

Rejecting it in contains(null) was chosen for consistency with the concurrent collections, which also throw, and so that the specialised implementations could skip null checks in their hot paths.

The consequence you must know: migrating from Arrays.asList or new ArrayList to List.of can turn a silent null into a NullPointerException, and a contains(possiblyNull) call needs a guard.

"What are the compact specialised implementations, and why do they matter?"

List.of() with zero, one, or two elements returns ImmutableCollections.List12, a class with two fields and no array, and larger sizes return ListN backed by an exact-size array.

Set.of and Map.of similarly have Set12, Map1, and open-addressed SetN and MapN without entry objects.

The gains are memory and speed. A two-element list is 24 bytes instead of an ArrayList's 24-byte object plus a 16-plus-40-byte array, and there is no indirection.

They are also serialisable through a CollSer proxy so the class names are not part of the wire format.

The practical implication is that constants and small fixed collections should always be List.of, not Arrays.asList.

"When is List.copyOf a mistake at a boundary?"

It is a mistake in three situations:

  • Legitimate nulls: it throws.
  • Huge input read once: it copies eagerly.
  • Live views: the caller relies on the collection being live, such as a view over a changing source.

It also loses ordering guarantees that the input type expressed: copying a LinkedHashSet into Set.copyOf gives a set with randomised iteration order, which surprises code that relied on insertion order.

Finally, it returns the same instance when the input is already immutable, which is a feature.

It means the returned list can be identical to something the caller holds, so code that later checks identity gets confused.

None of those are common, but I mention the Set.copyOf ordering one because it has bitten real code.

"How do Stream.toList and Collectors.toList compare in this family?"

Stream.toList(), added in JDK 16, returns an unmodifiable list that, unlike List.of, permits null elements.

It is implemented as an unmodifiable wrapper around an exact-size array and is the right default for stream results.

Collectors.toList() is documented as making no guarantees about mutability or nulls, though in practice it returns an ArrayList, and a lot of code depends on that undocumented mutability.

Collectors.toUnmodifiableList() from JDK 10 rejects nulls like List.of.

So my choices are:

  • toList() for results that will be read;
  • Collectors.toCollection(ArrayList::new) when I need mutability and want to say so;
  • never bare Collectors.toList() when I plan to modify the result.

Q56 · Scenario. "A config service hands consumers Collections.unmodifiableList(settings). A consumer cached that list and later found its contents had changed underneath them. They're claiming your 'immutable' list mutated. What happened?"

Reveal answer

Strong answer Both sides are half right, which is exactly the trap.

Collections.unmodifiableList does not create an immutable list; it wraps the original in a view that rejects writes made through the wrapper.

The backing list is still the same live object. Anyone holding the original reference — here, the config service when it reloads settings in place — mutates what every consumer sees, with no exception anywhere. The steps I would walk through:

  1. Confirm the producer mutates the underlying list — a config reload that calls clear() and re-adds entries is the usual culprit — and note the consumers see a torn, half-reloaded list at exactly that moment, which is also a visibility hazard across threads.
  2. Decide what the contract should be. If consumers should get a stable snapshot, return List.copyOf(settings) — a genuine detached copy, and nearly free when the source is already immutable. On reload, build the new list fully and swap a single reference.
  3. If live updates are actually the intended contract, keep the unmodifiable view but document it loudly — a silent live view is how this ticket got filed.

The vocabulary matters in the room: unmodifiable means "not writable through this reference"; immutable means "cannot change, period". The List.of family gives the second; wrappers only give the first.

Picture it one live list with a read-only wrapper around it, and the reload that changes what the wrapper shows.

The setup: a config service that hands out an unmodifiable view and reloads in place.

ConfigService.javaruns offline
class ConfigService {
    private final List<String> settings = new ArrayList<>(List.of("a=1", "b=2"));
    List<String> getSettings() { return Collections.unmodifiableList(settings); }   // ❌ TRAP: a view, not a snapshot
    void reload() { settings.clear(); settings.add("a=1"); settings.add("b=3"); }
}
// consumer
List<String> cached = service.getSettings();
System.out.println(cached);        // [a=1, b=2]
service.reload();
System.out.println(cached);        // Result: [a=1, b=3]  same object, changed underneath

Make the invisible visible: the wrapper and the service point at the same list object.

memory picture
service.settings ---------------------------->  ArrayList [a=1, b=2]   <------+
consumer.cached --> UnmodifiableList { list --------------------------------+ }
cached.add("x")  -> UnsupportedOperationException   (the wrapper blocks writes)
settings.add(..) -> allowed, and cached shows it     (the owner's reference is not wrapped)

The trace: what a consumer on another thread can observe during the reload.

reload interleaving
step  service.reload()                  consumer reads cached
 1    settings.clear()                  []                  ✗ empty list, half-reloaded
 2    settings.add("a=1")               [a=1]               ✗ partial
 3    settings.add("b=3")               [a=1, b=3]          ✓ complete, but not what it cached

What you see: the same list printing two different contents.

console
[a=1, b=2]
[a=1, b=3]          <- the consumer never called anything between these two lines

Why: unmodifiableList blocks writes through the wrapper only; it does nothing about writes through the original reference.

The fix: publish an immutable snapshot and swap a single reference on reload.

SnapshotConfigService.javaruns offline
class ConfigService {
    private final AtomicReference<List<String>> current = new AtomicReference<>(List.of("a=1", "b=2"));
    List<String> getSettings() { return current.get(); }          // ✅ FIX: immutable, one volatile read
    void reload() { current.set(List.copyOf(loadSettings())); }   // ✅ FIX: build fully, then swap
}

What you see now: a consumer holds a stable snapshot and a fresh call sees the new one.

console after the fix
List<String> cached = service.getSettings();
System.out.println(cached);                    // [a=1, b=2]
service.reload();
System.out.println(cached);                    // [a=1, b=2]   unchanged
System.out.println(service.getSettings());     // [a=1, b=3]   new call, new snapshot

Land it A wrapper protects the list from its readers, not from its owner — when you promise a snapshot, copy; when you promise a feed, document.

Likely follow-ups
"You switched to List.copyOf and consumers now complain they miss config updates. What next?"

That is the contract question surfacing, which is good. A snapshot means consumers see the config as of the moment they asked, so anyone who cached it will hold it forever.

The correct pattern for both stability and freshness:

  1. Hold the snapshot in the service behind a volatile reference or AtomicReference<List<Setting>>.
  2. Swap in a fresh immutable list on reload.
  3. Have consumers call getSettings() each time they need it rather than caching.

Each call is a single volatile read, which is cheap. If a consumer needs to react to changes, offer a listener or a Flow.Publisher.

What I would not do is go back to the live view, because a torn read during reload is worse than either alternative.

"What does the torn read during a reload actually look like?"

The reload does settings.clear() followed by a loop of settings.add(...).

A consumer reading through the view between those calls sees an empty list, or a partial one.

If it iterates while the writer adds, it gets ConcurrentModificationException or, because the fail-fast check is best-effort, silently skips elements.

A consumer on another thread may also see a stale size and fresh elements, since there is no memory barrier.

In production this shows as a burst of "setting X not found" errors lasting milliseconds every time the config refreshes, which is very hard to reproduce.

Building the new list completely and then swapping one reference makes every reader see either the old or the new list, never a mixture.

"How would you document and enforce the snapshot contract in the API?"

In the return type first, then in the Javadoc. Returning List<Setting> says nothing; the Javadoc line "returns an immutable snapshot; call again to observe changes" says what matters. If the codebase uses Guava, returning ImmutableList<Setting> puts the guarantee in the signature.

A unit test enforces it: fetch the list, trigger a reload, assert the fetched list is unchanged and that a new fetch differs.

And a review rule: any method returning a collection from a service either returns an immutable copy or is explicitly named as a view, for example liveSettingsView(). Naming the exception makes the default obvious.

"Is there a performance concern with copying on every getSettings call?"

Only if you copy on every call, which you should not. Copy once at reload time and return the stored immutable list, so getSettings() is a field read.

List.copyOf on an already-immutable list returns the same instance without copying, so even a defensive List.copyOf(getSettings()) at a consumer's boundary is free. The only time copying costs is the reload itself, which is rare and off the request path.

If the config were large and read at very high rates, the volatile read is still the whole cost.

This is the general shape: pay for immutability once at the write, and reads become free and safe, which is the opposite of the wrapper approach where every read carries the risk.

Drill · Ordered, sorted, and specialist collections

Whether you know which structure buys which guarantee, and what actually breaks when a structure's contract is violated.

Q57. "How does LinkedHashMap keep its order, and what's the difference between insertion order and access order?"

Reveal answer

Strong answer LinkedHashMap is a HashMap whose entries are additionally threaded onto a doubly linked list — each entry carries a before-pointer and an after-pointer.

Lookups still go through the hash table at the same cost; only iteration changes, walking the linked list in a defined order instead of scanning buckets. The overhead is two references per entry plus head and tail pointers.

By default the list records insertion order — the order keys were first put — and re-puts of an existing key do not move it.

The three-argument constructor with accessOrder=true switches to access order.

Every get and every put of an existing key unlinks that entry and moves it to the tail, so the head is always the least recently touched entry.

One subtlety worth volunteering: in access-order mode a get restructures the list and bumps modCount.

So reading the map while iterating it throws ConcurrentModificationException even in a single thread.

Picture it the same table of buckets with a doubly linked list threaded through the entries, before and after one get in access-order mode.

The setup: three entries, in access-order mode.

AccessOrder.javaruns offline
var m = new LinkedHashMap<String, Integer>(16, 0.75f, true);   // true = access order
m.put("a", 1); m.put("b", 2); m.put("c", 3);
System.out.println(m.keySet());     // [a, b, c]
m.get("a");                         // a is touched
System.out.println(m.keySet());     // Result: [b, c, a]

Make the invisible visible: the hash table (index = hash & 15) and the linked list over it, before the get.

LinkedHashMap before get("a")
table[16]                       (lookups use only this part)
 [1] (a)   [2] (b)   [3] (c)    "a" = 97, 97 & 15 = 1;  "b" -> 2;  "c" -> 3

linked list over the same entries (iteration uses only this part)
 head --> (a) <--> (b) <--> (c) <-- tail          head = eldest, tail = newest

The trace: get("a") finds the entry through the table, then afterNodeAccess unlinks it and relinks it at the tail.

after get("a")
table[16]   unchanged:  [1] (a)   [2] (b)   [3] (c)
 1. find (a) through bucket [1]                              ✓ O(1), same as HashMap
 2. unlink (a):   head.after = (b); (b).before = null        pointer writes
 3. relink (a):   (c).after = (a); (a).before = (c); tail = (a)
 head --> (b) <--> (c) <--> (a) <-- tail
 modCount++        (a structural change in access-order mode)

What you see: a get that changes iteration order, and one that breaks a loop.

console
[a, b, c]
[b, c, a]
for (String k : m.keySet()) m.get(k);   // ❌ TRAP: get bumps modCount behind the iterator
-> ConcurrentModificationException on the next step

Why: the table finds entries, the linked list orders them, and access-order mode edits the linked list on every get.

Land it Access order is the entire reason the mode exists — the head being the least recently used entry is precisely the hook an LRU cache needs, which is the natural follow-up.

Likely follow-ups
"What did JDK 21's SequencedMap add to LinkedHashMap?"

LinkedHashMap now implements SequencedMap, which gives firstEntry(), lastEntry(), pollFirstEntry(), pollLastEntry(), putFirst(k, v), putLast(k, v), and reversed().

Before JDK 21 there was no way to get the eldest entry except entrySet().iterator().next(), which is why LRU caches had to use the removeEldestEntry hook.

Now an eviction is map.pollFirstEntry(), and a "touch" that moves a key to the newest position is map.putLast(k, map.get(k)) even in insertion-order mode.

reversed() is a live view in the opposite order, so iterating newest-first no longer needs a copy. LinkedHashSet gained the matching SequencedSet methods, including addFirst and addLast.

"What is the memory cost of the linked list on top of the hash map?"

Each LinkedHashMap.Entry extends HashMap.Node with two more references, before and after.

With compressed pointers the entry grows from 32 to 40 bytes, and the map itself adds head and tail.

That is a 25% overhead on the node, before keys and values, which for a million-entry map is about 8 MB extra.

Operations stay O(1) because the linking is constant work per insert and per removal.

In access-order mode each get does an unlink and relink, which is a handful of pointer writes.

So it is cheap enough to use whenever order matters, and expensive enough that I do not use it as a default Map type "just in case".

"If a get mutates the structure in access-order mode, what does that mean for concurrent readers?"

It means reads are writes, and the map is unsafe for concurrent readers even with no writer.

Two threads calling get on different keys each relink an entry to the tail, and the two relinks can interleave and corrupt the list, producing a cycle or a lost entry.

one possible interleaving
step  thread 1: get("a")                 thread 2: get("b")                 list
 1    reads tail = (c)                   reads tail = (c)
 2    (a).before = (c); (c).after = (a)  (b).before = (c); (c).after = (b)  ✗ (c).after written twice
 3    tail = (a)                         tail = (b)                         ✗ forward walk from (c) reaches only (b)

So an access-ordered LinkedHashMap must be fully synchronised for reads as well as writes, with Collections.synchronizedMap or an explicit lock, which serialises all access.

That is a hard limit on its use as a shared cache.

It is the reason production caches use a different design: Caffeine records reads into a lock-free buffer and applies them to its ordering asynchronously, so reads stay concurrent.

"Does re-inserting an existing key change insertion order?"

No, and the Javadoc is explicit: insertion order is not affected if a key is re-inserted. put on an existing key replaces the value and leaves the entry where it was.

If you want re-insertion to move the key to the end, you either remove and re-put, or since JDK 21 call putLast, which is exactly that operation in one call.

This distinction matters for anything that uses the map as a recency record, such as a "recently used files" list.

put alone will not bump an existing file to the top, and people report that as a bug.

Access-order mode handles it automatically, at the cost of also reordering on get.

Q58 · Scenario. "Build me a small in-memory LRU cache in plain Java, no libraries. What do you write, and what are its limits?"

Reveal answer

The real test Whether you know the JDK ships the hook for this — and whether you volunteer the production caveats unprompted.

Strong answer LRU — least recently used — eviction means that when the cache is full, the entry nobody has touched for the longest time is discarded.

LinkedHashMap in access-order mode already keeps that entry at the head of its list, and it exposes a protected hook, removeEldestEntry, called after every insertion; returning true evicts the head automatically. The whole class is shown under Picture it below.

Every get moves the entry to the tail; every put beyond capacity drops the head.

The limits I would state before anyone asks:

  1. It is not thread-safe, and because a get mutates the order links, even concurrent reads race — so wrapping requires Collections.synchronizedMap with the lock covering reads too, which serializes everything.
  2. It has no expiry, no size-by-weight, no statistics, and no protection against one burst scan evicting the whole working set.

In production I reach for Caffeine, whose Window TinyLFU policy also resists scan pollution — but this fifteen-line version is exactly right for a single-threaded tool or a per-request scope.

Picture it the cache as a linked list from eldest to newest, step by step through a get that refreshes an entry and a put that evicts one.

The setup: the whole implementation (code moved here from the answer), capacity 3.

LruCache.java
class LruCache<K, V> extends LinkedHashMap<K, V> {
    private final int maxEntries;

    LruCache(int maxEntries) {
        super(16, 0.75f, true);   // third arg: access order
        this.maxEntries = maxEntries;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > maxEntries;
    }
}

Make the invisible visible: the list before and after the fourth put, with the eviction hook firing.

eviction pointers
before put("d"):    head -> (b) <-> (c) <-> (a) <- tail                 size 3
link the new entry: head -> (b) <-> (c) <-> (a) <-> (d) <- tail         size 4 > capacity 3
afterNodeInsertion: removeEldestEntry(eldest = (b)) returns true  -> remove (b) from table and list
after eviction:     head -> (c) <-> (a) <-> (d) <- tail                 size 3

The trace: one line per call, list shown from eldest to newest.

LRU trace, capacity 3
put a      [a]
put b      [a b]
put c      [a b c]
get a      [b c a]          ✓ a relinked at the tail, so b is now the eldest
put d      [b c a d]  size 4 > 3  -> evict b   ✓
           [c a d]

What you see: the demo and the production caveats in one block (code moved here from the answer).

an LRU cache in eight linesruns offline
// LinkedHashMap has access-order mode and an overridable eviction hook.
// This is the whole implementation.
class LruCache<K, V> extends LinkedHashMap<K, V> {
    private final int capacity;

    LruCache(int capacity) {
        // initialCapacity, loadFactor, accessOrder=TRUE
        super(16, 0.75f, true);     // <- true = reorder on GET, not just PUT
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;   // called after each put; true -> evict eldest
    }
}

var cache = new LruCache<String, User>(3);
cache.put("a", u1); cache.put("b", u2); cache.put("c", u3);
cache.get("a");                    // "a" moves to the most-recent end
cache.put("d", u4);                // Result: evicts "b", the least recently USED
System.out.println(cache.keySet()); // Result: [c, a, d]

// WHAT I WOULD SAY ABOUT SHIPPING IT:
//  - ❌ TRAP: NOT thread-safe. Collections.synchronizedMap serialises everything;
//    for real concurrency use Caffeine.
//  - No TTL, no weighting, no stats, no async refresh.
//  - Access-order mode makes get() a STRUCTURAL modification, so a concurrent
//    read is a structural mutation — a surprise for anyone assuming reads are safe.
//  - ✅ FIX: in production I would reach for Caffeine, which does all of this with
//    a better eviction policy (W-TinyLFU) than pure LRU.

The access-order detail is worth stating. With accessOrder=true a get mutates the map's internal ordering, so two threads reading concurrently can corrupt it — which surprises people who assume that only writes need synchronising.

The trap: even a read relinks the list, so two readers can corrupt it.

two readers, one cache
step  thread 1: get("a")                 thread 2: get("c")                 tail
 1    unlink (a), reads tail = (b)       unlink (c), reads tail = (b)
 2    (b).after = (a); tail = (a)        (b).after = (c); tail = (c)       ✗ (a) is lost from the forward chain
 # one possible interleaving: the fix is a lock around every get and put, or a sharded or Caffeine design

Land it Knowing removeEldestEntry wins the coding points; knowing why you would still deploy Caffeine wins the senior points.

Likely follow-ups
"Make it thread-safe without serialising every read. What changes?"

The honest answer is that you cannot keep LinkedHashMap and get concurrent reads, because reads reorder the list.

The designs that work:

  1. Shard: split the cache into N independent LruCache instances each behind its own lock, chosen by key.hashCode() & (N-1), so contention drops by N and correctness holds.
  2. Decouple reads from reordering: keep entries in a ConcurrentHashMap and push each access into a bounded ring buffer that a single thread drains to update recency, which is Caffeine's design in miniature.

The second is a few hundred lines to do correctly.

In an interview I sketch the sharded version, because it is simple, correct, and good enough for most services, and I name Caffeine for the rest.

"Add time-based expiry to your version. What is the minimal correct change?"

Store the write timestamp alongside the value, a small record Entry(V value, long writtenAt), and check it on read.

In an overridden get, if now - writtenAt > ttl, remove the entry and return null.

That gives lazy expiry, so a stale entry costs memory until it is touched or evicted by size.

For active expiry you add a periodic sweep on a scheduled executor that iterates and removes expired entries, under the same lock as the map.

The details that matter:

  • Clock: use System.nanoTime() for elapsed time, never currentTimeMillis(), because wall-clock jumps break TTLs.
  • Refresh: decide whether a get refreshes the timestamp, which is the expire-after-access versus expire-after-write distinction Caffeine exposes as two settings.
"What does scan pollution mean and why does LRU suffer from it?"

LRU keeps whatever was touched most recently, so a single pass over a large dataset, a report that reads every customer once, pushes every hot entry out and fills the cache with entries that will never be read again.

The working set is gone and the hit ratio collapses until it is rebuilt. LRU has no notion of frequency, only recency.

Caffeine's Window TinyLFU keeps a small admission window and a frequency sketch, a compact count-min structure.

It only admits a new entry into the main region if it is estimated to be more frequently used than the entry it would evict, so a one-time scan mostly bounces off.

Java's LinkedHashMap offers no hook for that. If scans are part of the workload, the fifteen-line cache will disappoint.

"What would you cut from Caffeine's feature set if you had to write your own under time pressure?"

Everything except correctness and bounds. I would ship: a size bound with LRU eviction, a coarse lock or sharding for thread safety, expire-after-write checked lazily on read, and a hit-and-miss counter exposed as metrics, because a cache without a hit ratio is unmanageable.

I would cut: weighted sizes, refresh-ahead, async loading, removal listeners, and any frequency-based admission. I would also cut weak or soft references, because their eviction timing is at the GC's discretion and confuses capacity planning.

And I would write down that the cache is a placeholder for Caffeine, with a ticket, because the first time someone asks for scan resistance or per-entry TTLs, the home-grown version is finished.

Q59. "What is actually inside a TreeMap, in plain words, and what does it guarantee?"

Reveal answer

Strong answer A TreeMap is a red-black tree: a binary search tree in which every node's left subtree holds smaller keys and its right subtree larger ones.

Each node also carries a red or black marker, and a handful of rules about those colors force the tree to stay balanced, guaranteeing the deepest path is at most twice the shallowest.

That bounds every get, put, and remove at O(log n): about 20 comparisons for a million entries, against a HashMap's roughly one.

In exchange you get what hashing cannot give: keys held in sorted order — natural ordering or a supplied Comparator — plus ordered iteration and the whole navigation API.

Two practical notes:

  • Null keys: with natural ordering a null key throws NullPointerException because compareTo is called on it.
  • No equals or hashCode: lookups use only the comparator; equals and hashCode are never consulted.

Picture it seven keys inserted in ascending order, the red-black tree they form, and the exact comparisons a get, a floor and a ceiling make.

The setup: ascending inserts, which force rotations, then three lookups.

TreeShape.javaruns offline
var m = new TreeMap<Integer, String>();
for (int k = 10; k <= 70; k += 10) m.put(k, "v" + k);   // ascending order triggers rotations and recolouring
m.get(50);          // Result: v50 after 4 comparisons
m.floorKey(55);     // Result: 50
m.ceilingKey(55);   // Result: 60

Make the invisible visible: the tree that those seven puts leave behind, with node colours.

TreeMap as a red-black tree
                      20(B)
                  /          \
              10(B)           40(R)
                            /        \
                        30(B)        60(B)
                                    /      \
                                50(R)      70(R)
every root-to-leaf path has 2 black nodes; the deepest path has 4 nodes (limit: at most 2x the shortest)

The trace: each lookup is a walk down, one comparator call per node.

comparisons
get(50):         50 vs 20 -> right,  50 vs 40 -> right,  50 vs 60 -> left,  50 vs 50 -> found     4 compares
floorKey(55):    55 vs 20 -> right,  55 vs 40 -> right,  55 vs 60 -> left,  55 vs 50 -> right, null
                 last node passed with key <= 55 is 50                                           floor = 50
ceilingKey(55):  same walk; last node passed with key >= 55 is 60                               ceiling = 60
HashMap.get(50): one bucket index, usually one equals()     for 1,000,000 entries: TreeMap about 20 compares

What you see: answers in key order, and a lookup cost that grows with log n.

console
keySet()      -> [10, 20, 30, 40, 50, 60, 70]       always sorted
get(50)       -> v50
floorKey(55)  -> 50
ceilingKey(55)-> 60
depth for 1,000,000 entries: log2(1,000,000) is about 20 comparisons

Why: the colour rules bound the depth, so every walk is short, and the order of the tree is what makes floor and ceiling a single walk.

Land it Choose TreeMap when the questions are about order — nearest, next, range — and HashMap when they are only ever "exactly this key"; paying log n for order you never query is waste.

Likely follow-ups
"What are the memory and constant-factor costs compared with HashMap?"

A TreeMap.Entry holds key, value, left, right, parent references and a boolean colour, so with compressed pointers it is 40 bytes versus 32 for a HashMap.Node, and there is no table array.

Memory is comparable. The real cost is the log-n comparisons, each a virtual call to compareTo or the comparator, and each following a pointer to a node that may be anywhere in the heap.

So a million-entry TreeMap lookup touches about 20 cache lines against a HashMap's two or three.

In practice a TreeMap.get is roughly 5 to 20 times slower than a HashMap.get at that size, and comparators over strings make it worse. Iteration is in order but also pointer-chasing.

"What does the red-black tree guarantee about rebalancing cost on insert and delete?"

Insertion and deletion each do an O(log n) descent to find the position.

Then they do at most a constant number of rotations to restore the colour invariants, at most two for insertion and three for deletion, plus O(log n) recolourings.

That is the advantage over AVL trees, which can rotate O(log n) times on deletion, and why red-black was chosen for a general-purpose map with mixed reads and writes.

The invariants are:

  1. every node is red or black;
  2. the root is black;
  3. no red node has a red child;
  4. every path from a node to its leaves has the same number of black nodes.

Together they bound the depth at twice the minimum.

You never see the rotations, but they are why put cost is predictable.

"When would ConcurrentSkipListMap be the right sorted map?"

When many threads read and write a sorted map concurrently.

A skip list is a layered linked structure where each node appears in a random number of levels, giving expected O(log n) search without rebalancing, which makes it possible to implement lock-free with compare-and-swap; a red-black tree's rotations touch several nodes atomically and do not lend themselves to that.

So ConcurrentSkipListMap gives the whole NavigableMap API, floor, ceiling, sub-maps, with weakly consistent iteration and no global lock. Its costs are higher memory, since each node has multiple forward pointers, and slower single-threaded performance than TreeMap.

For a scheduler's timer wheel or a leaderboard updated from many threads, it is the right structure.

Q60 · Scenario. "After a new Comparator shipped, a TreeMap started 'losing' entries — containsKey returns false for keys we can literally see inside the map in a heap dump. What's going on?"

Reveal answer

Strong answer The tree is not losing entries; the search is taking the wrong turn.

A TreeMap lookup navigates purely by comparator decisions — left or right at each node.

If the comparator is inconsistent, an entry sits where the comparator once steered it, while today's search branches the other way, hits a leaf, and reports the key absent. The entry is present and unreachable at once. My checklist, in order of how often each is the culprit:

  1. Subtraction overflow — a comparator written as (a, b) -> a.value - b.value overflows for operands of opposite sign, making it non-transitive; a large negative compared to a large positive can come out "smaller is bigger". Replace with Integer.compare or Comparator.comparingInt.
  2. Mutable sort keys — if a field used in the comparison changed after insertion, the entry's recorded position no longer matches what the comparator now says, which is the same wrong-turn failure. The discipline: sort keys are immutable, or you remove the entry, mutate, and re-insert.
  3. Genuine contract violations — non-determinism, or comparisons inconsistent with each other for equal inputs. Reproduce by feeding the failing keys through the comparator directly and asserting antisymmetry and transitivity.

Also worth stating: a comparator inconsistent with equals makes the map violate the Map contract itself — two keys that equals says are the same can both live in the tree, or two different keys can collapse into one.

Picture it a three-node tree built under one ordering and searched under another, where the entry is visible in iteration but the walk never reaches it.

The setup: a comparator whose behaviour changes after the tree is built, standing in for "a new Comparator shipped" against a long-lived map.

LostEntry.javaruns offline
static boolean reversed = false;
Comparator<String> cmp = (x, y) -> reversed ? y.compareTo(x) : x.compareTo(y);   // ❌ TRAP: ordering changes under a live tree
var m = new TreeMap<String, Integer>(cmp);
m.put("b", 1); m.put("a", 2); m.put("c", 3);     // built under the old ordering
reversed = true;                                  // the new ordering ships
System.out.println(m.keySet());                   // Result: [a, b, c]  all three are in the tree
System.out.println(m.containsKey("c"));           // Result: false

Make the invisible visible: where "c" sits and which way the new comparator sends the search.

tree and search path
stored under the old order:        search for "c" under the new order:
          b                          at b: reversed compare("c", "b") < 0  -> go LEFT
        /   \                        at a: reversed compare("c", "a") < 0  -> go LEFT
       a     c   <- stored here      left of a is empty                     -> not found
                                     "c" is in the right subtree, which this search never enters

The trace: the same key, two orderings.

call trace
containsKey("c") under old order:  c > b -> right -> c == c                       found     ✓
containsKey("c") under new order:  c < b -> left  -> c < a -> left -> null        absent    ✗
iteration (in-order walk, no comparator use): a, b, c                             present   ✓

What you see: a heap dump that shows the entry and a lookup that denies it.

console
[a, b, c]
false

Why: a lookup trusts the comparator to repeat the decisions made at insertion, and the new comparator makes different ones.

The fix: keep the ordering fixed for the life of a tree, and rebuild under a new ordering.

Rebuild.javaruns offline
var rebuilt = new TreeMap<String, Integer>(newCmp);   // ✅ FIX: a fresh tree under the new ordering
rebuilt.putAll(m);                                    // re-inserts every entry with the new comparator
System.out.println(rebuilt.containsKey("c"));         // Result: true

What you see now: the lookup agrees with the iteration.

console after the fix
[c, b, a]      reversed order, as the new comparator says
true

Land it A sorted structure trusts its comparator absolutely — corrupt the ordering and you have not broken sorting, you have broken lookup itself.

Likely follow-ups
"You replaced the subtraction with Integer.compare and entries are still lost. What next?"

Then the comparator was not the only change, or the data is mutating.

I take the failing key and the entries visible in the dump, and run the comparator pairwise in a test, asserting antisymmetry and transitivity.

If that passes, the comparator is fine now but the tree was built under the old one, so a restart or a rebuild of the map fixes it. I check whether the map is long-lived across the deploy, for example in a session store.

If the comparator passes and the map is fresh, I check the keys for fields that change after insertion, by comparing the key's fields in the dump with what the comparator reads.

And I confirm the comparator has no dependency on external state such as a locale or a clock, which makes it non-deterministic.

"Show me how the subtraction overflow actually breaks transitivity."

Take three ints: a = 2,000,000,000, b = 0, c = −2,000,000,000.

Subtraction says a − b is positive, so a > b; b − c is positive, so b > c; but a − c overflows to a negative number, so the comparator says a < c.

subtraction comparator, three ints
a = 2_000_000_000   b = 0   c = -2_000_000_000
a - b = 2000000000                 > 0  ->  a > b
b - c = 2000000000                 > 0  ->  b > c
a - c = 4000000000 overflows int   -> -294967296 < 0  ->  a < c      ✗ not transitive

The tree may place a to the right of b, c to the left of b, and then a lookup for a starting from a node holding c goes the wrong way.

The same problem hits long and hits hashCode-based comparators.

Integer.compare, Long.compare, and Comparator.comparingInt use branches, not subtraction, and cannot overflow.

This is why Sonar and Error Prone both flag subtraction in compare methods.

"Why does the map contract say a comparator inconsistent with equals makes the map 'not obey' the contract?"

Because the Map interface defines its behaviour in terms of equals: containsKey(k) means some key e exists with k.equals(e). A TreeMap never calls equals; it defines "same key" as compare == 0. When the two agree, a TreeMap is a correct Map.

When they disagree, you get keys that are equal by equals stored twice, or distinct keys collapsed, and code written against Map semantics observes the wrong thing.

The Javadoc says the behaviour is well-defined, just not what Map promises.

It is the same rule as for TreeSet and for Comparable generally, and the reason I insist the comparator ends in a unique key.

"How do you make a Comparator deployment safe when the map is persisted or long-lived?"

Treat the comparator as part of the data format.

If a TreeMap survives restarts, in a session store, a serialised cache, or a database-backed sorted structure, then changing the ordering invalidates every existing structure and you must rebuild it, ideally by reading all entries into a HashMap and inserting them into a new TreeMap under the new order.

So a comparator change needs a migration step, a version tag, or a fresh cache on deploy.

In review I ask where every sorted structure lives and how long it lives, and any answer longer than "one request" makes the comparator change a data migration rather than a code change.

Q61. "When do TreeMap's floor, ceiling, and subMap methods earn their keep over a plain HashMap?"

Reveal answer

Strong answer They answer nearest-neighbor and range questions, which a hash table structurally cannot do without scanning everything.

floorEntry(k) returns the entry with the greatest key at or below k, and ceilingEntry(k) the least at or above.

subMap, headMap, and tailMap return live views of a key range.

Real uses I have shipped:

  • Time series: "the configuration active at time T" is exactly floorEntry(T) on a map keyed by effective timestamp.
  • Tiered pricing: the applicable band for an amount is a floor lookup.
  • Scheduling: the next event at or after now is a ceiling lookup.
  • Range reporting: subMap(from, to) iterates one slice in key order without touching the rest.

Each of these is O(log n) on a TreeMap and an O(n) full scan on a HashMap.

One caution: the sub-view is live — writes go through, and inserting a key outside the view's range throws IllegalArgumentException.

Picture it a number line of effective times with the queries drawn on it, and a table of what each navigation call returns at the boundaries.

The setup: three configuration versions keyed by the time they take effect.

ActiveConfig.javaruns offline
var cfg = new TreeMap<Integer, String>();
cfg.put(100, "A"); cfg.put(200, "B"); cfg.put(300, "C");
cfg.floorEntry(250);      // Result: 200=B   the config active at time 250
cfg.ceilingEntry(250);    // Result: 300=C   the next change at or after 250

Make the invisible visible: the keys on a line, with the answers for time 250.

number line
time   ...  100 ----------- 200 ----------- 300 ---->
config       A               B               C
                                  ^ t = 250
floorEntry(250)   = (200, B)     greatest key <= 250
ceilingEntry(250) = (300, C)     least key >= 250
HashMap.get(250)  = null         a hash lookup has no notion of "nearest"

The trace: the boundary cases that cause off-by-one bugs, with the two-argument forms spelled out.

boundaries
floorEntry(100)   = (100, A)     at or below      lowerEntry(100)   = null      strictly below
ceilingEntry(300) = (300, C)     at or above      higherEntry(300)  = null      strictly above
floorEntry(99)    = null         nothing at or below 99
headMap(200)      = {100=A}                       headMap(200, true) = {100=A, 200=B}
tailMap(200)      = {200=B, 300=C}                tailMap(200, false) = {300=C}
subMap(100, 300)  = {100=A, 200=B}                to-key exclusive by default

What you see: what works and what throws on the live view.

  • Works: cfg.subMap(100, 300).clear() deletes 100 and 200 from cfg itself.
  • Fails: cfg.subMap(100, 300).put(400, "D") throws IllegalArgumentException, because 400 is outside the view's range.
  • Fails: adding a key to cfg while iterating the view throws ConcurrentModificationException.

Why: the keys are stored in order, so floor and ceiling are one walk and a sub-map is just a pair of bounds over the same tree.

Land it The moment a requirement contains "at or before", "next after", or "between", the map wants to be a TreeMap — that phrasing is the interview tell.

Likely follow-ups
"What is the difference between floorEntry, lowerEntry, floorKey and headMap in edge cases?"

floorEntry(k) returns the greatest entry with key less than or equal to k; lowerEntry(k) is strictly less than. ceilingEntry and higherEntry are the mirror.

The Key variants return just the key, or null when nothing qualifies, which is a problem if null keys were allowed.

That is one more reason TreeMap forbids them with natural ordering.

headMap(k) is exclusive of k by default and headMap(k, true) is inclusive; tailMap(k) is inclusive by default.

Those defaults are historical and inconsistent, so I always use the two-argument forms with an explicit boolean when the boundary matters.

I also test the boundary case, since off-by-one on "active at time T" is a production bug in a pricing system.

"How would you implement 'configuration active at time T' at scale, and when does TreeMap stop being the answer?"

A TreeMap<Instant, Config> with floorEntry(t) is exact and O(log n), and it stays the answer for tens of thousands of versions per key.

It stops being the answer when the data does not fit in one process, or when many threads write it, or when you need the same query against a database, where the equivalent is an index on effective_from and a query for effective_from <= :t ORDER BY effective_from DESC LIMIT 1.

For concurrent in-memory use, ConcurrentSkipListMap has the same floorEntry. For very high read rates over a mostly static timeline, a sorted array with Arrays.binarySearch is smaller and faster than any tree, because it is contiguous.

"What are the traps with the live sub-map views?"

Three traps:

  1. Writes go to the parent: usually intended, but subMap(a, b).clear() deletes a range from the backing map, which surprises people who thought they had a copy.
  2. Out-of-range inserts: inserting a key outside the view's range through the view throws IllegalArgumentException.
  3. Shared modCount: structural changes to the parent while iterating the view throw ConcurrentModificationException.

Also note size() on a sub-map is O(n) in the range, since it counts by walking, unlike the parent's O(1).

If I need a snapshot of a range I copy it with new TreeMap<>(map.subMap(a, b)), and I say so in the variable name.

"Is there a TreeMap-style answer for range queries on multiple keys?"

Not directly; TreeMap orders on one comparator.

For two-dimensional ranges, such as "orders between two dates and two amounts", you either pick the more selective dimension for the tree and filter the rest, or use a composite key ordered by the primary then the secondary field, which supports prefix ranges but not arbitrary rectangles.

True multi-dimensional range queries need a k-d tree or an R-tree, which the JDK does not provide, or a database index.

In an interview I say the honest thing: a TreeMap gives you one sorted axis, and the moment a requirement needs two independent range predicates, the data belongs in a store that indexes both.

Q62. "How is HashSet implemented under the hood?"

Reveal answer

Strong answer HashSet is a thin wrapper around a HashMap<E, Object>: every element is stored as a map key, and the value slot holds one shared static dummy object named PRESENT.

add(e) is literally map.put(e, PRESENT) == null, which is also how it reports whether the element was new.

Everything I said about HashMap therefore transfers wholesale:

  • the same load factor and resize behavior;
  • the same treeification of bad buckets;
  • the same case for presizing bulk loads;
  • the same per-element footprint of a full map entry — around 32 to 40 bytes of overhead per element, since the set does not get a slimmer node type.

The pattern repeats across the family: LinkedHashSet wraps a LinkedHashMap, and TreeSet wraps a TreeMap.

Picture it a HashSet drawn as the HashMap it wraps, with one shared dummy value, and what add returns for a new and a repeated element.

The setup: two adds of the same element and one of another.

SetIsAMap.javaruns offline
Set<String> s = new HashSet<>();
s.add("x");     // Result: true   (map.put("x", PRESENT) returned null)
s.add("x");     // Result: false  (map.put("x", PRESENT) returned the old PRESENT)
s.add("y");     // Result: true

Make the invisible visible: the set holds a map, the map holds the elements as keys, and every value is the same object.

memory picture
HashSet
  map ---->  HashMap  table[16]   ("x" = 120, 120 & 15 = 8;  "y" = 121 -> 9)
              [8]  Node(key "x", value ----+)
              [9]  Node(key "y", value ----+)
                                           v
             HashSet.PRESENT   one static Object shared by every entry of every HashSet

The trace: add is a put, and the old value in the answer tells whether the key was new.

call trace
add("x")  -> map.put("x", PRESENT)  -> old value null     -> == null is true    new element    ✓
add("x")  -> map.put("x", PRESENT)  -> old value PRESENT  -> == null is false   already there ✗
contains("x") -> map.containsKey("x")                                           same lookup as HashMap.get

Why: one hash table implementation serves both, at the cost of one unused value reference per element.

Land it It is deliberate engineering economy — one hash table implementation to test and tune, with sets as a facade over it — and it means tuning knowledge transfers one-to-one.

Likely follow-ups
"Why not implement HashSet with its own slimmer node instead of wasting the value slot?"

It was an engineering trade: one implementation to test, one set of bugs, one place to tune, at the cost of 4 bytes per element for the unused value reference.

The JDK team judged that 4 bytes out of roughly 36 per element was not worth a second hash table implementation.

If that memory matters to you, alternatives exist:

  • Eclipse Collections' UnifiedSet stores elements directly in the table array with no node objects at all, roughly halving the per-element cost.
  • The JDK's own immutable Set.of uses open addressing in a plain array.

So the answer is that the JDK chose simplicity and left the specialised structures to libraries, which is a consistent philosophy across java.util.

"What does the PRESENT trick imply for HashSet serialisation and for equality between sets?"

Serialisation is custom: HashSet.writeObject writes the capacity, load factor, size, and then only the elements, not the map or the dummy values.

So the stream is compact and the class does not expose its implementation. On read it rebuilds the map.

Set equality is defined by AbstractSet.equals: same size and containsAll, so a HashSet and a TreeSet with the same elements are equal.

hashCode is the sum of element hashes, which is order-independent.

That is why a set's hash code is stable regardless of bucket layout, unlike its iteration order. It also means a set of mutable elements has a hash that changes when an element changes, which breaks any map keyed by that set.

"Does HashSet.contains have the same failure modes as HashMap.get?"

Exactly the same, because it is map.containsKey(o). A missing hashCode strands elements, a mutated element becomes invisible to contains and remove while still appearing in iteration, and a poor hash treeifies buckets.

a mutated element in a HashSetruns offline
var k = new ArrayList<>(List.of(1));        // hashCode 32
var set = new HashSet<List<Integer>>();
set.add(k);
k.add(2);                                   // ❌ TRAP: hashCode is now 994, the element sits in the old bucket
set.contains(k);                            // Result: false
set.remove(k);                              // Result: false
set.size();                                 // Result: 1, and iteration still shows it

There is one extra subtlety with sets: add returning false is often used as a "have I seen this" check in deduplication loops.

If the element's equals is broken, the loop silently keeps duplicates or drops distinct items.

When I debug a set, I go straight to the same questions I would ask about a map key: are the elements immutable, do equals and hashCode agree, and are they derived from the same fields.

Q63. "Why do EnumMap and EnumSet beat HashMap and HashSet when the keys are enums?"

Reveal answer

Strong answer Because enum constants come with a free perfect index: ordinal(), the constant's fixed position in its declaration.

EnumMap exploits that by being nothing but a values array indexed by ordinal — no hashing, no collisions possible, no entry node objects, and iteration always in declaration order. A get is one array read.

EnumSet goes further and stores membership as a bit mask: for enums up to 64 constants the entire set is a single long.

contains is one bit test, and bulk operations like retainAll collapse into single bitwise instructions across whole sets at once.

Both are dramatically smaller and faster than their hash-based equivalents, both reject null keys, and the declaration-order iteration is deterministic — pleasant for tests and logs.

Typical uses: per-state counters in a state machine, sets of feature flags, permission sets.

Picture it an enum's ordinals used as array positions for EnumMap and as bit positions for EnumSet, with the arithmetic written out.

The setup: a seven-constant enum, a map with two entries and a set with three members.

EnumInternals.javaruns offline
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
var plan = new EnumMap<Day, String>(Day.class);
plan.put(Day.WED, "gym"); plan.put(Day.MON, "work");
EnumSet<Day> busy  = EnumSet.of(Day.MON, Day.WED, Day.SAT);
EnumSet<Day> other = EnumSet.of(Day.MON, Day.WED, Day.THU);

Make the invisible visible: the EnumMap value array and the EnumSet bit mask, indexed by ordinal.

EnumMap array and EnumSet bits
EnumMap  vals[7]
ordinal   0     1   2     3   4   5   6
Day       MON   TUE WED   THU FRI SAT SUN
vals    "work"  .  "gym"  .   .   .   .          get(WED) = vals[2]: one array read, no hashing

EnumSet  one long, bit n = ordinal n
bit       6   5   4   3   2   1   0
Day       SUN SAT FRI THU WED TUE MON
busy      0   1   0   0   1   0   1     = 0b0100101 = 37

The trace: set operations are single instructions on the long.

bit arithmetic
busy.contains(WED):    (37 & (1L << 2)) != 0                 -> true        one bit test
other = {MON, WED, THU} = 0b0001101 = 13
busy.retainAll(other): 37 & 13 = 0b0000101 = 5               -> {MON, WED}   one AND for the whole set
busy.addAll(other):    37 | 13 = 0b0101101 = 45              -> {MON, WED, THU, SAT}

What you see: declaration order, always.

console
plan -> {MON=work, WED=gym}           iteration in ordinal order
busy after retainAll -> [MON, WED]
a HashMap with enum keys iterates in an order that is not the declaration order and can change between runs

Why: an enum gives every key a small, fixed, dense number, so an array index and a bit position replace hashing.

Land it When the key domain is small, fixed, and pre-numbered, hashing is pure overhead — reach for EnumMap and EnumSet by reflex whenever the key is an enum.

Likely follow-ups
"What happens with EnumSet for an enum with more than 64 constants?"

The factory methods choose the implementation: RegularEnumSet holds one long for up to 64 constants, and JumboEnumSet holds a long[] with one word per 64 constants for larger enums. Both are package-private, so your code only sees EnumSet.

Operations on the jumbo version loop over the words, so contains is still one array read plus a bit test, and bulk operations are a loop of a few word-wide instructions.

The threshold matters because a 65-constant enum roughly doubles the cost of every bulk operation relative to a 64-constant one; it is not a reason to avoid large enums, but it is a detail that shows you know it is a bit vector.

"How does EnumMap handle null values and what is its iteration cost?"

Null keys are rejected, but null values are allowed and are stored as a private NULL sentinel object in the value array, so that the map can distinguish "mapped to null" from "absent", which is simply an empty slot.

containsKey checks that the slot is non-empty, and get unmasks the sentinel back to null.

Iteration walks the array in ordinal order, skipping empty slots, so it is O(number of constants) rather than O(size), which only matters for a large enum with a sparse map.

size() is a maintained counter.

The entry objects are created lazily during iteration, so a map with no iteration allocates nothing beyond its two arrays.

"When are EnumMap and EnumSet the wrong choice despite the keys being enums?"

It is the wrong choice in four situations:

  • Concurrency: neither is thread-safe and there is no ConcurrentEnumMap in the JDK; use ConcurrentHashMap or wrap with Collections.synchronizedMap.
  • Immutable and shared: Map.of or Map.copyOf is fine and safe, but you lose declaration-order iteration, so if order matters, wrap an EnumMap in Collections.unmodifiableMap.
  • Other sort orders: when you need a sorted or navigable view by something other than ordinal, TreeMap with a comparator.
  • Huge and sparse: the array's fixed footprint is wasted, though that is rare.

Serialisation across versions is another caveat: EnumMap serialises by constant name, so a renamed constant breaks old streams.

"Why is ordinal() considered dangerous to use directly, if EnumMap uses it?"

Because ordinal() is a position in the source file, and reordering or inserting a constant changes every ordinal after it.

EnumMap and EnumSet use it only within one JVM run, where the enum's definition is fixed, so it is safe.

The danger is persisting it: storing an ordinal in a database or a message means the next reordering silently remaps every stored value to a different constant, with no error.

That is why JPA's @Enumerated(EnumType.ORDINAL) is a well-known trap and EnumType.STRING is the recommended default.

It is also why I give enums an explicit stable code field for anything that leaves the process. Ordinal is an implementation detail of the class file, not part of the data.

Q64 · Scenario. "A test asserts that iterating a PriorityQueue yields elements in priority order, and it fails intermittently. Why is the iteration order 'wrong'?"

Reveal answer

Strong answer Because a PriorityQueue is not sorted — it is a binary heap: an array arranged so that each parent element is no larger than its two children. That single rule guarantees exactly one thing: the smallest element sits at index zero.

Siblings and cousins have no defined order relative to each other, so the array read left to right looks shuffled.

The iterator simply walks that backing array, which is why the test sees "wrong" order.

It is intermittent because the heap's internal layout depends on the order elements were inserted, which varies run to run. The fixes:

  1. To consume in priority order, call poll() repeatedly — each poll removes the head and restores the heap rule in O(log n).
  2. To just view sorted, copy out and sort: queue.stream().sorted() or dump into a list.
  3. Fix the test to assert on polled order, never on iteration or toString, which also prints array order and regularly confuses people reading logs.

Worth adding: ties are unstable — equal-priority elements come out in no guaranteed order.

The heap's laziness is the point: it does O(log n) work per operation precisely by never maintaining more order than "the minimum is on top".

Picture it the heap as an array and as a tree, built one offer at a time, then taken apart with poll.

The setup: six numbers offered in one order, printed, then polled.

HeapOrder.javaruns offline
var pq = new PriorityQueue<Integer>();
for (int x : new int[]{5, 3, 8, 1, 9, 2}) pq.offer(x);
System.out.println(pq);                       // ❌ TRAP: prints the backing array, not sorted order
while (!pq.isEmpty()) System.out.print(pq.poll() + " ");   // ✅ FIX: poll yields priority order

Make the invisible visible: the array after each offer (sift-up), and the tree it represents.

building the heap
offer 5   [5]
offer 3   [3 5]            3 < parent 5, swap
offer 8   [3 5 8]
offer 1   [1 3 8 5]        1 < 5 swap, 1 < 3 swap
offer 9   [1 3 8 5 9]
offer 2   [1 3 2 5 9 8]    2 < parent 8 swap, 2 > 1 stop

index:   0 1 2 3 4 5       children of i are 2i+1 and 2i+2
array: [ 1 3 2 5 9 8 ]
                 1
              /     \
             3       2
            / \     /
           5   9   8       only rule: each parent <= its children

The trace: poll takes the root, moves the last element to the root and sifts it down.

first poll
poll():  result = 1
         last element 8 moves to the root:   [8 3 2 5 9]
         sift down: children 3 and 2, smaller is 2 < 8, swap:   [2 3 8 5 9]       ✓ new minimum at the root
the same six numbers offered as 9, 8, 5, 3, 2, 1 give the array [1 3 2 9 5 8]    layout depends on insertion order

What you see: the printed queue is array order, and only poll is sorted.

console
[1, 3, 2, 5, 9, 8]          <- System.out.println(pq): array order ✗
1 2 3 5 8 9                 <- repeated poll(): priority order ✓

Why: the heap rule only orders each parent against its children, so siblings and cousins sit in no particular order.

What you see now: a test that polls gets the same sequence whatever the insertion order.

console after the fix
offered 5,3,8,1,9,2  -> polled 1 2 3 5 8 9
offered 9,8,5,3,2,1  -> polled 1 2 3 5 8 9

Land it A heap promises the best element now, not a sorted sequence — order exists only at the head, and only poll reveals it.

Likely follow-ups
"The test now uses poll and still fails intermittently. What next?"

Then it is almost certainly a tie-ordering assumption. If two elements have equal priority, poll() returns them in an order that depends on the heap layout, which depends on insertion history, and the test expects a specific one, usually insertion order.

The fix is either to make the comparator total, priority then a sequence number assigned at insertion, which is the standard way to get a stable priority queue, or to make the test order-insensitive for equal priorities.

equal priorities come out out of orderruns offline
// three tasks with EQUAL priority, offered A, B, C
// heap [A B C]; poll() -> A, then C moves to the root and, being equal to B, stays there
// Result: A, C, B   not insertion order

I would also check for a mutable priority: if an element's priority field changes after insertion, the heap invariant is broken and poll returns wrong elements; the rule is remove, mutate, re-add.

And I would run the test a hundred times locally to confirm it is fixed.

"How would you make a PriorityQueue stable, FIFO among equal priorities?"

Wrap each element with a monotonically increasing sequence number from an AtomicLong assigned at add time, and compare by priority first and sequence second. A record Task(int priority, long seq, Runnable job) with Comparator.comparingInt(Task::priority).thenComparingLong(Task::seq) does it.

The sequence makes the comparator total, so no two elements ever compare equal, and equal-priority tasks come out in arrival order. PriorityBlockingQueue has the same non-stable behaviour and the same fix. The cost is 8 bytes per element and one extra comparison.

This is also how ScheduledThreadPoolExecutor orders tasks with the same trigger time internally, with a sequence number on each ScheduledFutureTask.

"What are the actual complexities of PriorityQueue operations, including remove(Object)?"

offer and poll are O(log n) via sift-up and sift-down; peek is O(1). remove(Object) and contains are O(n) because the heap has no index by element, so they scan the array.

That is the trap in a scheduler that cancels tasks by removing them: with a hundred thousand pending tasks, each cancel scans the whole array.

The fix is lazy deletion, mark the task cancelled and skip it when polled, or an indexed heap that keeps a map from element to array position, which the JDK does not provide.

Building the queue from a collection is O(n) via heapify, not n log n, which is a nice detail if you construct it from a bulk load.

"When would you use a TreeSet instead of a PriorityQueue?"

When you need more than the minimum: remove an arbitrary element in O(log n), find the maximum as well as the minimum, iterate in sorted order, or do range queries.

A TreeSet gives all of that at the cost of higher constants and more memory per element, and with the requirement that the comparator be total, since a set drops duplicates.

A PriorityQueue is the right choice when the only questions are "add" and "give me the best", which is most schedulers and most k-smallest problems, because its array layout is compact and cache-friendly.

In Dijkstra-style algorithms with decrease-key, neither is ideal, and the practical trick is to add a new entry and skip stale ones on poll.

Q65 · Scenario. "A long-lived service kept per-object metadata in a HashMap<Object, Meta> and slowly leaked memory. Switching to WeakHashMap fixed it. Explain why — and why the same trick fails when the keys are String literals."

Reveal answer

The real test Whether you understand reachability well enough to predict when the weak-key trick silently does nothing.

Strong answer The original leak is structural: a HashMap holds strong references to its keys, so the cache alone keeps every keyed object alive forever — the classic failure of "attach metadata to objects I don't own" registries. The heap dump shows the map as the retainer.

WeakHashMap changes the key's reference type: each key is held through a weak reference, a reference the garbage collector ignores when deciding whether an object is still alive. The chain of events after the switch:

  1. When the last strong reference to a key elsewhere in the program disappears, the collector frees the key as if the map did not exist.
  2. The cleared reference is queued internally, and on subsequent map operations the map expunges those stale entries, so the values are released too and size shrinks on its own.

Why it fails with String literals: literals are interned — kept in the JVM's (Java Virtual Machine's) shared string pool and strongly referenced by the class that declares them for as long as that class is loaded.

A literal key is therefore never garbage collected, so its entries never clear, and the "cache" is a plain leak again. Two more caveats I would volunteer:

  • Value to key: the value must not strongly reference its own key, or the entry can never clear.
  • Timing: eviction timing follows GC (garbage collection) whim, so it is a leak-prevention tool, not a sizing policy — for real caches, Caffeine with weakKeys() gives the same semantics with actual controls.

Picture it who keeps a key alive in a HashMap, in a WeakHashMap after the sessions end, in a WeakHashMap whose value points back at its key, and with a String literal key.

The setup: the code below (moved here from the answer) shows the broken map, the two fixes and the sharp edges.

the per-object metadata map that leakedruns offline
// ❌ TRAP: BROKEN — a strong reference to every key, for ever.
private final Map<Session, Meta> metadata = new HashMap<>();
void track(Session s) { metadata.put(s, new Meta()); }
// The map keeps every Session alive. Sessions end, nothing removes them,
// the map grows for the life of the JVM. Classic listener-style leak.

// ✅ FIX 1 — WeakHashMap. Keys are held weakly, so an entry disappears once
// nothing else references the key.
private final Map<Session, Meta> metadata = new WeakHashMap<>();
//
// ❌ TRAP: TWO SHARP EDGES:
//  a) Entries vanish at GC's discretion, at an unpredictable moment. It is a
//     cache, never a source of truth.
//  b) THE VALUE MUST NOT REFERENCE THE KEY. If Meta holds the Session, the
//     value strongly reaches the key and nothing is ever collected — the
//     WeakHashMap then leaks exactly like the HashMap did.
//     If you need that, hold it as a WeakReference inside Meta.

// ✅ FIX 2 — explicit lifecycle. Preferable when there IS a clear end.
void endSession(Session s) { metadata.remove(s); }   // deterministic, testable

// NOTE WeakHashMap compares keys with equals(), not identity. For genuine
// per-instance metadata you usually want identity semantics, which means
// an IdentityHashMap, or a weak-keyed identity map from a library.

Edge (b) is the one that makes the fix useless. A value that references its own key creates a strong path from the map to the key, so the weak reference never becomes clearable and the leak is unchanged — with the added cost of everyone believing it was fixed.

Make the invisible visible: the reference chains from a GC root, one picture per case.

reference chains
HASHMAP  (strong keys)
 root: service field --> HashMap --> Node --strong--> Session s1 --> ...
 s1's last other reference is gone, but the Node still holds it              ✗ never freed, map grows

WEAKHASHMAP  (after the sessions end)
 root: service field --> WeakHashMap --> Entry --weak..> Session s1
                                           \--strong--> Meta
 no strong path reaches s1 -> GC clears the weak reference, the Entry is queued,
 the next map call expunges it and Meta becomes garbage                      ✓

WEAKHASHMAP, value points back at its key
 root: field --> WeakHashMap --> Entry --strong--> Meta --strong--> Session s1
 a strong path reaches s1 through the value                                  ✗ never cleared

WEAKHASHMAP with a literal key  map.put("ABC", meta)
 root: class constant pool / string pool --strong--> "ABC"                   ✗ never cleared

The trace: what happens to one entry across a collection.

lifecycle of one entry
t0  put(s1, meta1)           Entry(weak s1, strong meta1)           size 1
t1  session ends, no other reference to s1 remains
t2  GC: s1 only weakly reachable -> cleared and freed; Entry enqueued on the ReferenceQueue    ✓
t3  next size()/get()/put(): expungeStaleEntries() removes the Entry, meta1 is released       ✓
    with meta1 -> s1 (value points at key): at t2 s1 is still strongly reachable -> nothing happens   ✗

What you see: a map size that falls after collections, versus one that only climbs.

size log
# illustrative output
                     HashMap            WeakHashMap
t=0    live=10000    size=10000         size=10000
t=60s  live= 480     size=10000 ✗       size=  480 ✓   (after a GC and a map call)
t=120s live= 510     size=19800 ✗       size=  510 ✓

Why: the collector decides liveness from strong references only, so the map stops counting as an owner once its keys are weak, unless something else strong still reaches the key.

What you see now: after the fix and with no value-to-key reference, the retained count tracks live objects.

heap dump check
MAT: "Path to GC roots, excluding weak references" on a Session key
  alive in the app    -> a strong path exists
  only in the map     -> no path: it will be collected   ✓

Land it WeakHashMap only helps when the map is the last thing keeping keys alive — keys that are interned, pooled, or cached elsewhere make it an ordinary map with extra steps.

Likely follow-ups
"How would you confirm that the WeakHashMap entries are actually being cleared in production?"

Two signals.

  1. Size after GC: the map's size() should fall after garbage collections. Expunging happens on the next map operation, so I log size() periodically along with GC count from -Xlog:gc or the GarbageCollectorMXBean, and expect it to drop after young or mixed collections.
  2. A heap dump: in Eclipse MAT, the histogram of my key class should show only instances that are strongly reachable from elsewhere. The "Path to GC roots, excluding weak references" query on a key should find a path if it is legitimately alive or none if it is only in the map.

If keys show up as retained only through WeakHashMap$Entry, expunging has not run yet.

If they are retained through a strong path I did not expect, that path is the real leak.

"Why does a value that references its key defeat WeakHashMap, and how do you fix it?"

The map holds the key weakly but the value strongly, and the value holds the key strongly, so there is always a strong chain: map to entry to value to key.

The collector therefore never clears the weak reference, and the entry lives forever.

This is common when the value is a metadata object that keeps a back-pointer to the object it describes.

The fix is to make the value's back-reference weak too, a WeakReference<K> inside the value, or to remove the back-reference and pass the key explicitly when needed.

Guava's CacheBuilder.weakKeys() and Caffeine document exactly this caveat.

In review I look at the value type's fields whenever I see a weak-keyed map.

"When would you choose soft references instead, and why is that usually wrong?"

A SoftReference is cleared only when the JVM is under memory pressure, so a soft-valued cache theoretically uses spare heap and shrinks when needed.

In practice it is a poor cache policy.

HotSpot clears soft references based on -XX:SoftRefLRUPolicyMSPerMB, default 1000, meaning references survive roughly one second per megabyte of free heap since last use, which makes eviction timing depend on heap size and GC behaviour rather than on your workload.

The result is a cache that fills the old generation, lengthens GC pauses, and then evicts everything at once. Use an explicit size-bounded cache with a measured hit ratio instead.

Soft references are defensible only for truly optional, cheaply recomputed data where you cannot size the cache.

"Does the same interning problem affect keys other than String literals?"

Yes, any key that something else keeps alive indefinitely:

  • Boxed integers: values in the Integer cache range are shared constants, so a WeakHashMap<Integer, X> with keys under 128 never clears those entries.
  • Enum constants: held by their class.
  • Class objects: held by their class loader.
  • Static singletons and Spring beans: held by the container.

In each case the map is not the last reference, so weak keys change nothing. The general test is: if I removed this map entirely, would the key become garbage?

If the answer is no, weak keys give you an ordinary map with slower operations, and the correct fix is an explicit removal when the owning lifecycle ends.

Q66. "When would you reach for IdentityHashMap?"

Reveal answer

Strong answer IdentityHashMap compares keys with == — same object in memory — instead of equals, and hashes with System.identityHashCode instead of the key's own hashCode. That is a deliberate violation of the Map contract, so it is a specialist tool.

The canonical use is tracking visited objects while walking an object graph — serialization, deep copy, cycle detection — where two distinct objects that happen to be equals must still be treated as two nodes, and where keys may be mutated mid-traversal, which would corrupt any equals-and-hashCode-based map but leaves identity untouched.

Frameworks also use it to attach data to specific instances, such as proxy registries. A detail interviewers enjoy: internally it is not buckets and chains at all but a single flat array using linear probing — colliding entries just step to the next slot.

Land it The question it answers is "have I seen this exact object" — the moment the question is "an object like this", you are back in equals territory and this map is the wrong tool.

Likely follow-ups
"How does the linear-probing table work and what is its resize behaviour?"

The table is a single Object[] where keys sit at even indexes and values at the following odd index.

The index is computed from System.identityHashCode(key) masked to the table length; if the slot is taken by a different key, the probe steps to the next pair, wrapping around, until it finds the key or an empty slot.

There are no entry objects, so it is compact and cache-friendly. It resizes when two-thirds full, doubling the table, and because identity hash codes are effectively random, clustering is mild.

A subtlety: remove must rehash the following cluster to close the gap, otherwise probes would stop early at the hole. Its expected sizing constructor takes the expected max size, not a capacity.

"Why must an IdentityHashMap key not be a boxed primitive or a String?"

Because identity is not stable across equal values for those types. Two Integer.valueOf(1000) calls give two objects, so a lookup with a new boxed 1000 misses; and two equal strings may or may not be the same instance depending on the pool.

So a map keyed by identity with those types behaves randomly from the caller's perspective. Identity-keyed maps only make sense for objects whose identity is the thing you are tracking, such as nodes in a graph you are copying, or instances you are decorating.

If the key is a value type, you want equals and the ordinary HashMap. This is the check I do first when I see an IdentityHashMap in code review.

"Where does System.identityHashCode come from, and does it cost anything?"

It is generated lazily on first request and stored in the object header's mark word, so it is computed once per object.

The first call takes a slow path into the JVM to generate the number, which by default is from a thread-local pseudo-random generator, controlled by -XX:hashCode in older releases; it is not the address, so it does not change when the collector moves the object.

Two costs follow. Once an object has an identity hash, its header is occupied, which under the legacy locking scheme forced lock inflation when the object was later synchronised; the lightweight locking mode default since JDK 23 changed that.

And with compact object headers in JDK 25, identity hash still fits, but the design had to shrink the field.

Drill · Streams and iteration order

Whether you know what the streams pipeline actually executes, which threads run it, and which iteration orders you are ever allowed to rely on.

Q67. "What does it mean that streams are lazy, and what is operation fusion?"

Reveal answer

Strong answer Intermediate operations — filter, map, sorted — do not process anything when called; they only build a description of a pipeline. Nothing runs until a terminal operation — collect, forEach, count, findFirst — pulls elements through.

Fusion is the payoff: the stages are composed so each element flows through the whole pipeline in one pass, meaning filter().map().filter().collect() executes as a single loop with no intermediate collections materialized between stages. Laziness has visible consequences.

Short-circuiting works: findFirst after a filter stops the moment one element survives, so infinite sources with limit are fine.

And side effects buried in intermediate operations may never run — famously, list.stream().map(x -> { log(x); return x; }).count() on Java 9 and later can skip the map entirely, because the size is knowable without it.

Land it Treat a stream as a query plan, not a loop that already ran — the terminal operation is the execute button, and everything before it is only a promise.

Likely follow-ups
"Which operations break the single-pass fusion, and what do they cost?"

The stateful intermediate operations: sorted() must see every element before emitting any, so it buffers the whole stream into an array, sorts, and then continues the pipeline from the buffer; that is O(n) memory and n log n time, and it defeats short-circuiting downstream.

distinct() keeps a HashSet of seen elements, O(n) memory, though it does stream through. limit and skip are stateful but cheap in sequential streams and can be expensive in parallel ordered streams because the framework must track encounter order.

So a pipeline filter().sorted().limit(10) sorts everything to keep ten; if the source is large, a bounded priority structure or Stream.sorted on a pre-filtered small set is the fix.

"Why can count() skip the map stage, and is that dangerous?"

Since JDK 9, when the stream's size is known from the source, a SIZED spliterator such as a list, and no intermediate operation changes the size, count() returns the source size directly without traversing.

map preserves size, so the pipeline is skipped and its side effects never happen. It is only dangerous if you rely on side effects in intermediate operations, which the specification already forbids: behavioural parameters should be non-interfering and stateless.

The same optimisation lets toArray and toList presize their result.

The lesson I draw for teams is that a stream is a description of a computation and the runtime is allowed to skip work it can prove unnecessary, so logging inside map is a bug, not a debug aid.

"What is a Spliterator and why does its characteristics flag matter here?"

A Spliterator is the stream's source cursor: it can tryAdvance one element, forEachRemaining, and trySplit itself into two halves for parallel execution. Its characteristics bits, SIZED, ORDERED, DISTINCT, SORTED, IMMUTABLE, tell the pipeline what it may assume.

ArrayList's spliterator is SIZED and ORDERED and splits evenly, so it parallelises well and enables the count() shortcut. HashSet's is not ordered, so findFirst becomes as cheap as findAny. Iterator-based sources from Stream.iterate or BufferedReader.lines() are not sized and split poorly.

When a pipeline is slow in parallel, the first thing I check is the source's spliterator, because the framework can only be as clever as the flags allow.

"When does laziness cause a resource leak?"

When the stream wraps an I/O resource and no terminal operation runs, or the stream is not closed.

Files.lines(path) and Files.list(dir) open a file handle or directory stream that is released only when the stream's close() is called, which does not happen automatically at the end of a terminal operation.

So Files.lines(p).filter(...).findFirst() leaves the file open until the stream is garbage collected, and a service doing that per request runs out of file descriptors. The fix is try-with-resources around the stream: try (var lines = Files.lines(p)) { ... }.

Stream implements AutoCloseable for exactly this reason, and onClose handlers exist for custom sources.

Q68 · Scenario. "Someone stored a Stream in a field to reuse it, and the second use throws IllegalStateException: 'stream has already been operated upon or closed'. Why, and what is the fix?"

Reveal answer

Strong answer A stream is not a data structure — it is a one-shot pipeline over a cursor on the source. Running a terminal operation consumes that cursor, and the implementation flags the pipeline as linked or consumed; touching it again fails fast with exactly that exception, because silently re-reading could not be done correctly for all sources, some of which — lines of a file, a socket — cannot be rewound at all. The fixes, in order:

  1. Store the source, not the stream: keep the collection and call .stream() freshly at each use — creating a stream is cheap.
  2. When you need to hand around a reusable pipeline, hold a Supplier<Stream<T>> and call .get() per use, so each caller receives a new pipeline.
  3. When it is the results you want to reuse, materialize once with collect(Collectors.toList()) and share the list.

Prevention is a code-review rule: streams live as local variables inside one expression or method, like iterators — a Stream-typed field or getter is a smell.

Land it Think of a stream like an Iterator with better clothes — you would not store a half-consumed iterator in a field, and the same instinct applies here.

Likely follow-ups
"Why does even calling an intermediate operation twice on the same stream fail?"

Because each intermediate operation returns a new stage linked to the previous one and marks the previous stage as linkedOrConsumed. The pipeline is a linear chain, not a tree; a stage can have exactly one successor.

So var s = list.stream(); var a = s.filter(p1); var b = s.filter(p2); throws on the second call with the same "already been operated upon" message, even though no terminal operation has run. This surprises people who think of a stream as a reusable query builder.

If you need two derived pipelines from one source, create two streams from the source, or if the source is expensive, materialise it once into a list and stream that twice.

"What about a stream that must be consumed in two different ways in one pass?"

Use a collector that does both at once. Collectors.teeing(c1, c2, merger), from JDK 12, runs two collectors over the same elements in one pass and combines their results, so computing both a sum and a count, or a min and a max, needs no second traversal.

For more than two, a custom Collector with a mutable accumulator holding all the partial results is the general form, and summarizingInt is a prebuilt example returning count, sum, min, max, and average together.

The alternative of forking a stream into two consumers does not exist in the JDK, and library attempts at it need buffering, which is the same cost as collecting to a list first.

"How would you design an API that hands out streams safely?"

Return a fresh stream from a method, never from a field or a cached getter, and document that each call returns a new one: Stream<Order> orders() creating the stream from the underlying collection or query each time.

If the stream wraps a resource, document that the caller must close it, or better, take a function and manage the lifecycle inside: <R> R withOrders(Function<Stream<Order>, R> f) opens the stream, applies f, closes, and returns.

Spring Data's streaming repository methods follow the first pattern with an @Transactional requirement; JOOQ's fetchStream requires try-with-resources. The general rule is that a Stream in an API is a one-shot cursor and should be treated like an Iterator or a ResultSet.

Q69. "Explain groupingBy and partitioningBy — and what a downstream collector is."

Reveal answer

Strong answer Collectors.groupingBy(classifier) buckets elements by the classifier's result into a Map<K, List<T>>.

A downstream collector is an optional second argument that reduces each bucket instead of keeping raw lists: groupingBy(Order::region, counting()) yields counts per region, and mapping, summingLong, or a nested groupingBy compose the same way — nesting two of them is how you build a pivot table in one pass.

partitioningBy(predicate) is the two-bucket special case keyed by boolean, with one behavioral difference worth naming: the result always contains both the true and false keys, even when one side is empty, whereas groupingBy only creates keys it actually saw.

Two senior-level footnotes: plain groupingBy returns a HashMap, so the group order is meaningless — pass a map factory like groupingBy(cl, TreeMap::new, downstream) when order matters — and the concurrent variant groupingByConcurrent exists for parallel pipelines.

Land it The composability is the point — classifier picks the bucket, downstream says what a bucket becomes, and that two-slot design replaces a page of manual map-merging code.

Likely follow-ups
"How does groupingBy behave with a null classifier result?"

It throws NullPointerException with the message "element cannot be mapped to a null key", because the underlying HashMap.computeIfAbsent-style accumulation refuses null keys by design in that collector.

So groupingBy(Order::getRegion) fails the whole collect if any order has a null region, and the failure is data-dependent, which is the flaky kind. The options: map nulls to a sentinel first, groupingBy(o -> Objects.requireNonNullElse(o.getRegion(), "UNKNOWN")); filter them out; or wrap the key in Optional.

partitioningBy cannot have this problem, since a predicate returns a primitive boolean. I check this whenever the classifier reads a field that comes from an external source.

"What does the pivot table with nested groupingBy actually produce, and how do you keep it readable?"

groupingBy(Order::region, groupingBy(Order::product, summingLong(Order::amount))) produces Map<Region, Map<Product, Long>>: for each region, a map from product to total amount, computed in one pass.

Readability suffers at three levels of nesting, so I extract each downstream collector into a named variable of type Collector<Order, ?, Map<Product, Long>>, or give the nested map a record type.

For output that needs a fixed shape, such as a report, I often prefer a single groupingBy on a composite record key, record Cell(Region r, Product p), then a flat Map<Cell, Long>, because it is easier to iterate and sort.

The nested version is best when you genuinely need the per-region sub-map as a unit.

"How do you control the map and collection types produced, and why would you?"

groupingBy has a three-argument form: classifier, map factory, downstream. groupingBy(cl, TreeMap::new, toList()) gives sorted groups; groupingBy(cl, LinkedHashMap::new, toList()) preserves first-seen order; and the downstream toCollection(TreeSet::new) or toUnmodifiableList() controls the group contents.

Reasons to do it: deterministic output for reports and tests, since the default HashMap order is meaningless; immutability for results that cross a boundary; and memory, since toList() in a group creates an ArrayList per key, and counting() or summingLong avoid holding elements at all.

When the groups are large, choosing a reducing downstream over toList() is the difference between O(groups) and O(n) memory.

"How does groupingByConcurrent differ, and when is it worth it?"

groupingByConcurrent accumulates into a single shared ConcurrentHashMap from all worker threads, instead of giving each thread its own map and merging at the end.

That avoids the merge step, which for many groups is expensive, but it makes the collector CONCURRENT and UNORDERED: elements within a group arrive in no particular order, so a downstream toList() gives lists in nondeterministic order.

It is worth it for a parallel stream with many distinct keys and a cheap downstream, such as counting. For a sequential stream it is strictly slower than groupingBy. If encounter order within groups matters, stay with the ordinary collector and accept the merge cost.

Q70. "collect versus reduce — when is each the right tool, and how does reduce become accidentally quadratic?"

Reveal answer

Strong answer reduce is immutable accumulation: it repeatedly combines two values into a brand-new value, which is perfect when combining is cheap — sums, minimums, products of small immutable things.

collect is mutable accumulation: a supplier creates a container, an accumulator folds each element into it in place, and a combiner merges containers — built for results that are collections, maps, or builders.

The quadratic trap is using reduce where each combination copies everything so far: reduce("", String::concat) allocates a new, ever-longer string per element, so total work grows with the square of the input — a thousand elements is fine, a million is a minutes-long stall.

Collectors.joining() does the same job into one StringBuilder in linear time. The parallel angle matters too: collect gives every worker thread its own container and merges them at the end, so mutation is safe without locks, while reduce demands an associative, non-interfering function to parallelize correctly.

Land it If the result is a value, reduce; if the result is a container, collect — and any reduce whose combiner copies its accumulated result is an O(n²) bug waiting for production-sized input.

Likely follow-ups
"What does associative mean for reduce, and what happens if the function is not?"

Associative means grouping does not matter: f(f(a, b), c) equals f(a, f(b, c)). Addition and string concatenation are associative; subtraction and floating-point average are not.

A parallel reduce splits the input into chunks, reduces each, and combines the partial results, so the grouping is decided by the split, and a non-associative function gives different answers on different runs and different from the sequential result.

There is no runtime check; the result is just wrong. Floating-point addition is associative in theory and not in practice because of rounding, so parallel sums of doubles vary in the last bits, which has failed golden-file tests.

The identity element must also be a true identity: reduce(1, Integer::sum) in parallel adds one per chunk.

"Show me the three-argument reduce and when the combiner is actually used."

reduce(identity, accumulator, combiner) lets the accumulator change type: reduce(0, (sum, s) -> sum + s.length(), Integer::sum) folds strings into an int. The accumulator combines the running result with an element; the combiner merges two running results from different chunks.

In a sequential stream the combiner is never called, which is why a wrong combiner can pass every test until someone adds parallel(). In parallel it is called once per chunk merge.

The rules: the combiner must be compatible with the accumulator, so combiner(u, accumulator(identity, t)) equals accumulator(u, t). For anything with a mutable result, this form is a trap and collect is the right tool.

"How would you spot the quadratic reduce in a profile or in code review?"

In review, the pattern is a reduce whose function returns a new object containing everything accumulated so far: String::concat, (list, x) -> { var copy = new ArrayList<>(list); copy.add(x); return copy; }, or BigInteger multiplication of growing values.

In a profile it shows as time in System.arraycopy or the copy constructor under ReduceOps, with allocation rate proportional to n². A quick sanity check is to run with 1,000 and 10,000 elements: quadratic work gets a hundred times slower, linear gets ten times.

The fix is collect, which mutates one container in place, or a purpose-built collector such as joining or toList. I treat any reduce that builds a collection or string as a defect.

Q71 · Scenario. "One endpoint used parallelStream to fan out calls to a remote service. Under load, latencies spiked on completely unrelated endpoints too. A thread dump shows every ForkJoinPool.commonPool-worker thread blocked on socket reads. Diagnose and fix."

Reveal answer

The real test Whether you know parallel streams share one JVM-wide pool — and whether your fix is honest about the custom-pool folklore.

Strong answer The dump has already told the story; the job is to read it out:

  1. Every parallelStream in the JVM runs its work on the shared ForkJoinPool.commonPool — a work-stealing thread pool created once per JVM and sized to the number of cores minus one, so on an 8-core box there are 7 workers for the entire process.
  2. This endpoint put blocking network calls inside the stream. Sockets park the workers, and a parked worker does nothing else — so under load all 7 sit blocked on reads.
  3. The contagion follows: every other user of the common pool — other endpoints' parallel streams, plus CompletableFuture's default async methods, which run there too — queues behind the blocked workers. That is exactly why unrelated endpoints spiked, and the dump's uniform commonPool-worker stacks in socket reads confirm it.
  4. The fix: take blocking fan-out off parallel streams entirely. Use a dedicated, bounded ExecutorService with CompletableFuture.supplyAsync(task, executor) — or structured concurrency on Java 21 — sized for input/output (I/O) wait, with timeouts, and owned by this endpoint so saturation stays local.
  5. Be honest about the folk remedy: submitting the stream from inside your own ForkJoinPool so it executes there does work, but it exploits an implementation detail rather than a documented guarantee, and it still gives you no timeouts or backpressure — I would not build a request path on it. Likewise, raising java.util.concurrent.ForkJoinPool.common.parallelism just makes the shared pool bigger; it does not un-share it.

Prevention: reserve parallelStream for CPU-bound, in-memory, side-effect-free crunching of large data — never for anything that blocks inside a request handler.

Going deeper One version fact to state carefully: structured concurrency, StructuredTaskScope, is still a preview feature as of Aug 2026; it went through its fifth preview in JDK 25 under JEP 505 and needs --enable-preview, so it is not the safe default for a production request path.

The final, supported tool since JDK 21 is virtual threads, and the clean fan-out today is try (var exec = Executors.newVirtualThreadPerTaskExecutor()) { var f1 = exec.submit(...); var f2 = exec.submit(...); }, where each blocking socket read parks a cheap virtual thread rather than a platform worker, and the try-with-resources waits for completion.

Two details matter for the diagnosis in this scenario: CompletableFuture's default async methods use the common pool only when its parallelism is greater than one, otherwise they fall back to a thread-per-task executor, so a two-core container behaves differently from an eight-core one; and the common pool's size is set once at JVM start from Runtime.availableProcessors(), which in a container is the CPU quota, so a pod limited to two CPUs has a common pool of one worker.

To prove the sharing, dump threads with jcmd <pid> Thread.print and count frames whose thread name starts with ForkJoinPool.commonPool-worker; if every one is in SocketInputStream.read or NioSocketImpl, the diagnosis is confirmed before reading any code.

Land it parallelStream borrows a pool the whole JVM shares — blocking in it is not a local decision, it is a tax on every other feature in the process.

Likely follow-ups
"You moved the fan-out to a dedicated executor and unrelated endpoints are still slow. What next?"

Then something else is shared, and I go back to the thread dump rather than the code.

The candidates: the HTTP client's own connection pool, where a small maxConnectionsPerRoute makes the fan-out queue on connections and every caller of that client waits; a shared database pool such as HikariCP exhausted by the same requests; the servlet container's worker threads, where a long fan-out holds a Tomcat thread for the whole duration, so 200 slow requests consume all 200 workers; or garbage collection pressure from the fan-out's allocations.

Each has a signature in the dump or metrics: threads parked in the pool's borrow, Hikari's pending-connections gauge, Tomcat's busy-threads gauge, or GC pause time. The fix depends on which one it is.

"Why is running the stream inside your own ForkJoinPool unreliable?"

Because it works only through an implementation detail: when a parallel stream's terminal operation runs on a thread that is itself a ForkJoinWorkerThread, the tasks it forks go to that thread's pool.

Nothing in the Stream specification promises this; the Javadoc never mentions a way to choose the pool.

There is also a subtlety that the calling thread participates in the work, so the pool's parallelism is effectively one more than configured, and if the pool is saturated, the submitting task blocks. And it gives no timeouts, no cancellation, no bounded queue.

It is an acceptable trick for a batch job that must limit its own parallelism, and a poor foundation for a request path, which needs the controls an ExecutorService and CompletableFuture.orTimeout provide.

"What would you do differently in a greenfield design for this endpoint on JDK 21 or later?"

I would use virtual threads and stop thinking about pool sizing.

Each remote call runs on its own virtual thread from Executors.newVirtualThreadPerTaskExecutor(), blocks cheaply, and the fan-out is a loop of submit followed by get with a deadline, or once it is final, a StructuredTaskScope that cancels the siblings on first failure.

The remaining limits move to where they belong: a Semaphore around the remote client to cap concurrent calls per dependency, a per-call timeout on the HTTP client, and a circuit breaker.

In Spring Boot 3.2 and later, spring.threads.virtual.enabled=true puts the request handling itself on virtual threads, so a slow fan-out holds no platform thread at all.

"How would you prevent the next engineer from putting blocking calls in a parallel stream?"

Three layers. A written rule in the team's engineering guide: parallel streams are for CPU-bound, in-memory work only, with a one-line explanation of the shared pool.

A static check: an ArchUnit test or a custom Error Prone rule that fails the build when parallelStream() or parallel() appears in packages annotated as request handlers, which is coarse but effective.

And a runtime alert: a metric on the common pool's active thread count via ForkJoinPool.commonPool().getActiveThreadCount(), exported through Micrometer, alarming when it sits at the pool's parallelism for more than a few seconds, because that is the shape of the incident before it spreads.

"What does the contagion look like in metrics before someone takes a thread dump?"

Latency rises on endpoints with no code change, CPU stays low, and the correlation is with the traffic to the offending endpoint. If the service exports the common pool's active count and queued task count, they saturate first.

CompletableFuture.supplyAsync callers across the codebase see their futures complete late, so anything with a timeout starts timing out. Under Kubernetes, the low CPU with high latency often confuses autoscaling, since it scales on CPU and sees no reason to add pods.

The tell that separates this from a slow dependency is that the slow calls are in many unrelated code paths at once, which a per-endpoint latency dashboard shows as a broad, simultaneous step change.

Q72 · Scenario. "This parallel pipeline intermittently loses elements, and once a week throws ArrayIndexOutOfBoundsException. Find the bug."

Reveal answer
StatefulLambdaBug.java
List<String> results = new ArrayList<>();
orders.parallelStream()
      .map(this::enrich)
      .forEach(o -> results.add(o.summary()));   // shared mutable state

Strong answer The lambda passed to forEach mutates a shared ArrayList from many threads at once, and ArrayList is not thread-safe.

Two threads adding concurrently race on the unsynchronized size++ and the array write. That produces both symptoms you were shown:

  • Two adds land in the same slot, so one element silently vanishes — the intermittent loss.
  • When the race falls across a capacity-growing resize, an index computed against the old array flies past the new bounds and throws — the weekly exception.

This violates the stream contract by name. Behavioral parameters must be non-interfering, meaning they do not touch the source, and stateless, meaning they do not depend on or mutate shared state.

It is intermittent precisely because it depends on thread interleaving. The single-threaded unit tests will pass forever.

The fix is to let the stream own the accumulation: results = orders.parallelStream().map(this::enrich).map(Order::summary).collect(Collectors.toList()). As covered under collect versus reduce, each worker fills a private container and the framework merges them — correct, with no locks.

The tempting non-fix is wrapping with Collections.synchronizedList. That removes the crash, but serializes every add through one lock, quietly deleting the parallelism you paid for.

One more note: forEach also abandons encounter order. forEachOrdered restores it at a cost — but here the real answer is to stop side-effecting altogether.

Land it The rule that catches this whole bug class in review: a parallel stream may compute anything but must mutate nothing — results come out of collect, not out of side effects.

Likely follow-ups
"Explain the exact interleaving that produces the ArrayIndexOutOfBoundsException."

ArrayList.add is roughly: read size; if size == elementData.length, grow; write elementData[size] = e; then size = size + 1.

Two threads both read size as 9 in a 10-slot array, both see no growth is needed, both write index 9, so one element is lost and size becomes 10 or 11 depending on which increment wins.

The exception comes from a slightly different race: thread A reads size 10 with a 10-slot array and starts growing; thread B reads the old 10-slot array reference after A has bumped size to 11 but before B refreshes the array, and writes to index 11 of the 10-slot array.

That is an out-of-bounds write with no bounds check because the code trusts its own invariant. The frequency depends on how often growth coincides with concurrent adds, hence weekly.

"Would forEachOrdered fix it, and what would it cost?"

forEachOrdered guarantees that the consumer is invoked in encounter order, and the implementation serialises the consumer invocations, so the adds would no longer race and the list would be in order.

It fixes this case by accident: the consumer is still shared mutable state, and it is only safe because forEachOrdered happens to serialise it.

The cost is that the consumer runs one element at a time, which throws away the parallel benefit for that stage, while the upstream map still runs in parallel.

So it is a legitimate tool when the side effect must be ordered and cheap, such as writing lines to a file in order, but for building a result the collector is both faster and correct by design.

"How would you write a test that catches this class of bug deterministically?"

Deterministically is hard, but reliably is doable.

A test that runs the pipeline over a large input, say a million elements, in parallel, ten times, and asserts the result size equals the input size will fail on most runs with the buggy code on a multi-core CI runner.

To make it sharper, use jcstress, whose harness runs a small scenario across cores and reports every observed outcome with counts.

For static prevention, Error Prone does not catch this directly, but a review rule that any lambda inside a stream that writes to a captured variable must be justified catches nearly all instances.

And in production, a size mismatch assertion after the collect, logged with the counts, would have converted "weekly mystery" into a clear signal.

"Is a ConcurrentLinkedQueue or CopyOnWriteArrayList as the target a reasonable fix?"

Both remove the crash and the lost elements, but they are the wrong shape. CopyOnWriteArrayList copies the whole array on every add, so a million-element result costs O(n²) work.

ConcurrentLinkedQueue is lock-free and O(1) per add, so it is not terrible, but the result order is nondeterministic, the queue allocates a node per element, and you still have a side effect in a forEach, which the stream specification tells you not to do.

collect(toList()) has none of those costs: each worker fills its own ArrayList and the merge is a handful of addAll calls.

So the concurrent collections are a fix in the sense that the bug goes away; the collector is the fix in the sense that the code becomes right.

Q73. "Which iteration-order guarantees do HashMap, LinkedHashMap, and TreeMap actually make?"

Reveal answer

Strong answer HashMap guarantees nothing — the Javadoc says the order is unspecified and may change over time, and it genuinely does: the order is just the bucket-array scan order, which shifts whenever the table resizes and can differ across JDK versions.

LinkedHashMap guarantees insertion order — or least-recently-accessed-first when constructed in access-order mode — stably, regardless of resizes, because iteration follows its internal linked list rather than the buckets. TreeMap guarantees ascending key order as defined by the comparator, always.

A modern footnote worth volunteering: the immutable Set.of and Map.of collections deliberately randomize their iteration order with a per-JVM-run seed, so code that accidentally depends on their order fails fast on the next run — the JDK authors weaponized unpredictability because so many teams had fossilized on HashMap's incidental order.

Land it The discipline is to treat order as part of the type's contract: if any consumer of your output can observe order, produce it from a structure that promises one.

Likely follow-ups
"How does the Set.of randomisation actually work, and can you turn it off?"

ImmutableCollections has a static SALT32L value computed at class initialisation from the nanosecond clock, and SetN and MapN use it to choose the starting probe index and iteration direction.

So the same set built in two JVM runs iterates in different orders, but within one run the order is stable for the same contents.

As of JDK 21 there is no supported way to disable it; an internal system property, jdk.internal...., existed for the JDK's own tests but is not a contract.

The intent is explicitly to break code that depends on order early, during development, rather than in production after an upgrade. If you need order, that is the signal to use LinkedHashSet or a sorted structure.

"What does HashMap's iteration order actually depend on, precisely?"

On four things: the keys' hash codes, the current table capacity, the insertion order within a bucket, and whether a bucket is treeified.

Iteration walks the table from index 0 upward and each chain in order, so order is a function of (n-1) & spreadHash for each key.

Change any input and the order changes: add enough entries to resize and every bucket index changes; use a JDK where String.hashCode is the same but a different key type's hash changed; or run on a different -XX:AutoBoxCacheMax, which does not change Integer.hashCode, so that one is safe.

And String.hashCode is specified and stable, which is why string-keyed maps look deterministic and encourage the wrong assumption.

"Which JDK's collections have deterministic order by specification, and which only in practice?"

By specification: List implementations, LinkedHashMap and LinkedHashSet, TreeMap and TreeSet, EnumMap and EnumSet, ArrayDeque, and the SequencedCollection family from JDK 21.

In practice only: HashMap and HashSet, whose order is stable for the same keys, capacity, and JDK, and ConcurrentHashMap, whose order is similar but can shift during concurrent resizes. Deliberately non-deterministic: Set.of, Map.of, and Set.copyOf, Map.copyOf.

PriorityQueue iteration is heap order, deterministic for the same insertion sequence but not sorted. When I write output that a person or a diff tool will read, I use a specification-ordered type or sort explicitly at the boundary.

Q74 · Scenario. "A JSON-comparison test passed for months, then started failing after someone added one field — the keys now serialize in a completely different order. The object behind it is a HashMap. Explain the flakiness."

Reveal answer

Strong answer The test was never correct; it was lucky, and one insertion ended the luck. The reasoning chain:

  1. JSON (JavaScript Object Notation) objects are unordered by specification, but string comparison of serialized output makes order load-bearing anyway. The serializer walks the HashMap in bucket order, and bucket position is (n-1) & spreadHash — a function of the current capacity.
  2. Adding one field pushed the map past its resize threshold — for a default map, the 13th entry crosses 16 × 0.75. The table doubled, the mask gained a bit, and every key was re-placed at its old index or old index plus the previous capacity depending on that new bit. One innocent field therefore reshuffled the visible order of all the others, which is exactly the symptom.
  3. The same order is also hostage to JDK implementation changes, so it can rot across upgrades even with no code change.
  4. Fix on the test side, which is the real bug: compare parsed JSON trees — assertions that are order-insensitive for object keys — rather than raw strings.
  5. Where a canonical byte-for-byte output is genuinely required, for golden files or signatures, make the producer deterministic: build from a LinkedHashMap for declaration order, a TreeMap for sorted keys, or enable the serializer's ordering switch, such as Jackson's ORDER_MAP_ENTRIES_BY_KEYS.

Land it A test that encodes an unspecified order is a time bomb with a resize for a fuse — either stop observing the order or start guaranteeing it.

Likely follow-ups
"How do you compare JSON documents order-insensitively in a test?"

Parse both sides into trees and compare the trees. With Jackson, objectMapper.readTree(expected).equals(objectMapper.readTree(actual)) compares JsonNode structures, where object fields are compared as a map and array elements in order.

JSONassert's assertEquals(expected, actual, JSONCompareMode.STRICT) gives a readable diff and offers lenient modes that ignore array order or extra fields. AssertJ's JSON support and Spring's JsonContent assertions wrap the same idea.

What I avoid is normalising by sorting keys in a string, since that still breaks on whitespace, number formatting, and escaping. The test should assert the document's meaning, and a tree comparison is the cheapest faithful way to do that.

"When is byte-for-byte deterministic JSON genuinely required, and how do you get it?"

When the bytes are signed, hashed, or diffed: JWS payloads, content-addressed storage, cache keys derived from the body, golden files under version control, and reproducible builds.

The recipe: a canonicalisation step that sorts object keys, fixes number formatting, and uses a defined escaping, which the RFC 8785 JSON Canonicalization Scheme specifies; in Jackson the pieces are SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS for maps, MapperFeature.SORT_PROPERTIES_ALPHABETICALLY for beans, and a fixed PrettyPrinter or none at all.

For records and beans, property order follows declaration order by default, which is already deterministic; the HashMap was the only nondeterministic input. Then a test asserts the exact bytes, because now the bytes are part of the contract.

"Why did the test pass for months if the order was never guaranteed?"

Because every input that determined the order was fixed: the same keys with the same String.hashCode values, the same number of entries, so the same table capacity, and the same JDK. Under those conditions HashMap iteration is completely repeatable, which is what makes the trap effective.

The order changes only when an input changes, and adding the thirteenth field crossed the resize threshold. Had the field been the tenth, the test would have kept passing and the surprise would have arrived with the JDK upgrade or the fifteenth field.

That is the property I try to communicate: an unspecified order is not random, it is stable until the day it is not, which is worse for tests than randomness would be.

"What would you change in the producer so this class of bug is impossible?"

Replace the HashMap with a type whose order is part of its contract. If the fields are known, a record serialised by Jackson has declaration-order properties and the test becomes meaningful. If the structure is genuinely dynamic, a LinkedHashMap or TreeMap makes order explicit.

And I would add an ArchUnit or Error Prone rule that flags serialising a raw HashMap in the API layer, because the producer is where order should be decided, not the serialiser's settings.

The test change and the producer change are both needed: one makes the test honest, the other makes the output stable for the consumers who, as we now know, were also reading it as ordered.

Q75 · Scenario. "In a quick experiment, a HashMap<Integer, String> with keys 1 through 10 printed its keys in perfect ascending order, and a developer concluded HashMap keeps keys sorted. What is actually happening, and when does the illusion break?"

Reveal answer

The real test Whether you can explain a misleading observation from the mechanics rather than just asserting the rule.

Strong answer The order is a three-way coincidence, and each leg is checkable. Integer.hashCode() returns the value itself, so key 7 hashes to 7.

The spreading step XORs in the high 16 bits, which for small non-negative integers are all zero, so the hash passes through unchanged. And the index mask (16-1) & hash maps values 0 through 15 to bucket numbers equal to themselves.

So keys 1 through 10 occupy buckets 1 through 10, and the iterator, which scans buckets in array order, emits them ascending.

The illusion breaks the moment any leg fails: a key of 16 or more wraps around the mask, so 16 lands in bucket 0 ahead of 1; negative keys scatter once the high bits stop being zero; growth past 12 entries triggers a resize that re-deals the buckets; and any non-integer key type has hash codes with no relation to ordering at all.

The developer observed the bucket layout of identity-hashed small numbers in a small table — not a guarantee, and the fix for wanting sorted keys is TreeMap, which promises it.

Land it "It came out sorted when I tried it" is the most dangerous sentence in Java collections — an unspecified order that currently looks meaningful is still unspecified.

Likely follow-ups
"Show me the exact key that first breaks the illusion, with the arithmetic."

With the default 16-slot table, keys 0 through 15 sit in buckets equal to themselves, so 1 through 10 iterate ascending.

Key 16 has hash 16, the spread step leaves it unchanged since its high bits are zero, and the mask 15 & 16 is 0, so key 16 lands in bucket 0 and iterates before key 1.

Key 17 lands in bucket 1 behind key 1, so the order becomes 16, 1, 17, 2, 18, and so on.

Negative keys break it even sooner: −1 has hash 0xFFFFFFFF, the spread XORs in 0xFFFF and gives 0xFFFF0000, masked to 0, so −1 sits in bucket 0 alongside 16.

And the 13th insertion resizes to 32 slots, so keys up to 31 look sorted again until 32 appears.

"Would the same illusion appear with Long, Short, or String keys?"

Long.hashCode is the XOR of the two 32-bit halves, so small non-negative longs behave exactly like ints and show the same false ordering. Short and Byte hash to their value, same story.

Character hashes to its code point, so single ASCII characters iterate in alphabetical order in a large enough table, which has fooled people into thinking HashMap<Character, Integer> is sorted.

String does not: "a" hashes to 97 and "b" to 98, so single letters look sorted, but "aa" is 3104 and "b" is 98, so the order collapses with multi-character keys.

Every one of these is the same mechanism: an identity-like hash and a table larger than the key range.

"How would you demonstrate the mechanism to the developer in a way that sticks?"

A three-line experiment they run themselves. Put keys 1 through 10, print, and see the ascending order. Add key 16 and print again; it appears first.

Then create the map with new HashMap<>(4), put 1 through 10, and print: the resizes and the smaller mask scramble the order completely. Finally replace HashMap with TreeMap and watch all three cases come out sorted.

Seeing the same data in four orders in under a minute does more than any explanation of the spread function, and it gives them the two rules I want remembered: order comes from the type's contract, and HashMap's contract says nothing.

04 · JVM plumbingGenerics, Exceptions & JVM Plumbing — Q76–Q105

Everything in this section lives below the syntax: what the compiler actually emits for generics, how exceptions travel and get lost, and how the JVM — the Java Virtual Machine, the program that loads and runs your compiled bytecode — finds, links, and optimizes your classes. Interviewers use these questions to separate engineers who use Java from engineers who can explain what Java is doing to them. The scenario answers name real flags, real commands, and real failure messages, because that is what a senior is expected to reach for during an incident.

Drill · Generics under the hood

These questions test whether you know what the compiler emits for generic code — because every strange generics rule is a consequence of that one design decision.

Q76. "What actually happens to generic types when the compiler is done with them — and why did Java choose to do it that way?"

Reveal answer

The real test Can you explain erasure as a deliberate trade-off rather than reciting "generics are compile-time only".

Strong answer Generics — type parameters like the String in List<String> — go through type erasure: the compiler checks all the types, then deletes the parameters and emits bytecode that uses the bound, usually Object.

So List<String> and List<Integer> are the exact same class at runtime, and wherever your code reads an element, the compiler silently inserts a cast back to the declared type. The reason is backward compatibility.

When generics arrived in Java 5, the language had a decade of existing libraries and compiled jars.

Erasing the types meant the old List and the new List<String> are one class, so old binaries kept running unchanged and old code could call new generic libraries without recompiling.

The alternative — keeping types at runtime, as C# did — would have split the ecosystem in two.

Land it Erasure traded away runtime type information to buy a painless migration path — every generics limitation you meet is the interest on that loan.

Likely follow-ups
"If the types are erased, how does reflection know a field is a List of String?"

Because erasure removes type arguments from the bytecode instructions, not from the metadata. The compiler writes a Signature attribute into the class file for every generic field, method, and class declaration, and reflection exposes it through Field.getGenericType(), Method.getGenericReturnType(), and Class.getGenericSuperclass(), returning ParameterizedType objects.

That is how Jackson knows to deserialise a List<Customer> field into customers rather than maps, and how the super-type-token trick works: an anonymous subclass of TypeReference<List<Customer>> preserves the argument in its superclass signature.

What is gone is the type of any particular object: a List instance has no idea what it was declared to hold.

"Where exactly does the compiler insert the casts, and can they fail?"

At every point where a value of a type-variable type flows into a context that needs the concrete type: the result of list.get(0) assigned to a String gets a checkcast String instruction, and the same for method arguments and returns. javap -c shows them.

They can fail with ClassCastException only when heap pollution has occurred, meaning something bypassed the compiler's checks with a raw type, an unchecked cast, or reflection.

The cast is also elided when the target is Object, so Object o = list.get(0) has no check, which is why a polluted list can be read without error for a while and then fail later at a narrower use.

"What are the performance implications of erasure versus reification?"

Two. First, boxing: a List<Integer> stores Integer objects, because there is one List class and it holds references, so a million ints cost sixteen bytes each plus a pointer, and iteration chases pointers. C# specialises List<int> to a flat int array.

Second, the checkcast instructions, which are cheap, a type-pointer comparison, and often eliminated by the JIT when it can prove the type. Project Valhalla is the long-term answer: value classes plus, eventually, specialised generics so that List<int!> could be flat.

As of Aug 2026 that is still in development, so primitive streams and libraries such as Eclipse Collections remain the practical way to avoid boxing.

"Did erasure actually deliver the compatibility it promised, and what did it cost the ecosystem?"

It delivered: the Java 5 migration was almost painless, every pre-generics jar kept working, and the collections API was generified in place rather than duplicated the way .NET has both ArrayList and List<T>.

The costs are permanent: raw types will exist forever, generic arrays are awkward, overloading on type arguments is impossible, every framework that needs runtime types invented a workaround such as TypeReference, and primitive specialisation was ruled out for twenty years.

Kotlin and Scala live with the same erasure because they target the JVM. Most language designers today would say erasure was the right call for 2004 and that Valhalla is the bill coming due.

Q77. "Give me three concrete things you cannot write because of erasure, and explain why each one fails."

Reveal answer

Strong answer Three that come up in real code:

  • new T[10] is illegal. Arrays are reified — an array object physically remembers its element type at runtime and checks every store against it. After erasure there is no T left to stamp onto the array, so the JVM could never enforce that check. The workaround is (T[]) new Object[10] inside a class that controls all access, which is exactly what ArrayList does internally.
  • x instanceof List<String> is illegal. The runtime only sees a List; the String was erased, so the question is unanswerable. Only instanceof List<?> compiles.
  • You cannot overload process(List<String>) and process(List<Integer>). Both erase to process(List) — the same method signature — so the compiler rejects the pair as a duplicate. This is called a same-erasure clash.
three things erasure makes impossibleruns offline
// 1. NO OVERLOAD ON TYPE ARGUMENT — both erase to the same signature.
void process(List<String> a) { }
void process(List<Integer> a) { }    // "have the same erasure" -- won't compile
                                     // both become process(List)

// 2. NO `new T[]` AND NO `instanceof List<String>`.
class Box<T> {
    T[] items = new T[10];           // "generic array creation" -- won't compile
}
// Why: at runtime the array has no idea what T was, so it cannot perform the
// store check that arrays are required to do. The workaround is an Object[]
// with a cast, which is why library code is full of @SuppressWarnings.
@SuppressWarnings("unchecked")
T[] items = (T[]) new Object[10];

if (list instanceof List<String>) { }   // "illegal generic type for instanceof"
if (list instanceof List<?>) { }        // legal: the only thing knowable at runtime

// 3. NO STATIC MEMBER OF TYPE T, and no `T.class`.
class Box<T> {
    static T instance;               // won't compile: T is per-instance
    void f() { Class<T> c = T.class; }   // won't compile
}
// The workaround libraries use is a type token passed explicitly:
class Box<T> {
    private final Class<T> type;
    Box(Class<T> type) { this.type = type; }   // Jackson, Spring do exactly this
}

// AND THE CONSEQUENCE AT RUNTIME — heap pollution:
List<String> strings = new ArrayList<>();
List raw = strings;
raw.add(42);                          // unchecked warning only
String s = strings.get(0);            // ClassCastException HERE, far from the cause

The last block is why erasure matters in practice. The failure surfaces at the read, in code that is entirely correct, rather than at the write that actually broke the invariant — which is what makes an ignored unchecked warning so expensive to debug later.

Land it All three fail for one reason: the information the code pretends to use simply does not exist at runtime.

Likely follow-ups
"Why is (T[]) new Object[10] acceptable inside ArrayList but a bug if the array leaks?"

Inside the class the array is only ever accessed as Object[] and elements are cast on the way out, so the runtime type mismatch is never observed.

The moment the array escapes with its declared type T[], the caller's code has a String[] variable pointing at an Object[] object, and the compiler-inserted checkcast String[] at the return fails with ClassCastException.

That is why toArray() returns Object[] and the typed version takes a caller-supplied array or an IntFunction<T[]>, as in toArray(String[]::new): the caller creates an array of the real runtime type. Effective Java's advice is to store as Object[] and cast elements, unless the array never leaves.

"What are the erasure rules for bounded type parameters?"

A type variable erases to its leftmost bound, or Object if unbounded.

So <T extends Comparable<T>> T max(List<T>) erases to Comparable max(List), and <T extends Number & Comparable<T>> erases to Number, which is why the order of an intersection bound matters for binary compatibility: swapping the bounds changes the erased signature and breaks existing callers.

It also explains a real design choice: declaring a method with T extends Object & Comparable<T> makes it erase to Object for compatibility with a pre-generics version that returned Object, which is exactly what Collections.max does.

Reading the JDK's odd-looking bounds becomes easy once you know they are erasure-driven.

"How do catch clauses and generic exceptions interact with erasure?"

A generic class cannot extend Throwable, and you cannot catch a type variable: catch (T e) is illegal because the JVM's exception table matches on concrete class names, and after erasure T is just its bound, so the catch could not be specific. You can, however, declare throws T on a method with T extends Exception, which is how "sneaky throw" tricks and generic callback interfaces work, and the compiler checks the concrete type at each call site. Static fields of a generic class are also affected: there is one static per class, not per instantiation, so Box<String>.count and Box<Integer>.count are the same field, and a static field of type T is illegal.

"How do you write a generic method that needs the runtime class of T?"

Pass it in. The type-token pattern takes a Class<T> parameter: <T> T read(String json, Class<T> type) can then call type.cast(obj) or type.getDeclaredConstructor(), and the compiler ties the argument to the return type.

For parameterised types, where Class cannot express List<Customer>, the super-type token captures it in a subclass signature: new TypeReference<List<Customer>>() {}, read back through getGenericSuperclass(). Both are workarounds for erasure, and both are what Jackson, Gson and Spring's ParameterizedTypeReference use.

The alternative is to design so the runtime type is never needed, which is often possible by passing a factory such as Supplier<T> instead.

Q78. "What is a bridge method, and when does the compiler generate one?"

Reveal answer

The real test Whether you understand how the JVM keeps polymorphism working after the generic types are gone.

Strong answer A bridge method is a small, compiler-generated forwarding method that patches the gap erasure leaves in inheritance. Take a class Person implements Comparable<Person> with compareTo(Person p).

After erasure, the interface actually declares compareTo(Object) — but my class only wrote compareTo(Person), which is a different signature, and the JVM dispatches virtual calls by exact signature.

So the compiler quietly adds a synthetic compareTo(Object o) that casts o to Person and calls my real method. That bridge is what makes code holding a plain Comparable reference still land in my implementation.

You meet bridge methods in stack traces, in reflection results — Method.isBridge() identifies them — and as the true source of the ClassCastException when a polluted collection is compared.

Land it Bridges exist because dynamic dispatch works on erased signatures — the compiler fakes the override the JVM needs to see.

Likely follow-ups
"Show me the bridge method in javap output, and how would you recognise it in a stack trace?"

Running javap -p -c Person.class shows two compareTo methods: public int compareTo(Person), the one you wrote, and public int compareTo(java.lang.Object) flagged ACC_BRIDGE, ACC_SYNTHETIC, whose body is aload_0; aload_1; checkcast Person; invokevirtual compareTo(Person); ireturn.

In a stack trace, a bridge appears as an extra frame with the same method name at the same class, usually with no meaningful line number, directly below the frame from the interface caller such as TreeMap.put.

When a ClassCastException is thrown "at Person.compareTo(Person.java:1)" with a line number that makes no sense, that is the bridge's checkcast failing because a polluted collection handed it the wrong type.

"When else does the compiler generate bridges, besides generic interfaces?"

Covariant return types. If Object clone() is overridden as Person clone(), the JVM needs a clone() returning Object to satisfy virtual dispatch, so the compiler adds a bridge that calls the covariant version.

The same happens when a subclass narrows the return type of any superclass method, and when a class overrides a method whose parameter was a type variable in the superclass, such as Node<T>.setValue(T) overridden as setValue(String).

Also, access bridges: before JDK 11's nestmates, a private member accessed from an inner class needed a synthetic access$000 method, which is not technically a bridge but is the same species of compiler-generated glue.

"Can bridges cause bugs with reflection or annotation processing?"

Yes.

Class.getMethods() returns both the real method and the bridge, so a framework scanning for methods named compareTo sees two and may pick the bridge, which has no annotations of its own; Spring's BridgeMethodResolver exists to map a bridge back to its bridged method precisely for this reason.

Annotation lookups via method.getAnnotation on the bridge return null, so a @Transactional on a generic interface implementation can appear missing. Overload resolution by reflection with getMethod("compareTo", Object.class) finds the bridge, which works but goes through the extra frame.

The reliable technique is to check method.isBridge() and skip, or to resolve to the declaration with the most specific parameter types.

Q79. "Explain PECS, and use the signature of Collections.copy to show me why it is written the way it is."

Reveal answer

Strong answer PECS stands for Producer Extends, Consumer Super: if a parameter produces values you read, declare it ? extends T; if it consumes values you write into it, declare it ? super T. The library method is static <T> void copy(List<? super T> dest, List<? extends T> src).

The source is a producer — the method only reads T values out of it — so ? extends T lets a List<Integer> serve as a source of Number: everything you pull out is safely a Number.

The destination is a consumer — the method only writes T values into it — so ? super T lets a List<Object> accept Number elements: anything that can hold a supertype can hold a T.

The restrictions run the other way and protect you: you cannot add to a List<? extends T>, because the real element type might be a narrower sibling, and reading from a List<? super T> only gives you Object.

With plain List<T> on both sides, copying a List<Integer> into a List<Number> would not even compile — the wildcards exist purely to widen what callers may pass.

PECS, read off the signature of Collections.copyruns offline
public static <T> void copy(List<? super T> dest, List<? extends T> src)
//                               ^^^^^^^^^^ CONSUMER      ^^^^^^^^^^^^ PRODUCER

// PECS: Producer Extends, Consumer Super.
//   src PRODUCES T values for us to read   -> ? extends T
//   dest CONSUMES T values that we write   -> ? super T

// WHY EACH BOUND IS THE ONLY ONE THAT WORKS:

List<? extends Number> producer = new ArrayList<Integer>();
Number n = producer.get(0);      // READ IS SAFE: whatever it holds IS a Number
producer.add(1);                 // WRITE IS FORBIDDEN -- it might be a List<Double>,
                                 // and adding an Integer would corrupt it.
producer.add(null);              // the only legal add: null is any type

List<? super Integer> consumer = new ArrayList<Number>();
consumer.add(42);                // WRITE IS SAFE: an Integer fits any supertype list
Object o = consumer.get(0);      // READ GIVES ONLY Object -- it could be a
                                 // List<Number> or List<Object>, so nothing narrower
                                 // is guaranteed

// So copy() can read T-or-better out of src and write T-or-better into dest,
// which is exactly what a copy needs and nothing more.

// THE PRACTICAL RULE for your own APIs: if a parameter is only read from,
// use extends; if it is only written to, use super; if both, use plain T.
void addAll(Collection<? super T> target, Collection<? extends T> source)

Read the two forbidden lines together. Each wildcard gives up exactly one direction — extends gives up writing, super gives up precise reading — and choosing the wrong one shows up as a compile error that looks arbitrary until you know which direction the data flows.

Land it Wildcards buy flexibility for the caller at zero safety cost — the compiler forbids exactly the operations that could go wrong.

Likely follow-ups
"Why is Comparator<? super T> the right type for a sort method's parameter?"

Because a comparator consumes T values: the sort calls compare(t1, t2) with elements of type T and never reads a T out of the comparator. By PECS, a consumer gets ? super T.

The practical payoff is that a Comparator<Object> or a Comparator<Number> can sort a List<Integer>: anything that knows how to compare the supertype can compare the subtype.

Without the wildcard, sort(List<T>, Comparator<T>) would reject a perfectly usable comparator written for the parent type, and every caller would need an adapter. Collections.sort, List.sort, and Stream.sorted all use it, and I apply the same rule to any Consumer<? super T> or Predicate<? super T> parameter.

"Why is List<? extends Number> not the same as List<Number>, and why can you not add to it?"

Because generics are invariant: a List<Integer> is not a List<Number>, since if it were, you could add a Double to it through the Number view and corrupt the integer list. List<? extends Number> is a supertype of all of them: it means "a list of some specific but unknown subtype of Number".

Reading is safe because whatever the subtype is, it is a Number. Adding is refused because the compiler does not know which subtype: adding an Integer would be wrong if the list is really a List<Double>.

The only thing you can add is null, which belongs to every type. Arrays are covariant instead, which is why ArrayStoreException exists.

"When do you avoid wildcards even though PECS says to use them?"

In return types, almost always: returning List<? extends Shape> forces every caller to deal with the wildcard and prevents them from adding to the result, so return List<Shape> and copy if needed.

When a type parameter appears in two places that must match, use a named parameter, because a wildcard cannot be referred to twice. When the API is user-facing and the audience is unfamiliar with generics, a slightly less flexible signature can be worth the readability.

And when the type is both read from and written to, List<T> is the honest type. The rule I follow is that wildcards belong in method parameters of library-style code, and named parameters or concrete types everywhere else.

"Explain what wildcard capture is, and the error message 'capture#1 of ?'."

When the compiler sees an expression of type List<?>, it internally invents a fresh type variable, written capture#1 of ? in error messages, standing for the specific unknown type of that particular list.

Two List<?> expressions get two different captures, which is why swap(list, 0, 1) with list.set(0, list.get(1)) fails: get returns capture#1 and set expects capture#2 from a separately captured occurrence.

The capture-helper idiom routes the list through a generic method <T> void swapHelper(List<T> l, ...), where inference binds T to the single capture, so both calls agree. Understanding that message turns a confusing compiler error into a mechanical fix.

Q80 · Scenario. "A teammate suppressed an unchecked warning months ago. Today a ClassCastException fires on a line that contains no cast at all. Walk me through what happened and how you find the real bug."

Reveal answer

The real test Do you know what heap pollution is, and that the crash site and the bug site are different lines.

Strong answer This is heap pollution — a variable of a parameterized type, say List<String>, ends up pointing at a structure containing the wrong element type. The unchecked warning was the compiler saying "I can no longer guarantee this"; suppressing it removed the only fence. The exception fires later, at the invisible cast the compiler inserted where the value is read — possibly far from where the wrong value was written.

heap-pollution.java
static List<String> names = new ArrayList<>();

static void sneak(List raw) {      // raw type — compiler only warns
    raw.add(42);                   // pollution happens HERE, silently
}

public static void main(String[] args) {
    sneak(names);
    String s = names.get(0);       // ClassCastException fires HERE
}
  1. Read the throwing line and accept it is only the detection point — the compiler-inserted checkcast instruction lives there, not the bug.
  2. Trace the collection backwards to every place it is populated, then grep that path for @SuppressWarnings("unchecked"), raw types, and casts like (List<T>) someObject. Generic varargs methods are another classic entry point.
  3. To catch the write in the act, wrap the collection with Collections.checkedList(names, String.class) in a test run — it verifies every insertion, so the failure moves to the actual bug line.
  4. Fix the source of pollution, then prevent recurrence: compile with -Xlint:unchecked and treat warnings as errors, and reserve @SafeVarargs for methods that genuinely never store into the varargs array.

Land it An unchecked warning is a deferred ClassCastException with the stack trace pointing at the wrong line — suppressing one is signing that debt.

Likely follow-ups
"You found and removed the raw type and the exception still occurs. What next?"

Then there is another entry point, and I stop searching by eye. I switch the collection's creation to Collections.checkedList(new ArrayList<>(), String.class) in a test or staging build and re-run the workload; the checked wrapper throws at the offending add with the real stack trace.

The usual second sources: a deserialiser configured with a raw List.class that produces LinkedHashMap elements instead of your type, a generic varargs method that stored into its array, a cache shared between two call sites with different parameterisations, or a serialisation round-trip that reconstructed elements as a different class.

I also compile with -Xlint:unchecked,rawtypes -Werror once, which lists every remaining hole in the module.

"What is @SafeVarargs, and when is it a lie?"

A generic varargs parameter such as T... items creates an array of the erased type, so the compiler warns at the declaration and at every call, since the array could be misused.

@SafeVarargs suppresses that on the promise that the method only reads from the array and never stores into it or lets it escape.

It is a lie if the method does items[0] = something, returns items, or passes it to code that stores it as Object[] and later writes: then a caller's List<String>[] can end up containing a List<Integer>, which is heap pollution with no warning anywhere.

It is allowed only on static, final, private, or constructor methods, because an overridable method could be redefined to break the promise.

"How does Collections.checkedList work, and what does it cost in production?"

It wraps the list and, on every add, set, and addAll, calls type.isInstance(element) and throws ClassCastException with a message naming the expected and actual types if it fails; it also wraps iterators and sublists so writes through them are checked too.

Reads are unchecked and pass through. The cost is one virtual call and a type test per write, negligible for most code but visible in a tight insertion loop, and it adds a wrapper object and an extra indirection.

In production I would use it only around a collection that crosses a boundary with legacy or reflective code, where the cost of a late ClassCastException is high; otherwise it is a diagnostic to turn on when hunting.

"How would you keep the fix from regressing in a codebase with hundreds of unchecked suppressions?"

Ratchet, do not boil the ocean. First, make every @SuppressWarnings("unchecked") carry a justification comment, enforced by a Checkstyle rule, so the next reader knows what the author believed.

Second, enable -Xlint:unchecked,rawtypes and record the current warning count as a baseline; a build step fails if the count grows, which stops new pollution without requiring the old to be fixed.

Third, pick off the suppressions in code that touches collections shared across modules first, since those are where pollution travels. Error Prone's UnsafeUnchecked-style checks and IntelliJ's raw-type inspections can drive the cleanup. The goal is that unchecked casts become rare, scoped to one line, and explained.

Q81. "Raw types still compile in 2026. Why were they kept, and what exactly do you lose the moment you use one?"

Reveal answer

Strong answer A raw type is a generic class used without its type arguments — List instead of List<String>. They were kept for the same reason erasure was chosen: interoperability with pre-Java-5 code.

Millions of lines already said List, and the migration plan required old and new code to link against the same classes, so the raw spelling had to stay legal.

The cost is bigger than people expect: using a raw type does not just drop checking for the missing parameter — it switches off generic checking for every member of that instance, so even methods unrelated to the type parameter degrade to their erased forms and every call is unchecked.

That is different from List<?>, which means "unknown but still checked" — you cannot add anything but null to it, which is the safety talking. The professional rule: raw types only at the boundary with legacy code, immediately converted back into a properly parameterized reference.

Land it List<?> says "I don't know the type"; a raw List says "stop checking" — only one of those is ever acceptable in new code.

Likely follow-ups
"Give me a concrete example of a raw type switching off checking on an unrelated method."

Take class Box<T> { void put(T t); List<String> labels(); }. With a raw Box b, the erased put(Object) accepts anything, which you expect.

Less expected: b.labels() now returns raw List, not List<String>, even though labels() never mentioned T. The specification says the type of a member of a raw type is the erasure of the member's type, so every generic signature on the class degrades.

Assigning that result to List<String> l = b.labels() is an unchecked conversion, and for (String s : b.labels()) is a compile error. That is the difference from Box<?>, where labels() still returns List<String>.

"Where do raw types still sneak into modern code, and how do you spot them?"

Four habitual places: Class literals passed around as raw Class instead of Class<?>; instanceof List checks, which are fine as a test but become raw when the result is assigned; older reflection and serialisation APIs that return raw Map or List; and generic array creation workarounds like new ArrayList[10].

The compiler flag -Xlint:rawtypes reports every one, IntelliJ has a "Raw use of parameterized class" inspection, and Error Prone has no dedicated raw-type check but flags the resulting unchecked operations. The fix pattern is usually List<?> for "I only read", or a proper type parameter.

I treat the raw-type warning count as a build metric that only goes down.

"Is instanceof List<?> really any different from raw instanceof List?"

At runtime, no: both compile to the same instanceof java/util/List check, because the element type is erased.

At compile time, yes: instanceof List<?> is the reifiable form the language allows and it keeps the code out of raw-type territory, so a following pattern binding, if (o instanceof List<?> l), gives you a List<?> you can safely read from without unchecked warnings.

Writing instanceof List<String> is a compile error, since the check cannot be performed.

Pattern matching for instanceof since JDK 16 also allows instanceof List<String> l only when the compiler can prove the cast is safe from the static type, for example from a Collection<String> variable, which is a nice corner to know.

Q82. "When do you declare a named type parameter on a method, and when is a wildcard the better choice?"

Reveal answer

Strong answer The working rule: if the type appears exactly once in the signature and you never need to relate two occurrences, use a wildcard — void printAll(List<?> items) is simpler and tells the caller "any list works".

The moment the type must connect two things — two parameters that must match, or a parameter and the return type — you need a name: <T> T pickFirst(List<T> from) only works because T ties the input to the output.

There is also the classic capture idiom: the public method takes the wildcard for a clean API, and delegates to a private generic helper — <T> void swapHelper(List<T> l, int i, int j) — because inside the helper the unknown type gets a name the compiler can reason with, which is what lets you both read from and write to the same list.

Land it Wildcards for flexibility at the API surface, named parameters wherever types must agree — and the helper-method capture trick when you need both at once.

Likely follow-ups
"Why does the JDK write Collections.max with a bound like <T extends Object & Comparable<? super T>>?"

Each piece does a job. extends Object & first forces the erasure to Object, so the method's binary signature matches the pre-generics version that returned Object, which keeps old compiled callers linking. Comparable<? super T> rather than Comparable<T> lets a subclass use its parent's comparison: if Employee implements Comparable<Person>...

wait, a class Manager extends Employee where only Employee implements Comparable<Employee> can still be passed as List<Manager>, because Manager is comparable to a supertype of itself.

That wildcard is the same PECS rule applied to a bound: the comparable is a consumer of T. It reads badly, but every character is there for compatibility or flexibility.

"When is a bounded wildcard better than a bounded type parameter, and vice versa?"

If the method only needs "a list of some subtype of Number" and returns nothing tied to it, double sum(List<? extends Number> xs) is cleaner than <T extends Number> double sum(List<T> xs); the type parameter adds a name nobody uses.

If the method returns the element, <T extends Number> T first(List<T>), the name is required so the return type can be precise. If the method needs the bound for two arguments, <T extends Comparable<T>> T max(T a, T b), the name ties them.

A guideline from Effective Java: if a type parameter appears only once in a signature, replace it with a wildcard. A caller can also supply explicit type arguments to a named parameter, Util.<String>first(list), which is impossible with wildcards and occasionally rescues inference.

"Can you overload a method on wildcard types, or on List<? extends A> versus List<? super A>?"

No. Both erase to List, so two methods differing only in their wildcard bound have the same erasure and the compiler rejects them as a name clash, exactly like List<String> versus List<Integer>. That constraint shows up when designing fluent APIs: you cannot have accept(Consumer<? super T>) and accept(Function<? super T, ?>)...

those actually differ in the raw parameter type, so they are fine, but two List-taking overloads are not. The workaround is different method names, or a single method taking the more general type.

Kotlin has the same rule and offers @JvmName to rename the erased method, which is a reminder that the limit is the JVM's, not the language's.

Drill · Exceptions that survive production

This group tests exception design judgment — whether your error handling helps the on-call engineer at 2 a.m. or actively hides the truth from them.

Q83. "What is your actual rule for checked versus unchecked exceptions — and why did Spring and Hibernate abandon checked exceptions entirely?"

Reveal answer

The real test A design opinion with reasons, not a definition recital.

Strong answer A checked exception is one the compiler forces every caller to catch or declare, like IOException; an unchecked one — any subclass of RuntimeException — carries no such obligation.

My rule: checked only when the direct caller can realistically recover right there, at that call site — retry the read, fall back to a default.

Unchecked for programming errors, and for failures where the only sensible handler lives many layers up, which in a real service is almost everything. The frameworks went unchecked because checked exceptions do not compose.

SQLException in a repository forces throws clauses through every service signature above it, produces ritual catch blocks that wrap-and-rethrow without adding anything, and collides with lambdas and streams, whose functional interfaces declare no throws at all.

Spring's answer was to translate SQLException into the unchecked DataAccessException hierarchy and let one boundary handler deal with it.

Land it Default to unchecked and handle at the boundary; a checked exception is a demand on every caller, so make it only when the caller can actually pay.

Likely follow-ups
"How do you deal with a checked exception inside a lambda or stream today?"

Three options, in order of preference. Move the call out of the stream: do the I/O in a plain loop or a helper method that returns a value or a result type, and stream the results.

Wrap at the boundary: a small helper such as static <T> T unchecked(Callable<T> c) that catches the checked exception and rethrows it as an UncheckedIOException or a domain exception with the cause attached, used once per lambda.

Or use a result type: map each element to a record Result(T value, Exception error) and decide afterwards.

What I avoid is the "sneaky throw" trick that uses generics to throw a checked exception without declaring it, because it hides the exception from every reader and every tool.

"What does Spring's exception translation actually do, mechanically?"

Repository beans annotated with @Repository get a PersistenceExceptionTranslationPostProcessor-installed proxy that catches exceptions from the persistence provider and passes them through a PersistenceExceptionTranslator.

For JDBC, SQLErrorCodeSQLExceptionTranslator maps vendor error codes and SQLState values, from a bundled sql-error-codes.xml, to subclasses of DataAccessException: a unique-key violation becomes DuplicateKeyException, a lock timeout becomes CannotAcquireLockException, and so on.

The result is that service code can catch a meaningful, database-independent, unchecked type, and a driver change does not change the catch clauses. Knowing that the mapping is data-driven and by error code is what makes the "why unchecked" answer concrete.

"Is there a checked exception you would still design in today?"

Yes, a small number. InterruptedException is the canonical one: it must be handled at the point of blocking, because the correct response, restoring the interrupt flag or stopping, depends on the caller.

In application code I would use a checked exception for an outcome that is part of the method's normal contract and that every direct caller must consciously handle, such as InsufficientFundsException on a withdraw call in a small, stable API. The test is whether callers realistically branch on it right there.

Even then, modern designs often prefer a sealed result type, sealed interface WithdrawResult permits Success, InsufficientFunds, which forces handling through exhaustive switch without the composition problems of checked exceptions.

"What does throwing an unchecked exception cost compared with a checked one?"

Nothing different at runtime. Checked versus unchecked is a compile-time distinction; the JVM has one exception mechanism, and the cost is the same: constructing the Throwable fills in the stack trace, which is the expensive part, and unwinding walks frames looking for a handler.

The JIT can make throwing within a compiled, inlined region very cheap, sometimes a jump, and can even preallocate trace-less exceptions for hot implicit ones.

So the decision between checked and unchecked is purely about API design and caller obligations, never about performance, and someone who argues for unchecked on speed grounds has the wrong reason.

Q84 · Scenario. "A file-export job dies and the only logged exception is 'Stream closed' from a close() call. The on-call engineer fixed the close and it failed again, differently. What is really going on, and how does try-with-resources change the story?"

Reveal answer

The real test Suppressed exceptions — knowing that the exception you see from cleanup code is usually not the one that mattered.

Strong answer This is the classic masking pattern. In an old-style try/finally, the body throws the real exception — say the disk filled up mid-write — and then the finally block calls close(), which also throws because the stream is already broken. In Java, the exception thrown later wins: the close failure replaces the original, and the disk-full evidence is silently discarded. The on-call was debugging the symptom.

  1. Recognize the shape: an exception coming from cleanup code with no explanation of why the work itself failed is a red flag for masking.
  2. Convert the block to try-with-resources. It closes resources automatically and, crucially, keeps the body's exception as the primary one, attaching any close() failure to it via addSuppressed.
  3. Read the full stack trace: suppressed exceptions print as indented Suppressed: lines, and code can read them with getSuppressed().
  4. Mind the ordering: resources close in reverse declaration order, so declare wrapper streams after the streams they wrap.
suppressed-close.java
try (FileOutputStream out = new FileOutputStream(path);
     GZIPOutputStream gz = new GZIPOutputStream(out)) { // closes gz, then out
    gz.write(data);   // throws IOException: "No space left on device"
}
// gz.close() also throws "Stream closed" — but try-with-resources keeps
// "No space left on device" as the PRIMARY exception and prints the close
// failure underneath it as:  Suppressed: java.io.IOException: Stream closed
the exception that hid the real oneruns offline
// BROKEN — the classic pre-Java-7 shape, still written by hand today.
InputStream in = null;
try {
    in = open(path);
    process(in);                 // throws IOException: "disk full"  <- THE REAL CAUSE
} finally {
    if (in != null) in.close();  // ALSO throws: "Stream closed"     <- what you see
}
// A finally block that throws REPLACES the in-flight exception. The original
// is discarded entirely — no cause, no suppression, nothing in the log.

// FIXED — try-with-resources keeps both.
try (InputStream in = open(path)) {
    process(in);                 // primary exception
}                                // close() throws -> ADDED AS SUPPRESSED

// The log then shows:
//   java.io.IOException: disk full
//       at ...
//       Suppressed: java.io.IOException: Stream closed
//           at ...

// And you can read them explicitly if you need to:
catch (IOException e) {
    log.error("primary: {}", e.getMessage());
    for (Throwable s : e.getSuppressed()) log.error("suppressed: {}", s.getMessage());
}

// Resources close in REVERSE declaration order, so this is safe:
try (var conn = pool.get(); var stmt = conn.prepare(sql)) { ... }
// stmt closes first, then conn.

The suppressed-exception mechanism exists specifically for this failure. Before it, a cleanup error silently destroyed the diagnosis of the original error — which is why a hand-written finally that closes a resource is worth flagging in review even when it looks correct.

Land it With plain finally the last exception wins and the first one — usually the real one — vanishes; try-with-resources inverts that, which is reason enough to use it everywhere.

Likely follow-ups
"You converted to try-with-resources and now the job fails with only the suppressed exception visible. What next?"

Then the primary exception is being lost after try-with-resources did its job, usually by a wrapper. Check the catch block: catch (IOException e) { throw new ExportException(e.getMessage()); } discards the cause and its suppressed list.

Check the logging: some frameworks print only the top-level message, and structured loggers may drop suppressed entries unless configured; Throwable.printStackTrace and Logback's default converter both print Suppressed: lines, but a custom %ex{short} pattern may not.

And check for a finally with a return or a second throw. I would reproduce locally by filling a small tmpfs, then read the raw trace with e.printStackTrace() before anything else touches it.

"What is the exact order of close calls and exception handling in a multi-resource try?"

Resources are initialised in declaration order; if a later initialiser throws, the earlier resources are closed before the exception propagates. The body runs, then resources close in reverse declaration order, each in its own try, so a failure closing one does not prevent closing the others.

If the body threw, every close() exception is added to the body's exception via addSuppressed. If the body completed normally and a close() throws, that close exception becomes the primary, and later close failures are suppressed onto it.

Then any catch or finally attached to the statement runs after all closes. That last point matters: the catch sees the resources already closed.

"Why is the resource variable effectively final, and what does JDK 9's change allow?"

The resource variable must not be reassigned inside the body, because the statement closes the object the variable referred to at initialisation; reassigning would leak the original.

Before JDK 9 you had to declare the resource inside the parentheses, so wrapping an existing stream required a new variable. JDK 9 allowed try (existingStream) for any effectively final variable, which makes it natural to accept a resource as a parameter and still close it.

The trap is ownership: if a method receives a resource and closes it, the caller cannot use it afterwards, so document who closes. My rule is that the code that opens a resource is the code that writes the try-with-resources.

"How would you make the disk-full failure visible to operations before it costs an incident?"

The exception fix is necessary, but the real defence is observability and pre-checks. Log the full exception once at the boundary with its cause chain and suppressed entries, so No space left on device appears in the log search.

Emit a metric per export outcome with the exception class as a tag, so a spike in IOException alerts. Before starting a large export, check Files.getFileStore(path).getUsableSpace() against the expected size and fail fast with a clear message.

And ensure the node's disk usage is on a dashboard with an alert at 80 percent. The masking bug turned a capacity problem into a code mystery; the operational fixes make the next capacity problem boring.

Q85 · Scenario. "A batch method reports success, but its work is missing and nothing was logged. Reviewing the code, you find a return statement inside a finally block. Explain exactly what the JVM does here."

Reveal answer

Strong answer A finally block always runs on the way out of the try, whether the body completed, returned, or threw. If the finally block itself completes abruptly — a return, a throw, even a break — that abrupt completion wins and the original outcome is discarded. So here the body threw an exception, the finally executed its return, and the JVM threw the exception away entirely: no propagation, no log, method returns a success value. The diagnosis that gets you there:

  1. Notice the contradiction — side effects missing but no error anywhere — which means an exception was born and then destroyed, not never thrown.
  2. Inspect every finally (and every broad catch) on the code path for statements that complete abruptly; javac even warns "finally block does not complete normally".
  3. Fix by restricting finally to pure cleanup — or removing it in favor of try-with-resources — and returning only from the main body.
  4. Prevent it with static analysis: SpotBugs and Error Prone both flag return-from-finally as a bug pattern, so wire that into the build.

Land it finally is for cleanup only — the moment it changes control flow, it can silently overwrite both return values and exceptions.

Likely follow-ups
"What does the bytecode for try/finally look like, and why does that explain the behaviour?"

javac inlines the finally block at every exit point of the try: after the normal path, before each return, and in a catch-all handler that covers the try region, which stores the in-flight exception in a local, runs the inlined finally code, and then reloads and athrows it.

When the finally block contains a return, that inlined copy in the catch-all handler executes ireturn before ever reaching the athrow, so the stored exception is simply abandoned.

You can see this with javap -c: the exception table has an entry with catch type any, and the handler's code ends in a return instruction rather than athrow.

There is no magic in the JVM; the compiler wrote a method that returns from its exception handler.

"Besides return, what else in finally can hide an exception?"

Any abrupt completion: throw replaces the original exception with the new one, and the original is lost entirely unless you attach it; break or continue inside a loop within a finally discards it the same way as return.

A subtler case is a method call in finally that throws, such as resource.close(), which is the masking scenario from the previous question. And System.exit() in finally prevents propagation trivially.

The compiler warns only for the statically visible cases with "finally clause cannot complete normally", and only when -Xlint:finally is enabled, which it is not by default. That is why the static-analysis rule matters more than the compiler here.

"If a return in finally is a bug, why does the language allow it at all?"

Because the specification defines finally as "always runs", and the designers chose to make its semantics uniform rather than forbid particular statements; restricting control flow inside it would have added special cases to the language.

There are also rare legitimate uses: a finally that deliberately swallows an exception in cleanup code that must never fail, in a top-level thread loop for instance, though even there an explicit catch is clearer.

The practical position taken by every major style guide, and by Error Prone's Finally check, is to treat it as forbidden in application code. The interviewer wants to hear that you know it is legal, know why it is dangerous, and enforce the ban mechanically.

Q86. "When you catch a low-level exception and throw your own, what must you preserve, and what should the new exception add?"

Reveal answer

Strong answer You must pass the original exception as the cause — throw new PaymentStoreException("saving order 8812 failed", e) — so the full chain survives and prints as Caused by: sections in the stack trace.

Wrap without the cause and the on-call engineer sees only your wrapper, thrown from your own catch block; the actual failing line, the SQL error code, the constraint name — all gone. That single mistake regularly turns a five-minute incident into an hour.

The new exception should earn its existence two ways: it translates a technology-specific type into a domain-level one at an architectural boundary, so callers are not coupled to your persistence choice, and its message adds context the lower layer could not know — which order, which file, which tenant — instead of restating "database error".

And wrap at most once per boundary; re-wrapping at every layer produces a five-deep chain that says the same thing five times.

Land it Wrapping is translation plus context — the cause keeps the evidence, the message adds what only this layer knows.

Likely follow-ups
"What if the exception class you are throwing has no constructor that takes a cause?"

Use initCause: construct the exception, call e.initCause(original), and throw it. initCause may be called only once and only if the constructor did not already set a cause, otherwise it throws IllegalStateException, so it is a fallback for legacy exception types, not a pattern to prefer.

The better fix is to add the (String message, Throwable cause) constructor to your own exception types, which I consider mandatory in review. For third-party exceptions without one, wrap them in a domain exception of mine rather than trying to reuse theirs.

Every Throwable has supported causes since JDK 1.4, so there is no excuse for a modern exception class to omit the constructor.

"How do you avoid the five-deep chain that says the same thing five times?"

Wrap only at architectural boundaries, and only when the wrap adds a translation or context. Inside a layer, let exceptions propagate untouched. At the repository boundary, translate the vendor exception to a domain one once.

At the service boundary, add business context if the repository could not know it, such as the order id, or otherwise let it pass. At the API boundary, map to a response.

A reviewer's test is to read the resulting trace: if two adjacent Caused by: entries have the same message with different class names, one of them is noise.

Spring's translation does the repository step for you, so most service code should have no catch blocks at all.

"Should the wrapping exception's message include the original's message?"

Usually not, because the cause is printed in the trace anyway and copying its text means the same string appears twice and can leak vendor details into an API response.

The wrapper's message should say what this layer was doing and with which identifiers: "saving order 8812 for tenant acme".

If the wrapper will be shown to a user or serialised into a response, keep the technical cause out of the message entirely and log the full chain server-side with a correlation id.

The one exception is when the wrapper crosses a process boundary where the cause chain is lost, such as a remote call, where including a sanitised summary of the root cause in the message is the only way it survives.

"How do you handle exceptions in an asynchronous chain so the cause survives?"

In CompletableFuture, an exception thrown inside a stage is wrapped in CompletionException when observed via join or downstream stages, and in ExecutionException via get.

Both keep the original as the cause, so the rule is to unwrap once at the point where you handle it, ex instanceof CompletionException ? ex.getCause() : ex, and to add context when rethrowing.

The stack trace of the original shows the worker thread, not the submitting code, which is why adding the submitting context in the wrapper matters.

With virtual threads and structured concurrency, exceptions from child tasks propagate to the parent scope with the child's trace intact, which is a real improvement in diagnosability.

Q87 · Scenario. "Throughput of a record-parsing service collapses under load, and the profiler shows most CPU time inside Throwable.fillInStackTrace. What is happening and how do you fix it?"

Reveal answer

The real test Do you know where the cost of an exception actually lives — in construction, not in throwing or catching.

Strong answer Someone is using exceptions as ordinary control flow.

Every time a Throwable is constructed, it calls fillInStackTrace, which walks the entire call stack and records every frame — and in a framework-heavy service the stack is often more than a hundred frames deep.

Do that per record, millions of times a minute, and stack-walking becomes your workload.

The classic culprits: calling Integer.parseInt and catching NumberFormatException just to test whether a string is numeric, or a lookup API that throws a NotFoundException for a case that occurs on half of all requests.

  1. Confirm with a flame graph — async-profiler in CPU mode will show fillInStackTrace as a wide plateau — and identify the hot throw sites above it.
  2. Replace the exceptional path with a check or a value: validate before parsing, or return Optional from the lookup so absence is a value, not an event.
  3. If a hot path genuinely must signal via an exception type, make it cheap: use the protected Throwable constructor with writableStackTrace=false, or override fillInStackTrace to return this — a trace-less exception costs almost nothing to create.
  4. Know the related JVM behavior: for hot implicit exceptions like NullPointerException, the JIT eventually substitutes a preallocated, trace-less instance — the OmitStackTraceInFastThrow optimization — which is also why you sometimes see NPEs with empty stack traces in production.

Land it Throwing and catching are cheap; constructing is expensive — so exceptions belong on paths rare enough that the construction cost never shows up.

Likely follow-ups
"You replaced parseInt-with-catch by a pre-check and throughput is still down. What next?"

Then the hot throw site is elsewhere, and I go back to the flame graph rather than reasoning from memory.

I look at the callers above fillInStackTrace and group by exception class using JFR's jdk.JavaExceptionThrow event, which is disabled by default because of its volume but can be enabled for a short recording with a custom settings file.

Common second culprits: a framework converting lookups into exceptions, such as Spring's EmptyResultDataAccessException on getSingleResult, a logging call constructing a Throwable to capture the caller location, a date parser used to test formats, or an Optional.orElseThrow on a path where absence is common. Each is the same fix: make the common outcome a value.

"What does OmitStackTraceInFastThrow do exactly, and when would you turn it off?"

When the C2 compiler sees an implicit exception, a NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, ClassCastException, or ArrayStoreException, thrown repeatedly from the same compiled site, it replaces the allocation with a preallocated shared instance that has no stack trace and no message.

That makes a hot implicit exception nearly free, but it means production logs show an NPE with an empty trace and, since JDK 14's helpful messages, no message either.

You turn it off with -XX:-OmitStackTraceInFastThrow when you are diagnosing one of those and need the location; the cost is that the hot path becomes slow again until you fix it. It applies only to implicit exceptions, never to your explicit throw statements.

"How much does fillInStackTrace cost, in numbers, and what controls the depth?"

Roughly a microsecond per ten to twenty frames on a modern CPU, so a 200-frame framework stack costs on the order of ten to twenty microseconds per exception, which at fifty thousand exceptions per second is a full core.

The JVM captures at most -XX:MaxJavaStackTraceDepth frames, default 1024, which you can lower to cap the cost, at the price of truncated traces.

The trace is stored compactly as a backtrace object and only materialised into StackTraceElements when getStackTrace or printing asks, so the capture is the cost, not the storage. A trace-less exception via the four-argument constructor with writableStackTrace=false costs about as much as any small object allocation.

"Is a pre-validated parse always faster than parse-and-catch?"

Only if the exceptional case is common. If 99.9 percent of inputs are valid, a pre-check scans every string twice and the rare exception is cheap in aggregate, so parse-and-catch can win.

If half the inputs are invalid, as in this scenario, the exception path dominates and the pre-check wins by orders of magnitude. The general rule is that exceptions should be for exceptional frequencies, roughly under one percent of calls on a hot path.

When the frequency is high, use a method that returns a result without throwing: the JDK has no tryParseInt, but a small hand-written one, or Guava's Ints.tryParse, which returns null, avoids both the double scan and the exception.

Q88. "You are designing the exception hierarchy for a new service. What does a good one look like, and what mistakes do you see most often?"

Reveal answer

Strong answer A good hierarchy is small and designed for the catcher. One unchecked base type per module — say BillingException extends RuntimeException — so a boundary handler can catch everything from that domain in one clause.

Under it, only subtypes that callers will actually branch on differently; in practice the most useful axis is retryable versus permanent, not one class per failure mode.

Exceptions should carry structured fields — an error code, the order ID — not just prose, because prose cannot be switched on or turned into a metrics dimension. Every constructor must accept a cause.

The mistakes I see: thirty subtypes that every caller handles identically, which is taxonomy for its own sake; throwing bare RuntimeException so nothing can be caught selectively; and letting third-party types like SQLException or a vendor SDK exception cross your module boundary, which welds your callers to your implementation.

Land it Add a subtype only when some caller would handle it differently — otherwise it is cost without a customer.

Likely follow-ups
"How do you represent retryable versus permanent so callers can act on it?"

Either as two abstract subtypes, TransientBillingException and PermanentBillingException, which lets callers catch by category, or as a boolean or enum property on the base class, isRetryable(), which lets a generic retry policy decide without knowing the domain.

I prefer the property, because retry libraries such as Resilience4j accept a predicate on the exception, and because "retryable" is a property of the situation, not of the class: a timeout is retryable once, a constraint violation never.

A structured error code enum on the base, mapped to HTTP status and to a metric tag at the boundary, completes the design. Subtypes then exist only where a caller genuinely handles one case differently.

"Where should third-party exceptions be translated, and how do you enforce it?"

At the adapter that talks to the third party: the repository for SQL, the client wrapper for an HTTP SDK, the consumer for a message broker. That adapter catches the vendor types and throws domain types with the cause attached.

Enforcement is architectural: an ArchUnit test asserting that no class outside the adapter package imports java.sql or the vendor's exception package, and that no method in the service layer declares or throws them. Spring does this for persistence automatically.

The reason is dependency direction: if a vendor exception leaks into the service, the service now depends on the vendor, and swapping the vendor becomes a change to every catch block in the system.

"What goes in the exception versus in the log?"

The exception carries what a handler needs to decide and what a person needs to identify the case: an error code, the key identifiers, and a message that describes the failed operation.

The log, written once at the boundary, carries the full chain and the surrounding context from MDC, such as request id, user, and tenant.

Do not put secrets or personal data in exception messages, because they end up in logs, error responses, and crash reports; carry an identifier and look up details elsewhere.

And do not put large payloads in exceptions; they are retained for the life of the exception, which in a retry loop or a cached failure can be a long time.

"How does this hierarchy map to an HTTP API, and what about gRPC?"

One boundary handler, in Spring a @RestControllerAdvice, maps the base exception's error code to a status and a response body following RFC 9457 Problem Details, which Spring 6 supports natively through ProblemDetail: validation failures to 400, not found to 404, conflicts to 409, retryable infrastructure failures to 503 with a Retry-After header, everything else to 500 with the details logged and a correlation id in the body. In gRPC the same mapping goes to Status codes, with UNAVAILABLE for retryable and FAILED_PRECONDITION or INVALID_ARGUMENT for permanent, plus rich error details in metadata. The mapping is a table, and it lives in one class, which is what having a small hierarchy with codes makes possible.

Q89. "Why is catch–log–rethrow a code smell, and what is the discipline you enforce in review?"

Reveal answer

Strong answer Because when every layer catches, logs, and rethrows the same exception, one failure prints three or four times.

The on-call engineer cannot tell whether they are looking at one incident or four, error-rate metrics and alerts are inflated by the duplication, and the log is full of stack traces that all end in a rethrow rather than a resolution.

The discipline is: handle it or throw it, never both.

Exactly one place logs a given failure — the boundary that finally handles it, typically a top-level handler such as a controller advice — and every layer below either lets the exception fly untouched or wraps it once with added context and the original as cause, without logging.

The same review also catches the swallow variant, catch (Exception e) { log.error(...); } with no rethrow, which converts a failure into a silent wrong result and is strictly worse.

Land it One failure, one log line, at the layer that owns the decision — everything else is noise that costs minutes during an incident.

Likely follow-ups
"When is logging and rethrowing legitimate?"

When the exception is about to cross a boundary where the original will be lost or unreadable.

A message consumer that will hand the exception to a broker's retry mechanism, which may only record a message string; a thread pool task whose exception would otherwise vanish into a Future nobody reads; a remote call where the client will only see a status code.

In each case, log once, with the full chain and the correlation id, at the point where the detail is still available. Even then, log at the level the situation deserves and rethrow without further wrapping.

The discipline is "one log per failure", and the boundary is where that one log belongs.

"How do you catch duplicate logging mechanically?"

Two ways. Static: Error Prone and Sonar have rules for catch blocks that both log and rethrow, and a Checkstyle regex for log.error( followed by throw in the same block gets most of them.

Dynamic: count error-level log events per request id in the log pipeline; a request producing three error entries with the same exception class is a duplicate, and a saved search for that pattern finds the offending layers in minutes.

I also read the incident log for any recent outage and count how many times the same trace appears; if the answer is more than one, the review rule is not being applied, and the fix is usually deleting catch blocks rather than adding code.

"What about catch-and-swallow in a loop that must keep going, like a batch processor?"

That is a legitimate handle, not a swallow, provided the failure is recorded and counted.

The pattern is to catch per item, log once with the item's identifier, increment a failure metric, record the failure in a result object or dead-letter store, and continue; at the end, report the totals and decide whether the batch as a whole succeeded.

What makes the plain catch (Exception e) { log.error(...); } a smell is that the failure has no consequence: no metric, no result, no decision.

Also narrow the catch: catching Exception in a loop also catches programming errors like NullPointerException and hides them; catch the expected types and let the rest propagate.

Drill · Class loading & linkage

Class loading is invisible until a deploy breaks — these questions test whether you can read the JVM's linkage errors and trace them to the jar, the initializer, or the loader that caused them.

Q90. "Walk me through parent-first class loading, and explain why an app server that flips it to child-first is playing with fire."

Reveal answer

Strong answer A class loader is the JVM component that finds a class's bytes and defines the class.

There are three built-in loaders in a chain: the bootstrap loader for core classes like java.lang, the platform loader for the rest of the JDK modules, and the application loader for your classpath.

The delegation model is parent-first: before a loader looks in its own location, it asks its parent, all the way up.

That guarantees java.lang.String always comes from the bootstrap loader — one definition per name across the whole JVM — which prevents both spoofing of core classes and accidental duplicates.

App servers sometimes flip to child-first so a webapp can use its own version of a library the server also ships. The danger is class identity: to the JVM, a class is the pair (name, defining loader).

The same class file loaded by two loaders is two unrelated types, so passing one across the boundary fails with the famously confusing "com.foo.X cannot be cast to com.foo.X".

Land it Parent-first buys a single definition of every class; child-first buys version freedom and pays for it with split class identities at every boundary.

Likely follow-ups
"How do you diagnose 'X cannot be cast to X' when it happens?"

Confirm the two loaders first. In the exception handler or a debugger, evaluate a.getClass().getClassLoader() and X.class.getClassLoader() for the two sides; different loader objects prove the diagnosis.

Then find where each copy of the class file lives: -Xlog:class+load=info prints every loaded class with its source, so grep for the class name and you will see it loaded twice from two jars or two locations.

The usual causes are a library packaged both in the webapp's WEB-INF/lib and in the server's shared lib, or a plugin system that includes an API jar it should have marked as provided.

The fix is to ensure exactly one copy sits with the loader that all parties share, typically by marking the dependency provided in Maven.

"How does the module system change class loading, and does it replace parent-first?"

It does not change delegation between the built-in loaders, but it changes what each loader is allowed to load.

Since JDK 9 the platform loader and the application loader map named modules to themselves, and the boot loader serves only the modules it owns, so a class in the unnamed module cannot shadow a java.base class even by accident.

The module system also enforces readability and exports at link time, which is why an application cannot see sun.misc internals without --add-exports. Custom loaders and layers, ModuleLayer, give plugin systems a way to isolate modules with defined dependencies rather than relying on child-first tricks. Parent-first remains the default and the safe choice.

"What does a class loader actually do in defineClass, and what does the JVM verify?"

defineClass hands a byte array to the JVM, which parses the class file format, checks the magic number and version, and creates the runtime representation in Metaspace, tied to that loader. Before the class can be used, linking runs: verification, which checks that the bytecode is type-safe, stack heights are consistent, and no instruction does anything the verifier cannot prove sound; preparation, which allocates static fields with default values; and resolution of symbolic references, which happens lazily at first use. Verification is what makes it safe to load code you did not write; it is skipped for boot loader classes by default for speed, controlled by -Xverify, and the flag to disable it for other loaders was deprecated in JDK 13.

"When is child-first actually the right choice?"

When you are building a host that must run untrusted or independently versioned code with dependencies of its own, and you can guarantee that no type from those dependencies ever crosses the boundary.

Plugin systems for IDEs and build tools, Jenkins plugins, and Tomcat's per-webapp loaders are the classic cases, and each of them has a carefully managed list of packages that are always delegated to the parent: the servlet API, logging facades, anything shared.

So child-first is fine as long as it is child-first for private dependencies and parent-first for shared API types, and the mistake is treating it as a global switch. If you design such a system today, a ModuleLayer per plugin expresses that boundary explicitly.

Q91. "ClassNotFoundException versus NoClassDefFoundError — what is the actual difference, and what does each one tell you?"

Reveal answer

Strong answer ClassNotFoundException is a checked exception thrown when code explicitly asks for a class by name — Class.forName("com.foo.Driver") or loadClass — and no loader can find it.

It points at a lookup you requested, usually a configuration or classpath problem at a reflective boundary: a plugin name typo, a missing driver jar.

NoClassDefFoundError is an Error: the JVM itself needed a class — it was present when your code was compiled, since the compiled code references it — but at runtime it could not be found or could not be linked.

Critically, that includes the case where the class file is present but the class failed to initialize earlier; every later use then gets NoClassDefFoundError.

So the reading is: exception means "the lookup you asked for found nothing"; error means "the runtime's own wiring is broken", and the first step is always to check the message and cause for which of the two stories you are in.

Land it One is a failed request, the other a broken promise — and NoClassDefFoundError does not always mean the jar is missing.

Likely follow-ups
"What other linkage errors should I be able to read, and what does each mean?"

They are all subclasses of LinkageError and each names a specific mismatch. NoSuchMethodError and NoSuchFieldError: the class was found but the member you compiled against is not there, a version mismatch.

IncompatibleClassChangeError: a class changed shape, for example an interface became a class or a method became static. AbstractMethodError: a caller invokes a method the loaded implementation does not implement, typically an interface gained a method and an old implementor was not recompiled.

UnsupportedClassVersionError: the class file targets a newer JVM than the one running. VerifyError: the bytecode failed verification, usually from a bytecode-generating library. ExceptionInInitializerError: a static initialiser threw. Reading the class name tells you which layer to look at.

"Why is NoClassDefFoundError an Error rather than an exception, and should you ever catch it?"

Because it signals that the runtime's own linkage is broken, which application code cannot repair, and the designers put unrecoverable runtime failures under Error so ordinary catch (Exception e) does not swallow them.

Catching it is legitimate in exactly one shape: an optional-dependency probe, such as "is Jackson on the classpath", where the code tries to reference a class and, on NoClassDefFoundError, disables a feature. Even there, Class.forName with ClassNotFoundException is the cleaner probe.

A general handler that catches Throwable at a thread's top level may log it, but must not treat the application as healthy afterwards, because the failed class will fail again on every use.

"Show me how each of the two occurs in a Spring Boot fat jar deployment."

ClassNotFoundException typically appears when configuration names a class: a JDBC driver in spring.datasource.driver-class-name that is not on the classpath, or a @ConditionalOnClass probe, which Spring handles gracefully. NoClassDefFoundError appears when a library compiled against another library's newer version is loaded next to the older one, for example a client library needing a Jackson class that was removed, or when a static initialiser fails at startup and a bean later references the class. In a fat jar, both are usually dependency-resolution problems, and mvn dependency:tree or gradle dependencies plus -Xlog:class+load resolves which jar each class came from.

Q92 · Scenario. "Production throws NoClassDefFoundError: Could not initialize class ConfigHolder, but you can prove the class is inside the deployed jar. What happened and how do you find the real error?"

Reveal answer

The real test Reading the message precisely — "could not initialize" is a different failure from "could not find".

Strong answer The jar is fine; the class's static initializer failed. A static initializer — the static { } block plus the initializers of static fields — runs exactly once, at the class's first use.

If it throws, the JVM wraps the failure in an ExceptionInInitializerError carrying the real cause, and permanently marks the class as failed. Every subsequent use gets NoClassDefFoundError: Could not initialize class ... — with no useful cause attached.

What usually happens in production is that the first error was swallowed: it fired inside a thread pool task or during startup, someone's broad catch logged it at debug level or dropped it, and only the follow-on errors reached the alerting.

  1. Read the wording: "Could not initialize class" means initialization failure, so stop checking the classpath.
  2. Search the logs backwards in this JVM's lifetime for the first ExceptionInInitializerError mentioning ConfigHolder — its cause is the actual bug, typically a missing config file, a null environment variable, or an exception from another class it touched.
  3. Reproduce by forcing the class to initialize in isolation — Class.forName("ConfigHolder") in a test with production-like config — so the true exception surfaces directly.
  4. Fix the initializer, and then remove the fragility: keep static initializers free of I/O, config reads, and anything that can fail; do fallible work lazily in a method with explicit error handling.

Land it A class only gets one chance to initialize — after that, the JVM reports the scar, not the wound, so always hunt for the first occurrence.

Likely follow-ups
"The logs were rotated and the first ExceptionInInitializerError is gone. How do you recover the cause?"

Force the initialiser to run again where you can see it.

The failed class stays failed in this JVM, so I take a fresh JVM, ideally the same container image, and run Class.forName("com.acme.ConfigHolder") from a small main, a test, or a JShell session with the same environment variables and config mounted; the initialiser throws again and the real cause is right there.

If the failure only happens in production, I set the JVM flag -XX:+ShowCodeDetailsInExceptionMessages, which is on by default, and enable -Xlog:class+init=info and -Xlog:exceptions=info, which logs every thrown exception with its class and location, then restart one instance and read the first initialisation failure.

Since JDK 17, the later NoClassDefFoundError may also carry the original error as its cause, so check getCause() before assuming it is empty.

"What should a static initialiser be allowed to do, and where does the fallible work go?"

Constants, empty collections, cheap pure computations, and logger creation.

Anything that can fail, reads a file, touches the network, reads an environment variable that might be missing, or calls into another application class goes elsewhere: a lazy holder that initialises on first use with explicit exception handling, a constructor of an object managed by the container, or a startup step in the application's lifecycle where failure produces a clear message and a non-zero exit.

The reason is not just diagnosability; it is that class initialisation runs under a lock and cannot be retried, so a transient failure, a config service being briefly unavailable, permanently poisons the class for the JVM's lifetime.

"How do you write a test that catches a fragile static initialiser before production?"

A test that initialises the class with the production configuration source removed. Concretely, a test with an empty environment, using a library such as System Stubs or JUnit Pioneer's @ClearEnvironmentVariable, that calls Class.forName(name, true, loader) and asserts either success or a specific, informative exception.

If the class throws a bare NullPointerException inside <clinit>, the test fails and names it. For a broader net, an ArchUnit rule that static fields are not initialised by calls to methods in certain packages, such as I/O or config, catches new instances in review.

Also run the integration test suite in a fresh JVM per module, since a class poisoned by one test will fail every later test with the confusing secondary error.

Q93 · Scenario. "After adding one new dependency, production throws NoSuchMethodError for a Jackson method that plainly exists when you open the class in your IDE. Diagnose it."

Reveal answer

Strong answer NoSuchMethodError at runtime, on code that compiles, means one thing: the class that got loaded is a different version from the class you compiled against. The new dependency dragged in an older Jackson transitively, two versions are now on the classpath, and on a flat classpath the first jar found wins. Your IDE shows the newer class; the JVM loaded the older one.

  1. Establish which jar the class really came from: restart with -verbose:class (or the unified form -Xlog:class+load=info), which prints every loaded class and its source jar — or, live in a debugger, evaluate TheClass.class.getProtectionDomain().getCodeSource().
  2. Find who brings the duplicate: mvn dependency:tree -Dincludes=com.fasterxml.jackson.core shows every path pulling Jackson and the versions; in Gradle, gradle dependencyInsight --dependency jackson-databind. jdeps can additionally show which of your jars actually depend on the class in question.
  3. Fix by making the resolution deliberate: exclude the stale transitive from the new dependency, or pin the version centrally — a Maven dependencyManagement section or the official Jackson BOM (Bill of Materials, a published set of mutually compatible versions).
  4. Prevent recurrence: enable the Maven Enforcer plugin's dependencyConvergence rule (or Gradle's failing resolution strategies) so the build fails when two versions of one artifact are resolved, instead of production failing later.

Land it The compiler checked one version and the runtime loaded another — close that gap in the build, because the JVM will always trust whatever the classpath hands it first.

Likely follow-ups
"You excluded the old transitive and now a different library throws NoSuchMethodError. What next?"

That means the other library genuinely needs the old version, and you now have a real conflict rather than an accidental one.

I check both libraries' declared dependency ranges, then look for versions of each that share a compatible Jackson; Jackson's minor versions are backward compatible within 2.x, so upgrading the library that wants the old version is usually possible.

If not, the options are: upgrade or replace the older library, shade one copy under a different package with the Maven Shade plugin so both coexist, or isolate them with separate class loaders, which is heavy.

The dependencyInsight or dependency:tree -Dverbose output shows exactly who wants what, and I fix at the declaration, never by dropping jars into the runtime classpath.

"Why does the IDE show the right class while the JVM loads the wrong one?"

Because the IDE indexes every jar on the classpath and shows you the first match by its own ordering, or the one the module graph resolves, while the JVM resolves at runtime by the actual order of the classpath string or the order of jars in the fat archive.

Maven's nearest-wins rule and Gradle's highest-version rule decide which version goes into the packaged application, and that can differ from what the IDE's project model shows, especially when profiles or classifier artifacts are involved.

The only source of truth is the running JVM: -Xlog:class+load=info or jcmd <pid> VM.classloaders plus getProtectionDomain().getCodeSource().getLocation() in the process itself.

"How does the build produce two versions in the first place — is Maven not supposed to pick one?"

Maven picks one version per groupId:artifactId, but two artifacts with different coordinates can contain the same classes: a relocated artifact after a project rename, a shaded uber-jar bundling Jackson inside it, or a fork published under a different group. Those are not detected by version mediation.

Gradle has the same gap, and both leave you with two class files of the same name on the classpath.

Detection tools: the Maven Enforcer plugin's banDuplicateClasses rule from the extra-enforcer-rules project, or Gradle's checkClasspathDuplicates-style plugins, which scan all jars for identical class names and fail the build. I run that in CI for every service that has ever had this incident.

"How would you design dependency management so this never reaches production again?"

A single source of versions: a parent POM or Gradle platform with a dependencyManagement block or a BOM import for every framework family, so versions are pinned centrally and transitive upgrades are deliberate. Enforcer rules for convergence and duplicate classes as build failures.

A smoke test in CI that starts the application in the packaged form, the fat jar or the container image, not just runs unit tests on the IDE classpath, because linkage errors only surface at class-loading time in the real layout.

And dependency update automation with a review step, so upgrades happen in small increments with tests, rather than as an accidental side effect of adding an unrelated library.

Q94 · Scenario. "A service freezes during startup, forever. The thread dump shows two threads that look RUNNABLE, each sitting in a static initializer. What is this and why does it never resolve?"

Reveal answer

The real test Knowing that class initialization takes a hidden per-class lock — a deadlock most engineers have never seen coming.

Strong answer This is a class initialization deadlock. The JVM guarantees each class initializes exactly once, and it enforces that with a per-class initialization lock. If class A's static initializer touches class B, and B's touches A, then two threads starting from opposite ends each acquire one init lock and block waiting for the other — permanently.

clinit-deadlock.java
class A { static final B PEER = new B(); }  // A.<clinit> requires B initialized
class B { static final A PEER = new A(); }  // B.<clinit> requires A initialized

// Thread 1 touches A first: takes A's init lock, then waits for B's.
// Thread 2 touches B first: takes B's init lock, then waits for A's.
// Neither lock is ever released — the JVM waits forever.
  1. Take a thread dump with jstack or jcmd Thread.print. The tell is threads whose top frames are in <clinit> — the JVM's internal name for a static initializer — yet making no progress; confusingly, a thread blocked on class initialization is often reported as RUNNABLE, so do not trust the state field alone.
  2. Map the cycle: which class each stuck thread is initializing, and which class it is waiting to use. -Xlog:class+init logging helps confirm the order.
  3. Note why testing missed it: from a single thread, recursive initialization is permitted — the JVM lets the cycle proceed and you merely observe half-initialized statics — so the deadlock only appears when two threads race from opposite ends, typically at production startup.
  4. Fix by breaking the cycle: move the cross-class reference out of static initialization, for example behind the lazy holder idiom, so neither class needs the other to finish initializing.

Land it Static initializers run under an invisible lock the debugger barely shows — keep them trivial and never let two classes need each other inside <clinit>.

Likely follow-ups
"Why does jstack report the threads as RUNNABLE and not detect the deadlock?"

Because the class initialisation lock is not a Java monitor.

The JVM implements it internally with a per-class state and a native condition wait; a thread waiting for another thread's initialisation is parked in native code inside the JVM, which the thread state model reports as RUNNABLE, and the deadlock detector only examines synchronized monitors and java.util.concurrent locks.

So jstack's "Found one Java-level deadlock" message never appears. The tell is the stack itself: the top frames are in <clinit> or in a method called from it, and the state never changes across dumps.

Newer JDKs show a hint like "waiting on the Class initialization monitor for B" in the frame's annotation, which makes it explicit.

"The lazy holder fix shipped and the freeze still occurs occasionally. What next?"

Then there is a second cycle, or the holder itself participates in one.

I collect a dump at the freeze and map every thread sitting in <clinit> to the class it is initialising and the class it is waiting on, then draw the graph; with -Xlog:class+init=info on one instance, I can see the initialisation order from the moment of the freeze backwards.

Enum classes are a frequent hidden participant, because an enum constant's constructor that references a service class creates an edge. Another common one is a logging framework whose static configuration references application classes.

The systematic fix is to enumerate cross-class references in static initialisers with a static analysis rule, and to move all of them behind lazy access.

"Can this deadlock happen in a single-threaded program?"

No, because the JVM detects that the initialising thread is the current thread and lets recursive initialisation proceed; the specification calls this the "in progress by the current thread" case.

What you get instead is the half-initialised state: class A's initialiser triggers B, B's initialiser reads A's statics and sees defaults, null or zero, and continues. That is the bug from the earlier scenario, and it means single-threaded tests pass while the multi-threaded production startup deadlocks.

So the two symptoms, null statics under one thread and a freeze under two, share one root cause, and fixing either without removing the cycle leaves the other in place.

"How would you add a startup guard so this fails fast instead of hanging forever?"

Two layers. A watchdog: start a daemon thread with a deadline, say sixty seconds, that dumps all threads with ThreadMXBean.dumpAllThreads to the log and calls System.exit or Runtime.halt if the application has not reported ready, so an orchestrator restarts the pod and the dump is preserved.

And the platform's own check: Kubernetes startup probes with a failure threshold restart the container, but they do not capture the dump, which is why the in-process watchdog matters.

Additionally, an eager initialisation pass in a defined order, calling Class.forName on the known cyclic classes from the main thread before the pool starts, removes the race entirely, since one thread initialises both before any other can.

Q95 · Scenario. "A Tomcat instance grows its Metaspace with every hot redeploy until it dies with OutOfMemoryError: Metaspace. Why don't the old classes go away, and how do you prove what is pinning them?"

Reveal answer

Strong answer Metaspace is the native-memory area where the JVM stores class metadata. A class can only be unloaded when its defining class loader becomes garbage — collectible by GC (garbage collection, the JVM's automatic memory reclamation) — and a loader stays reachable while anything still references it, the classes it defined, or any instance of those classes. Each hot redeploy creates a fresh webapp class loader; the old one should die, but a single surviving reference pins the entire old generation of classes in Metaspace, and a few redeploys later you are out.

  1. Confirm the shape: jcmd <pid> VM.classloader_stats after several redeploys — multiple copies of the webapp loader, each holding thousands of classes.
  2. Take a heap dump (jcmd GC.heap_dump, or arrive prepared with -XX:+HeapDumpOnOutOfMemoryError), open it in Eclipse MAT, find the old WebappClassLoader instances, and run "Path to GC Roots, excluding weak references" — the path names the culprit.
  3. Check the usual suspects: a thread the app started and never stopped (its context class loader pins everything), a ThreadLocal on a pooled server thread holding an app class, a JDBC driver still registered in the JVM-wide DriverManager, a shutdown hook, or a static cache in a shared library retaining app objects.
  4. Fix in contextDestroyed: stop your threads, deregister drivers, clear the thread-locals — or adopt the modern posture and replace hot redeploys with full container restarts, which is why the leak class has mostly disappeared from Kubernetes-era operations.

Land it Classes die only with their loader, and one strong reference keeps a whole loader alive — that asymmetry is the entire redeploy-leak genre.

Likely follow-ups
"What are the Metaspace flags, and what does setting MaxMetaspaceSize actually do?"

-XX:MaxMetaspaceSize caps class metadata; the default is unlimited, bounded only by native memory, so without it a leak grows until the OS kills the process, and with it you get OutOfMemoryError: Metaspace earlier and more clearly. -XX:MetaspaceSize is the initial high-water mark that triggers the first GC to unload classes, and -XX:CompressedClassSpaceSize, default 1 GB, caps the separate area for compressed class pointers, which fails with a different message. The cap does not fix a leak; it makes the failure a clean exception instead of a native OOM. Monitoring with jcmd <pid> VM.metaspace or the MemoryPoolMXBean for Metaspace lets you see a sawtooth, healthy, versus a staircase, leaking, before either limit is reached.

"Why is a thread's context class loader such a common culprit?"

Every thread carries a context class loader reference, set from its creator at construction; a thread started by the webapp inherits the webapp loader.

If that thread outlives the undeploy, a timer, an executor without shutdown, a client library's background thread, it strongly references the loader, and the loader references every class it defined, and those classes reference their statics. One leaked thread pins the entire webapp's metadata.

Tomcat's memory-leak detection logs warnings like "The web application appears to have started a thread but failed to stop it" for exactly this, and it attempts to reset context loaders on pooled threads.

The fix is to own every thread you start and stop it in contextDestroyed.

"How do you read the Path to GC Roots result to find the pinning reference?"

In MAT, select the old WebappClassLoader instance and choose Path to GC Roots, excluding all phantom, weak, and soft references, so you see only strong paths. The result is a tree from the loader up to a root.

Read from the root downward: the root will be a thread, a system class, or a JNI global.

Below it, the chain shows the fields that connect, for example Thread to contextClassLoader, or a system class's static Map to a value object to your class to its loader. The first frame that belongs to code you control or configure is the fix point.

If there are several paths, fix them all; one remaining path is enough to keep the whole loader alive.

"Does this class of leak still matter in a container-per-service world?"

Much less for redeploys, because a rolling update replaces the whole JVM, but the same mechanism appears in new clothes.

Any system that loads classes dynamically over a long life has it: plugin frameworks, scripting engines that compile scripts to classes, serialisation libraries and proxy generators that define a class per type, and lambda-heavy code that spins hidden classes, though those are unloadable.

A service that generates classes per request, for example dynamic proxies for each new interface combination, shows the same staircase in Metaspace. So the diagnostic skills transfer intact: watch the Metaspace curve, dump, find the loader or the generator, and find what holds it.

Drill · Reflection, serialization & the JIT

This group tests whether you can explain the machinery frameworks and the runtime use on your behalf — proxies, annotations, object streams, and the compiler that rewrites your code while it runs.

Q96. "What does reflection actually cost, and why does setAccessible now blow up when you point it at JDK internals?"

Reveal answer

Strong answer Reflection — inspecting and invoking classes and members at runtime by name — costs in two places. Lookup is string-based and slow, so Method and Field objects must be cached, never re-fetched per call.

Invocation historically boxed arguments and hid the target from the JIT — the just-in-time compiler, which turns hot bytecode into optimized machine code — so calls could not be inlined; modern JDKs narrowed the gap by reimplementing reflection over method handles (JDK 18), but a reflective call still trails a direct one, and MethodHandle or VarHandle is the right tool for a genuinely hot path.

setAccessible(true) bypasses access checks; since the module system arrived in JDK 9 — with enforcement becoming the default in JDK 16 — it throws InaccessibleObjectException across module boundaries unless the target package is explicitly opened with --add-opens.

The reason is strong encapsulation: frameworks had grown dependent on JDK internals, which froze the JDK's ability to change its own implementation.

Land it Cache the handles, keep reflection off hot paths, and treat every --add-opens in your startup script as a debt marker naming a library that reaches where it shouldn't.

Likely follow-ups
"When is --add-opens unavoidable, and how do you keep it from spreading?"

It is unavoidable when a library you cannot replace reaches into JDK internals: older versions of Kryo and some serialisation frameworks needed java.base/java.lang, Netty's direct-buffer cleaner used to need java.base/java.nio, and some agents need jdk.internal.misc. As of Aug 2026, current releases of the major libraries have moved to supported APIs, MethodHandles, VarHandle, and the Foreign Function and Memory API, so most opens are stale. To contain them: keep every --add-opens in one launch configuration with a comment naming the library and version that needs it, add a ticket to remove it on the next upgrade, and run the test suite without the flags periodically to see which ones are still required.

"Show me how to replace a reflective call with a MethodHandle and why it is faster."

Obtain a lookup once: MethodHandle mh = MethodHandles.lookup().findVirtual(Order.class, "total", MethodType.methodType(long.class)), store it in a static final field, and invoke with long t = (long) mh.invokeExact(order).

Access checks happen once at lookup rather than per call, arguments are not boxed because invokeExact is signature-polymorphic, and a static final handle is a constant to the JIT, so the call can be inlined like a direct one.

Reflection's Method.invoke, even reimplemented over handles since JDK 18, still boxes arguments into an Object[] and checks accessibility per call. The rule: reflection to discover, handles to invoke, and a VarHandle for fields when you need atomic or volatile semantics.

"What does the JDK do about sun.misc.Unsafe, and what should a library author do?"

JEP 471, delivered in JDK 23, deprecated the memory-access methods of sun.misc.Unsafe for removal, and JEP 498 in JDK 24 made the JVM print a warning on their first use, controlled by --sun-misc-unsafe-memory-access=warn|allow|deny, with deny planned to become the default in a later release and the methods removed after that.

As of Aug 2026 the default is still a warning, so a library using them works but announces itself in the logs.

A library author should migrate to VarHandle for field and array access and to the Foreign Function and Memory API for off-heap memory, both final and supported. An application team should treat the warning as a dependency-upgrade task.

"How much slower is reflection really, in numbers?"

Order of magnitude, not orders.

A direct virtual call that the JIT inlines is under a nanosecond; a cached Method.invoke on a modern JDK is roughly five to twenty nanoseconds including argument boxing, and an uncached lookup by name is a microsecond or more because it walks the class's method table and copies Method objects.

A MethodHandle in a static final field is within a nanosecond of the direct call.

So reflection is fine for anything done once per request or less, and a problem only in serialisation loops and property access in tight paths, which is why Jackson and Hibernate generate or cache accessors.

The real cost is usually not speed but the loss of inlining and escape analysis around the call.

Q97. "How does @Transactional actually intercept your method call? What object is really sitting in the injected field?"

Reveal answer

The real test Whether you know the annotation is inert and the interception is an object wrapped around yours.

Strong answer The annotation itself does nothing — it is metadata. Spring's AOP (aspect-oriented programming — adding behavior around methods without editing them) builds a dynamic proxy: a class generated at runtime that wraps your bean.

What gets injected into every other bean is the proxy, not your object. A call then flows proxy first — open or join a transaction — then into your real method, then back through the proxy to commit or roll back. Two generation mechanisms exist.

A JDK dynamic proxy (java.lang.reflect.Proxy) implements your interfaces and routes every call to an InvocationHandler, so it requires an interface.

CGLIB instead generates a subclass of your concrete class, overriding its methods — no interface needed, which is why Spring Boot defaults to it — but it cannot override final methods or subclass final classes, and those silently escape interception.

You can see the machinery: getClass() on an injected bean prints a name containing $Proxy or $$SpringCGLIB.

the object actually sitting in your fieldruns offline
@Service
public class OrderService {
    @Transactional
    public void confirm(String id) { ... }
}

@RestController
class Controller {
    private final OrderService service;   // NOT an OrderService you wrote

    void debug() {
        System.out.println(service.getClass());
        // class com.acme.OrderService$$SpringCGLIB$$0
        //
        // Spring generated a SUBCLASS at runtime that overrides confirm(),
        // wraps it in the transaction interceptor, and delegates to your
        // instance. That subclass is what was injected.
    }
}

// Roughly what the generated override does:
public void confirm(String id) {
    TransactionInfo info = txInterceptor.createTransactionIfNecessary(...);
    try {
        super.confirm(id);                       // YOUR code
        txInterceptor.commitTransactionAfterReturning(info);
    } catch (RuntimeException | Error e) {
        txInterceptor.completeTransactionAfterThrowing(info, e);   // rollback
        throw e;
    }
}

// AND THE CONSEQUENCE: overriding is the mechanism, so anything that cannot
// be overridden cannot be advised — silently, with no warning:
@Transactional private void a() { }    // not proxied
@Transactional final   void b() { }    // not proxied
@Transactional static  void c() { }    // not proxied

Once you can name the generated subclass, every proxy bug becomes predictable. The same mechanism underlies @Async, @Cacheable, @Retryable and @PreAuthorize, and all of them fail the same silent way on a private, final or static method.

Land it It is decoration at runtime, not magic — which is exactly why everything breaks the moment a call path avoids the wrapper.

Likely follow-ups
"What exactly does a CGLIB subclass proxy do with your constructor and fields?"

The generated subclass is instantiated without running your constructor, using Objenesis, so it is an empty shell: its inherited fields are null or zero.

It holds a reference to your real, fully constructed bean and overrides each non-final public and protected method to run the interceptor chain and then delegate to the target.

That is why reading a field on an injected reference inside another class gives null, why this inside your method is the target and not the proxy, and why a final method or a private method is invisible to interception.

It also means a proxied class needs a visible no-argument constructor or Objenesis support, and that getClass() on the proxy is the generated subclass, which breaks naive getClass() == Other.class checks and enum-style singletons.

"How does the transaction interceptor decide commit versus rollback?"

TransactionInterceptor wraps the call in a TransactionAspectSupport.invokeWithinTransaction: it asks the PlatformTransactionManager for a transaction according to the propagation setting, invokes the target, and on normal return commits.

If the target throws, it consults the rule set: by default any RuntimeException or Error triggers rollback and any checked exception commits, which surprises everyone the first time. rollbackFor and noRollbackFor change the rules.

A subtle case is an inner transactional method that throws a RuntimeException which an outer method catches: the inner interceptor has already marked the transaction rollback-only, so the outer commit fails with UnexpectedRollbackException.

The commit or rollback happens in the proxy, so nothing in your code sees it.

"How would you verify at runtime that a bean is proxied and that the advice actually applies?"

Three checks. AopUtils.isAopProxy(bean) and AopUtils.isCglibProxy(bean) tell you whether the injected object is a proxy. TransactionSynchronizationManager.isActualTransactionActive() called inside the method tells you whether a transaction is live at that point, which I log at debug level during diagnosis.

And the Spring Boot actuator's beans endpoint or a debugger breakpoint in TransactionInterceptor.invoke shows whether the interceptor is hit for a given call.

If the method is public, the bean is a proxy, and the interceptor is not hit, the call is internal or the annotation is on an interface that CGLIB does not see.

"When would you choose AspectJ weaving over proxies?"

When the proxy model's limits are in the way: self-invocation must be intercepted, private or final methods need advice, or you want to advise objects the container did not create, such as JPA entities or objects returned from a factory.

AspectJ compile-time or load-time weaving modifies the bytecode of the class itself, so the advice runs on every call regardless of path, and there is no proxy object.

The costs are a build step or a Java agent, longer compile times, harder debugging because the code you read is not the code that runs, and coupling to a second toolchain.

Most services never need it, and I would prefer restructuring the self-invocation into a separate bean before adopting weaving.

Q98 · Scenario. "A @Transactional method runs in a transaction when another bean calls it, but when a method in the same class calls it, no transaction exists. Explain this at the JVM level."

Reveal answer

Strong answer This is self-invocation, and the JVM-level explanation is that the transaction logic lives in the proxy, and the proxy is only on the path when the call comes from outside.

External callers were injected the proxy, so their calls pass through the interceptor before reaching your object.

But inside the class, this.saveOrder() is an ordinary virtual call on the raw target object — this is your real instance, not the wrapper, because proxying works by composition, wrapping your object, not by rewriting your class's bytecode.

The JVM dispatches the internal call directly to your method, the interceptor never runs, and the annotation — which is inert metadata — does nothing on its own. To confirm it during debugging:

  1. Log getClass().getName() on the injected reference held by an external caller — it shows a generated name like OrderService$$SpringCGLIB$$0 — then log this.getClass() inside the method during the internal call, which shows the plain class.
  2. Set a breakpoint in the transaction interceptor: it fires for the external call and never for the internal one.

The remedies — routing the internal call back through the proxy or switching to bytecode weaving — are Spring configuration territory, covered in the tuning module; the point here is why the JVM cannot do otherwise.

self-invocation, and the three ways outruns offline
@Service
public class OrderService {

    public void processAll(List<String> ids) {
        for (String id : ids) {
            confirm(id);          // this.confirm(id) -- NEVER reaches the proxy.
        }                         // No transaction. Each iteration autocommits.
    }

    @Transactional
    public void confirm(String id) { ... }
}
// Called from another bean: proxy -> interceptor -> transaction. Works.
// Called from processAll:    plain Java call on `this`. Annotation ignored.

// FIX 1 — move the annotated method to another bean. Cleanest, and it usually
// improves the design because the transactional boundary becomes explicit.
@Service class OrderConfirmer { @Transactional public void confirm(String id) {...} }

// FIX 2 — self-injection. Works, and is a smell worth commenting.
@Service
public class OrderService {
    @Lazy private final OrderService self;      // @Lazy breaks the cycle
    public void processAll(List<String> ids) {
        ids.forEach(self::confirm);             // goes through the proxy
    }
}

// FIX 3 — do it programmatically, no proxy involved at all.
private final TransactionTemplate tx;
public void processAll(List<String> ids) {
    ids.forEach(id -> tx.executeWithoutResult(s -> confirm(id)));
}

// DIAGNOSTIC: turn this on and look for "Getting transaction for".
// If the line is absent, the proxy was never involved.
//   logging.level.org.springframework.transaction.interceptor=TRACE

The diagnostic line is what makes this fast to confirm. Rather than reasoning about whether the proxy applied, turn on transaction tracing and look for the entry — its absence is proof, and it takes thirty seconds.

Land it A wrapper can only intercept calls that arrive through it — this is not the proxy, and no annotation can change what a plain virtual call does.

Likely follow-ups
"What are the concrete fixes, and which do you prefer?"

In order of preference: move the transactional method into its own bean and inject it, so the call goes through a proxy naturally; that is a design improvement anyway, since it usually separates orchestration from a unit of work.

Second, inject the bean into itself with @Lazy or via ObjectProvider<Self> and call through that reference; it works but reads oddly. Third, AopContext.currentProxy() with exposeProxy = true, which ties the code to Spring AOP explicitly. Fourth, AspectJ weaving.

And the option people forget: make the outer method transactional instead, if the outer scope is the correct boundary. I avoid the self-injection tricks in review because they preserve a structure that is already telling you the class has two responsibilities.

"Why do private and package-private @Transactional methods do nothing, and what does Spring 6 change?"

A CGLIB subclass can only override methods it can see and that are not final: public and protected ones, and package-private ones if the generated class is in the same package, which it is.

A private method cannot be overridden, so no interception is possible, and Spring's default configuration ignores the annotation on it. Before Spring 6.0, only public methods were advised by default; since 6.0, protected and package-private methods on CGLIB proxies are also honoured.

That changed behaviour on upgrade for some teams: a package-private @Transactional method that was silently ignored under Spring 5 started opening transactions under Spring 6. Private methods remain unadvised in both, and JDK interface proxies still cover only interface methods.

"How would you write a test that fails on self-invocation?"

An integration test with a real transaction manager and a database, in-memory or Testcontainers, that calls the outer method and then asserts transactional behaviour that only holds if the transaction existed: force a failure at the end of the inner method and assert that the earlier writes were rolled back, or call TransactionSynchronizationManager.isActualTransactionActive() inside the inner method through a test hook and assert true. A unit test with mocks cannot catch this, because the proxy is not there. I also add an ArchUnit rule that a class does not call its own @Transactional methods, which can be approximated by checking for methods annotated with it that are called from the same class, and I keep the integration test as the source of truth.

"Does the same self-invocation problem affect @Cacheable, @Async and @Retryable?"

Yes, identically, because they are all implemented as proxy-based interceptors.

An internal call to a @Cacheable method bypasses the cache; to an @Async method runs synchronously on the caller's thread; to a @Retryable method never retries; and to a @PreAuthorize method skips the security check, which is the most dangerous case.

The diagnostic and the fixes are the same as for @Transactional. When I explain the proxy model to a team, I present all of them together, because people who learn it only as "the transaction thing" rediscover the same bug with @Async six months later.

Q99. "Explain the three annotation retention levels, and why a Spring or Jackson annotation must be RUNTIME."

Reveal answer

Strong answer Retention says how long an annotation survives. SOURCE means the compiler sees it and then discards it — it never reaches the class file; @Override and Lombok's annotations live here, doing their work at compile time.

CLASS, the default, means the annotation is written into the class file but not loaded into the runtime — only bytecode-processing tools that read class files directly can see it.

RUNTIME means it is in the class file and the JVM keeps it available to reflection, so method.getAnnotation(Transactional.class) returns it.

Frameworks like Spring and Jackson decide behavior at runtime by reflecting over your classes, so their annotations must be RUNTIME — with anything less, getAnnotation returns null and the framework simply behaves as if the annotation were absent.

That failure mode is the dangerous part: no error, no warning, the feature just silently does not happen — which is exactly what you get from a hand-written annotation whose author forgot @Retention(RetentionPolicy.RUNTIME).

Land it Wrong retention fails silently — the first thing to check when a custom annotation "does nothing" is whether reflection can see it at all.

Likely follow-ups
"What about annotation inheritance — does a RUNTIME annotation on a superclass or interface show up on the subclass?"

Only for class-level annotations marked @Inherited, and only through superclasses, never through interfaces. Method annotations are never inherited by an overriding method through plain reflection: subclassMethod.getAnnotation(Transactional.class) is null if only the superclass method was annotated.

Frameworks paper over this with their own lookup, Spring's AnnotatedElementUtils.findMergedAnnotation searches superclasses, interfaces, and meta-annotations, which is why @Transactional on an interface method works in Spring but is documented as fragile with CGLIB proxies.

The practical rule is to annotate the concrete class and method, and to know that what your framework sees depends on its lookup, not on Method.getAnnotation.

"What is a meta-annotation, and how does Spring use retention there?"

A meta-annotation is an annotation placed on another annotation type. Spring's @RestController is meta-annotated with @Controller and @ResponseBody, and @SpringBootApplication bundles several.

For that composition to work at runtime, every annotation in the chain must have RUNTIME retention, because Spring's MergedAnnotations walks the annotation types reflectively to find the ones it cares about.

A custom composed annotation with the default CLASS retention silently disappears, and the bean is simply not a controller, with no error.

When I create a composed annotation I copy the trio: @Retention(RUNTIME), @Target, and @Documented, and I write a test that asserts the framework finds it.

"How do annotation processors and Lombok fit into this picture?"

Annotation processors run inside javac and see annotations of any retention, including SOURCE, because they operate on the source model before class files exist.

That is how Lombok, MapStruct, Dagger, and Immutables work: they generate or modify code at compile time and their annotations never need to survive into the class file.

Lombok is special in that it modifies the abstract syntax tree of the class being compiled through internal compiler APIs, which is why it needs specific support in each JDK release, whereas standard processors only generate new files.

So SOURCE retention is not a lesser option; it is the correct one for anything resolved at compile time, and it keeps the class file smaller.

Q100 · Scenario. "After a rolling deploy, half your nodes throw java.io.InvalidClassException: local class incompatible: stream classdesc serialVersionUID = -6842, local class serialVersionUID = 1749. What happened and what do you do right now?"

Reveal answer

Strong answer Java serialization — the built-in mechanism that turns objects into byte streams via ObjectOutputStream — stamps every serialized class with a serialVersionUID, a version number. If you never declared one, the JVM computes it by hashing the class's structure, including its methods — so even adding a harmless method changes the computed value. During the rolling deploy, old nodes wrote objects (HTTP sessions in Redis, cache entries, queue messages) stamped with the old UID; new nodes compute the new one, and deserialization refuses the mismatch.

  1. Identify which serialized store is crossing versions — session replication, a shared cache, an in-flight queue — from the stack trace above the exception.
  2. Stop the bleeding: declare private static final long serialVersionUID = -6842L; — explicitly set to the old stream's value — and redeploy. Deserialization then proceeds, and structurally compatible changes are tolerated: fields added since just get default values, removed fields are ignored.
  3. If the class change was structurally incompatible, no UID trick saves you — drain or invalidate the store instead, and accept the logged-out sessions or cold cache.
  4. Prevent recurrence: every Serializable class declares its UID explicitly from day one, so only deliberate breaking changes alter it — and treat this incident as the argument for moving anything that outlives a deploy off Java serialization onto an explicit format like JSON or Protocol Buffers.

Land it An undeclared serialVersionUID makes every innocent edit a wire-format break — declare it, or better, stop letting Java serialization cross deploy boundaries at all.

Likely follow-ups
"You set the old serialVersionUID and deserialisation now throws a different error. What next?"

Then the change was structurally incompatible, and the UID was only the first gate. The stream format tolerates added or removed fields, but not a changed field type, a changed class hierarchy, a class becoming or ceasing to be Serializable, or a switch to Externalizable.

The new error's message says which: incompatible types for field is a type change, ClassCastException during read is a hierarchy change.

At that point the choice is to restore the old shape temporarily, deploy, drain the store, then make the change; or to accept the loss and invalidate sessions and cache entries.

What I would not do is keep patching the class blindly during a rolling deploy with half the fleet on each version.

"How do you make a rolling deploy safe when serialised state crosses versions?"

Treat the serialised form as a versioned protocol.

Rules: never change a class's serialised shape and its UID in the same deploy that still has old readers; make additive changes only, with new fields having sensible defaults; read-compatibility for one version back is a release checklist item; and prefer a format designed for evolution, JSON with a lenient mapper or Protocol Buffers, for anything stored in Redis or a queue.

For sessions specifically, most teams move to a stateless token or a JSON session serialiser in Spring Session. And a canary: deploy one new node, let it read state written by old nodes, and check for InvalidClassException in its logs before continuing the rollout.

"How is the default serialVersionUID computed, and why does that make it fragile?"

The JVM computes a SHA-1 hash over the class name, modifiers, interfaces, fields with their types and modifiers, and the signatures of constructors and non-private methods, then folds it to a long.

Because methods are included, adding a public helper method, renaming a method, or even changing a method's modifier changes the UID with no change to the data at all.

Compiler differences can also matter: synthetic members such as bridge methods or lambda-generated methods contribute, so the same source compiled by different javac versions can produce different UIDs.

That is why the Javadoc for Serializable explicitly recommends declaring it, and why serialver exists as a tool to print the computed value when you need to freeze it.

"What would you do in a greenfield design so this incident cannot happen?"

Never let Java serialisation cross a process or deploy boundary. In-process, use it nowhere; for anything stored or transmitted, use an explicit schema: Protocol Buffers or Avro for queues and caches with schema evolution rules, JSON with a tolerant reader for sessions and configuration.

Mark classes that must never be serialised with a writeObject that throws, or better, keep them non-Serializable and add a serialisation filter with -Djdk.serialFilter to reject unexpected classes, which also closes the deserialisation attack surface.

Put a format version in every stored record and test that the current code reads the previous version's fixtures in CI. Then a rolling deploy is a compatibility question the tests already answered.

Q101. "Why is Java's native serialization discouraged even by the people who built Java, and what do you use instead?"

Reveal answer

Strong answer Two reasons: security and brittleness. Security first: ObjectInputStream.readObject instantiates whatever classes the byte stream names, before your validation code ever runs.

Attackers chain readily available classes on your classpath — so-called gadget chains, the famous one built from Apache Commons Collections — into remote code execution from a single deserialized payload; several major CVEs (public vulnerability records) came from exactly this.

The JDK's mitigation is deserialization filters — ObjectInputFilter, added in JDK 9 and strengthened in JDK 17 — which let you allowlist classes, but the safest stream is one you never deserialize.

Brittleness second: the format is coupled to private class internals, so refactoring breaks stored data, and it is Java-only. Instead: JSON via Jackson for human-readable interop, Protocol Buffers or Avro when you need compact binary with an explicit, versioned schema. Keep implements Serializable only where a framework genuinely forces it.

Land it Native serialization executes the attacker's class choices before your code gets a vote — schema-based formats make deserialization a parse, not an invocation.

Likely follow-ups
"We have a legacy service that must keep accepting Java-serialized payloads for another year. How do you make that as safe as it can be?"

I would install a deserialization filter and make it an allowlist, not a blocklist.

The JVM-wide switch is the system property jdk.serialFilter, or the same pattern in the java.security file, and the syntax is a list like com.acme.dto.*;java.base/*;!* — the trailing !* rejects everything I did not name.

I also add resource limits in the same string: maxdepth=20;maxrefs=10000;maxbytes=1048576, so a tiny payload cannot expand into a huge object graph. Since JDK 17 there is also a filter factory, set with jdk.serialFilterFactory, which lets me pick a different filter per stream context.

Then I log every rejection, run it in staging first to find the classes I forgot, and treat any rejection in production as a security signal, not noise.

"How would you verify in production that the filter is actually in force?"

Two checks. First, at startup I log ObjectInputFilter.Config.getSerialFilter() and fail the boot if it is null, because the most common failure is a JVM flag that was dropped in a deployment template.

Second, I keep a canary test in the integration suite: it serializes an instance of a harmless class that is not on the allowlist, feeds it to the real endpoint, and asserts that the response is a rejection and that an InvalidClassException with the message "filter status: REJECTED" appears in the logs.

I also enable -Djava.security.debug=serialfilter temporarily when tuning, which prints every filter decision, so I can see the classes being checked rather than trusting the configuration on paper.

"Why is Protocol Buffers safer than Java serialization? Isn't parsing untrusted bytes always risky?"

The difference is what the bytes are allowed to say. A Java serialization stream names classes, and the runtime instantiates whatever it is told; the input decides which code runs.

A Protocol Buffers message can only populate fields of the one message type the parser was compiled for, so the input decides values, never types or code.

Parsing bugs are still possible, which is why I bound message size — CodedInputStream.setSizeLimit — and recursion depth, but a bug there is a crash or a denial of service, not remote code execution.

The same reasoning applies to Jackson, provided I never enable default typing, which is the one Jackson feature that reintroduces "the input picks the class" and has its own history of gadget-chain vulnerabilities.

"A framework forces Serializable on your HTTP session objects. What is your rule for those classes?"

My rule is that anything that touches a serialized session must be a small, boring value class.

Concretely: only primitives, strings, and other such value classes as fields; no references to services, connections, or anything with a lifecycle; a declared serialVersionUID so an innocent refactor does not silently invalidate every live session; and transient on anything derivable.

I keep the session tiny by storing identifiers, not whole domain objects, and I put the session store behind the same deserialization filter as everything else.

When the store is Redis or a database, I strongly prefer configuring the framework to use a JSON serializer for session attributes, which most session libraries support, so native serialization never reaches the wire at all.

Q102. "What does transient do, and what is readObject for — the legitimate use and the honest risk?"

Reveal answer

Strong answer transient excludes a field from the serialized stream; on deserialization it comes back as the type's default — null or zero.

You use it for secrets that must not be persisted, for caches derivable from other fields, and for members that are not serializable at all, like a lock or an executor.

readObject is a private method a class can define that the runtime calls during deserialization instead of blindly filling fields.

Its legitimate jobs: rebuild the transient state just lost, and validate invariants — essential, because deserialization is effectively an invisible constructor that bypasses every check your real constructors enforce, so a hostile stream can otherwise materialize an object your code could never legally build.

The honest risk: readObject runs while the input is fully attacker-controlled, so every readObject on the classpath is attack surface — validate before using any field, make defensive copies of mutable ones, and pair it with an ObjectInputFilter allowlist.

Land it Treat readObject as a public constructor taking untrusted input — because operationally, that is exactly what it is.

Likely follow-ups
"What is serialVersionUID, and what actually happens if you don't declare it?"

serialVersionUID is a long the stream carries to identify the version of the class that wrote it. If I do not declare it, the JVM computes one by hashing the class's name, fields, method signatures, and modifiers.

That means adding a harmless helper method changes the hash, and every previously stored object now fails with InvalidClassException saying the stream and local class descriptors are incompatible.

Declaring it explicitly, private static final long serialVersionUID = 1L;, freezes the identity so that compatible changes — adding a field, which reads back as default, or removing one, which is ignored — keep working.

I bump the number only when a change is genuinely incompatible and I want old data rejected on purpose.

"How do readObject and readResolve differ, and when would you use readResolve?"

readObject runs while the object is being filled in; it is the place to validate fields and rebuild transient state. readResolve runs after the object is fully built and lets me substitute a different object as the result.

The classic use is a singleton or an enum-like type: without readResolve, deserialization constructs a brand-new instance, and my "one instance" invariant is broken. With readResolve returning the canonical instance, the freshly built duplicate is discarded.

The serialization proxy pattern uses the same hook: I serialize a small proxy object instead of the real class, and its readResolve calls the real constructor, so all invariant checks run through the front door rather than through a hidden constructor.

"Give me a concrete readObject that defends against a hostile stream."

Suppose a class holds a Date start and end with the invariant that start precedes end. A hostile stream can set them in the wrong order, and it can also keep a reference to the mutable Date objects it handed me.

So the method reads in.defaultReadObject() first, then makes defensive copies — start = new Date(start.getTime()) — and only then checks the invariant, throwing InvalidObjectException if it fails. The order matters: copy first, validate second, because validating an object an attacker can still mutate is validating nothing.

The copies must be done with the copied values assigned to final fields through reflection or, more cleanly, by making the fields non-final, which is one honest reason to prefer the serialization proxy pattern.

"Why does deserialization not run the constructor? What does it run instead?"

The JVM allocates the object and runs the no-argument constructor of the nearest superclass that is not serializable — often just Object — and then fills the fields directly from the stream, bypassing every constructor of the serializable classes in the hierarchy.

That is why a class with a private constructor that validates inputs is still fully constructible from bytes. It is also a subtle trap: if the first non-serializable superclass has no accessible no-argument constructor, deserialization fails with InvalidClassException: no valid constructor.

Records changed this in JDK 16: a record is always deserialized through its canonical constructor, so its compact-constructor validation runs, which is one concrete reason records are the safer choice for serializable value types as of Aug 2026.

Q103. "In plain words, how does the JVM get from interpreting bytecode to fully optimized machine code?"

Reveal answer

Strong answer Through tiered compilation. Code starts in the interpreter, executing bytecode instruction by instruction — slow per operation, but it starts instantly and, importantly, it counts: method invocations and loop iterations.

When counters mark a method hot, C1 — the fast, lightly-optimizing compiler — produces decent machine code quickly and embeds profiling probes that record which branches are taken and which concrete types actually flow through each call site.

The hottest methods then go to C2, the slow, aggressive compiler, which uses that profile to inline call chains, eliminate allocations via escape analysis, and speculate — for example compiling an interface call as a direct call to the only implementation ever observed.

Speculation is a bet: if it is ever wrong, the JVM deoptimizes — throws the compiled code away, falls back to the interpreter, and recompiles with corrected assumptions.

The design rationale: compilation is expensive, so spend it only where it pays back, guided by evidence of real behavior rather than static guesses.

Land it The JVM is a profile-guided optimizer that gambles on what it has seen and keeps the interpreter around as the safety net — which is also why it needs warmup.

Likely follow-ups
"What are the actual thresholds? When does a method go to C1 and when to C2?"

With tiered compilation the levels are numbered 0 to 4: level 0 is the interpreter, levels 1 to 3 are C1 variants, and level 4 is C2.

The transitions are driven by counters: the interpreter hands a method to C1 at level 3 after roughly 200 invocations, controlled by -XX:Tier3InvocationThreshold, and by back-edge counts around 2,000 for loops.

C1 level 3 code then profiles, and once invocations reach about 5,000, -XX:Tier4InvocationThreshold, or the combined invocation-plus-loop count reaches 15,000, the method is queued for C2.

These are defaults and they scale when the compile queues are busy, which is why the same code can warm at different speeds on different machines. I can watch the levels with -XX:+PrintCompilation, where the number after the timestamp is the tier.

"What does deoptimization look like in practice, and how would you spot it hurting a service?"

A deoptimization shows up as a method that was fast suddenly running slow for a while, then fast again.

The common trigger is a type profile that was too narrow: an interface call site saw one implementation for an hour, C2 inlined it, then a new implementation appeared — perhaps a feature flag flipped — and the guard failed.

The JVM throws the compiled code away, and the method re-enters the interpreter until the counters trigger recompilation. To spot it I use -Xlog:jit+deoptimization=debug or a JFR recording, where the jdk.Deoptimization event names the method and the reason, such as class_check or unstable_if.

Repeated deoptimization of the same method is the smell; C2 eventually stops trusting that site and compiles it megamorphically, which is slower but stable.

"What is the code cache and what happens when it fills up?"

The code cache is native memory that holds compiled machine code, sized by -XX:ReservedCodeCacheSize, which defaults to 240MB when tiered compilation is on. If it fills, the JVM prints "CodeCache is full.

Compiler has been disabled" and stops compiling, so every new hot method stays in the interpreter forever — the service gets slower over days without any error.

Since JDK 9 the cache is segmented into non-method, profiled, and non-profiled regions, and there is a sweeper that evicts cold code, but a large application with many classes can still exhaust it.

I monitor it with jcmd <pid> Compiler.codecache or the JFR CodeCacheFull event, and I raise the reservation if the used size sits near the limit under steady load.

"Does the JIT ever inline across a virtual call? How does it decide?"

Yes, and that is where most of the speed comes from. C2 uses the type profile the C1 stage collected at each call site.

If exactly one receiver type was ever seen, the site is monomorphic and C2 inlines it directly, guarded by a cheap class check. Two types make it bimorphic and both get inlined behind a two-way check.

Three or more make it megamorphic, and C2 gives up and emits a real virtual dispatch through the vtable or itable — noticeably slower and a barrier to further optimization.

There are size limits too: -XX:MaxInlineSize at 35 bytes of bytecode for cold methods and -XX:FreqInlineSize at 325 for hot ones. This is why hot polymorphic code paths with many implementations sometimes benefit from splitting the call site.

Q104 · Scenario. "Every deploy, the first minute of traffic to a new pod shows a p99 of two seconds instead of the usual fifty milliseconds. Why, and what actually helps?"

Reveal answer

Strong answer The JVM is cold. Thousands of classes are being loaded, verified, and initialized; every method starts in the interpreter, roughly ten times slower than compiled code; the JIT compiles gradually, and compilation itself steals CPU from requests. On top sit the application's own cold-start costs: empty connection pools, empty caches, first-time TLS handshakes.

  1. Measure which cost dominates before fixing: -Xlog:class+load for class loading, -XX:+PrintCompilation or a JFR (JDK Flight Recorder, the JVM's built-in profiler) recording for compilation activity versus pool and cache misses.
  2. Ramp the traffic instead of the JVM: keep the readiness probe failing until the app has warmed, and use slow-start in the load balancer — Envoy's slow_start mode, for instance — so a new pod receives a trickle that grows over a window, letting the JIT warm on real traffic while the old pods carry the load.
  3. Warm deliberately: have startup code exercise the genuinely hot endpoints — real serialization, real query paths — before reporting ready. A synthetic loop that skips the real code paths trains the JIT on the wrong profile and buys nothing.
  4. Cut the class-loading share with CDS — Class Data Sharing — and its application-level form AppCDS: run once with -XX:ArchiveClassesAtExit=app.jsa, then start with -XX:SharedArchiveFile=app.jsa so class metadata is memory-mapped in pre-parsed form. Newer JDKs (24 onward, under Project Leyden) extend this into ahead-of-time caches that also carry compiled-code state.

Land it You cannot skip warmup, only decide who suffers through it — ramping and archives shift the cost off your users' first requests.

Likely follow-ups
"You added slow-start and a warmup routine, and p99 during the first minute is still 800ms. What next?"

Then I stop guessing and profile the first sixty seconds specifically.

I start the pod with JFR recording from boot, -XX:StartFlightRecording=duration=120s,filename=boot.jfr, and look at three things: the jdk.Compilation events to see whether the compiler threads are saturated, the class loading count over time, and the hot methods in the execution samples. Two outcomes are typical.

If compile queues are the bottleneck on a small CPU limit, the fix is more CPU during startup — Kubernetes cannot burst above the limit, so I raise it or use a startup probe with a longer window.

If the warmup routine is missing the real hot paths, I compare the set of methods compiled after one minute of warmup against one minute of real traffic and extend the routine to cover the gap.

"Explain what AppCDS actually stores, and what it cannot help with."

AppCDS stores the parsed and verified class metadata — the same structures the JVM builds in metaspace when it loads a class — in an archive file that is memory-mapped at startup.

So class parsing, verification, and much of the linking cost disappear, which typically cuts startup time by 20 to 40 percent for a large Spring application.

What it cannot help with is the interpreter-to-JIT warmup, because it holds no compiled code; and it cannot help with the application's own startup work, like building bean graphs or connection pools.

Those are the parts Project Leyden targets: as of Aug 2026, JDK 24's AOT cache, enabled with -XX:AOTCache, additionally stores loaded and linked classes, and JDK 25 adds AOT method profiles, so C2 has a warm profile from the first request.

"How would you build the Leyden AOT cache in a container pipeline?"

It is a training run. In the image build, I start the application once with -XX:AOTMode=record -XX:AOTConfiguration=app.aotconf, drive representative traffic against it — the same warmup script — and shut it down cleanly. Then a second step runs -XX:AOTMode=create -XX:AOTConfiguration=app.aotconf -XX:AOTCache=app.aot to produce the archive.

In JDK 25 there is a one-step form, -XX:AOTCacheOutput=app.aot, which records and creates together. The production command line then adds -XX:AOTCache=app.aot.

The important operational rule is that the cache is tied to the exact JDK build and classpath, so it must be produced in the same image build that ships, and the JVM silently ignores a mismatched cache — so I log the -Xlog:aot output at startup and alert if the cache was not used.

"Would you consider GraalVM native image for this? What is the trade?"

I would consider it when startup time is the dominant requirement, such as serverless functions or autoscaled workers that live for minutes.

Native image compiles the whole application ahead of time into a binary that starts in tens of milliseconds with a small heap, which eliminates this problem entirely.

The trade is real: build times of several minutes, a closed-world assumption that breaks reflection and dynamic proxies unless every use is registered in metadata, no runtime profile-guided optimization by default so peak throughput is often 10 to 30 percent lower than a warmed C2, and a different set of debugging and monitoring tools.

For a long-running service that serves traffic for days between deploys, the JIT's higher peak wins and the warmup techniques above are enough.

Q105 · Scenario. "A teammate's hand-rolled benchmark — a timed for-loop around the method — reports 0.5 nanoseconds per call. Why is that number impossible, and what did the JIT actually do?"

Reveal answer

The real test Whether you know the optimizer will happily delete a benchmark whose results nobody uses — and why JMH exists.

Strong answer Half a nanosecond is roughly one CPU cycle — no real method runs that fast, so the JIT almost certainly deleted the work. Several effects conspire:

  1. Dead-code elimination: the loop computes a result nobody reads, so the compiler, correctly, removes the computation — the benchmark times an empty loop.
  2. Constant folding: if the inputs are compile-time constants, the JIT computes the answer once and the loop measures nothing.
  3. On-stack replacement: OSR is the JVM's trick of recompiling a method while its loop is still running and jumping into the compiled version mid-flight — so one timed run blends interpreted iterations, compiled iterations, and the compilation pause, and OSR-compiled code is not even identical to normally-compiled code.
  4. Plus no warmup separation, and no accounting for the cost and granularity of System.nanoTime itself.

The fix is JMH — the Java Microbenchmark Harness — which exists precisely to defeat this list: it forks fresh JVMs so runs cannot contaminate each other, runs declared warmup iterations before measuring, feeds results into a Blackhole so dead-code elimination cannot fire, structures the harness so hot code is compiled normally rather than via OSR, and reports scores with error margins. Sanity-check any claimed result against -XX:+PrintCompilation or JMH's perfasm profiler to see what code actually ran.

Land it A naive benchmark measures the optimizer's ability to delete your code — if a number looks too good to be true, the JIT probably made it up.

Likely follow-ups
"Show me the JMH skeleton you would write, and explain the annotations."

The minimal shape is a class annotated @State(Scope.Thread) holding the inputs as fields, a method annotated @Benchmark that returns the result, and a main that runs org.openjdk.jmh.Main. @BenchmarkMode(Mode.AverageTime) with @OutputTimeUnit(TimeUnit.NANOSECONDS) gives me nanoseconds per call.

@Warmup(iterations = 5, time = 1) and @Measurement(iterations = 5, time = 1) separate warmup from measurement, and @Fork(2) runs everything in two fresh JVMs. Returning the result, or passing it to a Blackhole parameter, is what defeats dead-code elimination.

Inputs live in @State fields precisely so the JIT cannot see them as constants and fold them. I run it with the Gradle or Maven JMH plugin so the benchmark classpath matches production.

"How do you know your JMH result is trustworthy rather than another artifact?"

I look at the error margin first: if the reported 99.9 percent confidence interval is wider than the difference I am trying to measure, the result says nothing. Then I check for artifacts.

I run with -prof gc to see allocation rate per operation, because a benchmark that allocates nothing when the real code allocates was probably scalar-replaced.

I run with -prof perfasm on Linux to read the generated assembly for the hot loop, which shows immediately if the work was folded away. I vary the input size and confirm the time scales as expected.

And I compare against a known baseline like a trivial method, because if my "expensive" method benchmarks the same as an empty one, the JIT removed it.

"Why fork a new JVM? What contamination does that prevent?"

Profile pollution.

The JIT compiles based on what it has observed, and observations persist for the life of the JVM. If benchmark A calls an interface method with one implementation and benchmark B runs afterward with a different implementation, B sees a call site that is already bimorphic and pays a cost A never paid — the order of benchmarks changes the results.

Forking gives each benchmark a clean profile, a clean code cache, and a heap in a known state. It also averages away one-off effects: memory layout differences, where the OS placed the heap, which physical CPU the threads landed on.

Two or more forks with consistent results is the evidence that the number is a property of the code, not of one lucky process.

"Is a microbenchmark even the right tool here? When would you refuse to write one?"

I refuse when the question is about system behavior rather than a small piece of code. A microbenchmark measures a method in isolation with a warm cache, a warm branch predictor, and no contention, which is the opposite of production conditions.

Questions like "is this serializer faster for our payloads" are fine; questions like "will this change lower our p99" are not, because p99 is dominated by GC pauses, lock contention, and downstream latency that no microbenchmark models.

For those I use a load test against a staging environment with production-like data and an allocation profiler. I also refuse when the expected difference is under about five percent, because that is inside the noise of most environments and the effort is better spent elsewhere.

05 · Memory & GCJVM Memory & Garbage Collection — Q106–Q140

Memory is where an interviewer finds out whether you have operated a Java Virtual Machine (JVM) in production or only read about one. This section drills the memory layout, the garbage collectors, every variety of OutOfMemoryError as a production scenario, and the leak-hunting workflow with the real tools and flags. Thread dumps and CPU debugging belong to another section; here we stay strictly on memory.

Drill · Layout, object lifecycle & reference types

These questions test whether you can place every byte a JVM uses and narrate an object's life from allocation to reclamation without hand-waving.

Q106. "Walk me through the JVM's memory areas — heap, stack, metaspace, direct memory. What actually lives in each?"

Reveal answer

The real test Whether you know the process uses far more memory than the heap, and can say what the extra is.

Strong answer The heap is the shared pool where all objects live, managed by garbage collection (GC) — the JVM subsystem that finds dead objects and reclaims their space.

Each thread has its own stack, holding one frame per method call: local variables, primitives, and references — pointers into the heap. Objects themselves never live on the stack, only references to them.

Metaspace is native memory — memory the JVM requests from the operating system outside the heap — holding class metadata: each class's structure, method bytecode, and constant pool. It replaced PermGen in Java 8 and grows until -XX:MaxMetaspaceSize.

Direct memory is native memory allocated through ByteBuffer.allocateDirect or libraries like Netty, so input/output can happen without copying data through the heap; it is capped by -XX:MaxDirectMemorySize.

Land it The process's true footprint is heap plus metaspace plus thread stacks plus direct buffers plus GC and compiler overhead — which is why "-Xmx is 4G but the OS shows 6G resident" is normal, not a bug.

Likely follow-ups
"How would you actually account for the 2GB gap between -Xmx and RSS on a running process?"

I would turn on Native Memory Tracking and read the summary. Start with -XX:NativeMemoryTracking=summary, then jcmd <pid> VM.native_memory summary prints a table by category: Java Heap, Class, Thread, Code, GC, Compiler, Internal, Symbol, and Other.

On a typical 4GB-heap service I expect Class around 100 to 200MB, Thread equal to the thread count times the stack size, Code around 50 to 100MB, and GC bookkeeping that for G1 is a few percent of heap and for ZGC noticeably more.

Whatever NMT does not explain is outside the JVM's accounting: glibc malloc arenas, direct buffers that NMT lists under Other, or a native library.

The single flag that most often closes the gap is MALLOC_ARENA_MAX=2, because glibc creates one arena per core and each holds fragmented free space.

"What is the default for MaxMetaspaceSize, and is that a problem?"

The default is unlimited — metaspace grows until the operating system refuses. That is a deliberate change from PermGen's fixed 64MB or so, because the old cap caused far more outages than runaway class metadata ever did.

The catch in a container is that unlimited metaspace is a way to blow the cgroup memory limit and get OOMKilled with no Java stack trace.

So in containers I do set it, typically 256MB for a large Spring service after measuring actual usage with jcmd <pid> VM.metaspace, and I set it high enough that hitting it means a genuine classloader leak.

The related knob, -XX:MetaspaceSize, is not a cap; it is the occupancy that triggers the first GC for class unloading, so raising it just delays the first metaspace-driven collection.

"Where do string literals and interned strings live now?"

In the heap, since Java 7. Before that, interned strings and the string constant pool lived in PermGen, which is why heavy use of String.intern() used to cause PermGen exhaustion.

Now the String objects live in the ordinary heap and are eligible for collection when nothing references them; the intern table itself is a native hash table in the JVM that holds weak-style references to those heap strings.

Class metadata and the class-level constant pool — the symbolic references to classes and methods — stay in metaspace, and the shared symbol table is native memory under the Symbol category in NMT. The practical consequence is that a heap dump shows interned strings, but it does not show the symbol table.

"How big is each thread stack really, and can I make them smaller?"

The reservation is -Xss, 1MB by default on 64-bit Linux, but reservation is not residency: the operating system only backs the pages a thread actually touches, so a thread that never recurses deeply may use 100KB of physical memory.

NMT's Thread category reports the reserved and committed numbers separately, and the committed figure is what matters for the container budget.

I can lower -Xss to 512KB or 256KB for services with many shallow threads, but a deeply recursive path or a big framework stack will then throw StackOverflowError, so I test it under real traffic.

Virtual threads change the picture: their stacks live in the heap as small chunks that grow and shrink, so a million of them is feasible where a million platform threads is not.

Q107. "Why is the heap split into generations at all? Explain the weak generational hypothesis in plain words."

Reveal answer

The real test Whether you can justify the design from first principles instead of reciting the region names.

Strong answer The weak generational hypothesis is an empirical observation: most objects die very young.

The temporary strings, DTOs, and iterators created while serving one request are garbage milliseconds later, while an object that has survived a while — a connection pool, a cache — tends to keep surviving.

So the JVM splits the heap into a young generation — eden, where new objects are born, plus two small survivor spaces that hold recent survivors — and an old generation for long-lived objects.

This makes collection cheap: a young collection copies out the few live survivors and reclaims the rest of eden wholesale, so its cost is proportional to what survived, not to the mountain of garbage. The old generation, where little dies, is collected far less often.

Land it Generational GC is a statistical bet on death rates — and workloads that break the bet, like medium-lived objects or giant caches, are exactly the ones that cause GC pain.

Likely follow-ups
"Which workloads break the hypothesis, and what does that look like in the GC log?"

The classic breaker is the medium-lived object: something that lives for a few seconds — an in-flight request in a slow pipeline, a batch of rows being aggregated, a message waiting for an acknowledgement.

It survives several young collections, gets copied between survivor spaces each time, and is finally promoted just before it dies, so the old generation fills with objects that were never truly long-lived.

In the log I see high survivor occupancy after every young collection, objects reaching the maximum tenuring age, a steady promotion rate, and old-generation cycles that reclaim a lot — which means the promoted objects died, so promoting them was wasted work.

Large caches break it differently: they are long-lived but churn, so the old generation is both large and busy. Generational ZGC and G1 both suffer here.

"Why two survivor spaces and not one?"

Because copying collection needs an empty destination. A young collection copies live objects out of eden and out of the current survivor space into the other survivor space, which must be empty for that to be a simple bump-the-pointer copy with no fragmentation.

After the collection, the roles swap: the destination becomes the "from" space for the next cycle, and the now-empty source becomes the next destination.

With one survivor space I would be copying live objects into a space that still holds live objects, which means either compacting in place, which is slower and needs forwarding pointers, or losing the ability to age objects across cycles.

The cost is that one survivor space is always idle, which is why they are kept small, typically an eighth of the young generation each under -XX:SurvivorRatio=8.

"Does ZGC still use generations? I thought it was a single-generation collector."

It was, originally, and that was its main throughput weakness: every cycle had to mark the whole heap, so a high allocation rate meant continuous marking.

Generational ZGC arrived in JDK 21 under JEP 439, became the default ZGC mode in JDK 23 under JEP 474, and the non-generational mode was removed in JDK 24 under JEP 490 — so as of Aug 2026, ZGC is generational, full stop.

It keeps young and old generations as logical sets of regions, collects the young generation frequently and concurrently, and uses store barriers to track old-to-young references rather than a card table.

The measured result in the JEP was several times lower GC CPU on allocation-heavy workloads and far less heap headroom needed, which closed most of the gap to G1.

"How would you measure whether your workload fits the hypothesis?"

I read three numbers from the GC log. First, the young-collection survival ratio: how many megabytes came out of eden alive versus how many went in; under 5 percent means the hypothesis holds.

Second, the promotion rate, which I get from old-generation occupancy growth between young collections; a healthy service promotes a few megabytes per second at most.

Third, the tenuring distribution from -Xlog:gc+age=trace, which shows bytes at each age; a healthy shape decays fast, while a fat tail at high ages means objects are living just long enough to be expensive.

If those numbers look bad, I use a JFR allocation profile to find the allocation sites of the medium-lived objects and consider streaming or pooling them.

Q108. "Minor GC, major GC, full GC — what's the difference, and which one should page you?"

Reveal answer

Strong answer A minor GC collects only the young generation. It runs whenever eden fills, it is stop-the-world — all application threads paused — but usually takes single-digit milliseconds, and it is completely normal to see one every few seconds.

A major GC is the loose term for collecting the old generation; in practice people use it interchangeably with full GC, so in an interview I define my terms.

A full GC collects the entire heap — young and old together, usually with class unloading in metaspace — and is the expensive one: in G1 the fallback full GC is single-threaded compaction that can pause a large heap for seconds.

It triggers when the old generation fills faster than concurrent collection can keep up, or when fragmentation leaves no contiguous space.

Going deeper One correction worth making out loud: G1's fallback full GC has been parallel since JDK 10 under JEP 307, using all GC worker threads to mark, compact, and fix references.

It is still the slowest event G1 produces — a full compaction of an 8GB heap typically takes one to several seconds — but it is not single-threaded.

The log line to alert on is Pause Full (G1 Compaction Pause), or with the cause G1 Humongous Allocation or G1 Evacuation Pause when an evacuation failed.

In the log, an evacuation failure appears before the full GC as "to-space exhausted", which means G1 ran out of free regions to copy survivors into; that is the leading indicator, and it means the heap needs headroom or the reserve, -XX:G1ReservePercent at 10 by default, needs to be raised.

Land it Frequent minor GCs are the system breathing; recurring full GCs are an incident — that is the line I alert on in the GC logs.

Likely follow-ups
"What specifically triggers a full GC in G1, as opposed to a mixed collection?"

A mixed collection is planned: concurrent marking finishes, G1 knows which old regions are mostly garbage, and it adds a few of them to each young pause. A full GC is the failure case, and there are three usual triggers.

First, evacuation failure: during a young or mixed pause, G1 cannot find a free region to copy a live object into, logged as "to-space exhausted", and it falls back to compacting in place. Second, a humongous allocation that cannot find enough contiguous free regions.

Third, marking losing the race: the old generation fills to the limit before the concurrent cycle completes, so there are no cleaned regions to evacuate into.

Each has a different fix, which is why the cause string on the full GC line is the first thing I read.

"How would you alert on this? What is the actual metric and threshold?"

I export GC events as metrics rather than grepping logs.

With Micrometer, jvm.gc.pause is a timer tagged with the cause and action, so I can alert on any pause with action equal to "end of major GC" — that is the full GC — with a threshold of one occurrence per hour for a latency-sensitive service.

For pause duration, I alert on the maximum young pause exceeding my SLO budget, for example 200ms, over a five-minute window.

And I track the post-collection old-generation occupancy, jvm.memory.used for the old pool sampled right after collections, and alert on a rising linear trend over six hours, which catches leaks before they become full GCs.

A full GC on a service that normally has none is a page; a full GC on a batch job is expected and I do not alert at all.

"Is a full GC ever acceptable in a service? Would you ever trigger one deliberately?"

Acceptable, yes, in two cases: at startup after warmup, to compact and promote the long-lived working set once so later cycles are cheap; and on a service with a low traffic window where a nightly compaction is cheaper than tuning.

Triggering one deliberately, I would do only through jcmd <pid> GC.run for diagnosis — for example, to measure the true live set before a heap dump — never from application code.

System.gc() in application code is a smell because a library somewhere else may also call it, and a full GC per call is an easy way to create pauses.

If someone else's library does it, -XX:+ExplicitGCInvokesConcurrent makes G1 run a concurrent cycle instead, and -XX:+DisableExplicitGC ignores it entirely, though the latter breaks the direct buffer cleanup path in NIO.

"What is the difference between a young pause that takes 300ms and a full GC that takes 300ms?"

The cause and the trend.

A 300ms young pause means either the young generation is huge and holds a lot of live data at collection time, or the pause was inflated by something outside the copying — time-to-safepoint, reference processing, or a slow disk while writing the log.

It is a tuning problem and often a one-off. A 300ms full GC on a small heap is the symptom of the old generation being exhausted, and full GCs come in clusters: each one reclaims a little, the heap refills, and the next one comes sooner.

So the young pause makes me look at the phases in -Xlog:gc* to see where the time went; the full GC makes me look at the post-GC occupancy trend to see whether I am about to run out of memory entirely.

Q109. "Why is new so cheap in Java? Explain TLABs and bump-the-pointer allocation."

Reveal answer

The real test Whether you know allocation cost and collection cost are different bills.

Strong answer Each thread gets a TLAB — a Thread-Local Allocation Buffer, a private slice of eden that only that thread allocates from.

Because the slice is private and eden is a contiguous empty run of memory after every young collection, allocating is just bump-the-pointer: check there is room, advance a pointer by the object's size, done — roughly ten machine instructions, no lock taken and no search through free lists the way a general-purpose malloc must.

When a thread exhausts its TLAB it grabs a fresh one, which is the only synchronized step and is rare. That is why allocating millions of short-lived objects per second is normal in Java.

why allocation costs about ten cyclesruns offline
// Every thread owns a TLAB — a private slab carved out of Eden. Allocation is
// a pointer bump in that slab, with NO lock and NO free list:
//
//     ptr = tlab.top;
//     if (ptr + size <= tlab.end) {
//         tlab.top = ptr + size;        // that is the whole allocation
//         return ptr;
//     }
//     return slowPath(size);            // new TLAB, or straight into Eden

// Consequences worth stating:
//  - No contention between threads, because each has its own slab.
//  - Memory is handed out sequentially, so newly allocated objects are
//    contiguous and cache-friendly.
//  - The COST IS IN COLLECTION, and collection cost is proportional to what
//    SURVIVES, not to what was allocated. Garbage that dies in Eden is
//    genuinely close to free — it is never even visited.

// Which is why "avoid allocation" is usually the wrong advice, and
// "avoid allocations that SURVIVE" is the right one.

// Watch TLAB behaviour if you suspect the slow path:
//   -XX:+PrintTLAB -XX:+UnlockDiagnosticVMOptions
// A high slow-path rate means objects too large for a TLAB, or too many
// threads sharing too small an Eden.

The second bullet point is the one that changes decisions. Because collection cost scales with survivors rather than allocations, a service allocating a gigabyte a second of immediately-dead objects can have shorter pauses than one allocating a tenth of that and keeping it.

Land it Allocation is nearly free but collection is not — allocation rate in MB/s is what drives GC frequency, so the best GC tuning is often allocating less on the hot path.

Likely follow-ups
"What happens when an object is bigger than the remaining TLAB space?"

The thread has a choice: waste the rest of the current TLAB and grab a new one, or allocate this object directly in eden outside any TLAB. The JVM decides by size.

If the object is larger than the TLAB refill waste limit, a fraction controlled by -XX:TLABRefillWasteFraction at 64 by default, the object goes to a slow path: an atomic compare-and-swap on the shared eden top pointer, which is still cheap but contended.

Otherwise the thread retires the current TLAB — filling the unused tail with a dummy int array so the heap stays parseable — and takes a fresh one. TLAB sizes adapt per thread based on allocation rate, so a thread allocating heavily gets bigger TLABs.

I can see the statistics with -Xlog:gc+tlab=trace, and a high slow-path count is a signal of many medium-large allocations.

"So if allocation is nearly free, why is allocation rate the number you watch?"

Because every megabyte allocated is a megabyte that a young collection has to process, and young collections stop the world.

If a service allocates 500MB per second into a 2GB eden, a young pause happens every four seconds, and each pause must trace and copy whatever is live at that moment — including all the in-flight request objects.

Halving the allocation rate halves the pause frequency at zero change to pause length, which is the cheapest latency improvement available. It also matters for cache behavior: allocation streams through memory, evicting useful data from CPU caches.

I measure it with the JFR jdk.ObjectAllocationSample events, which show the top allocation sites by bytes, and typically the top three sites — a serializer, a logging pattern, a stream pipeline building intermediate lists — account for most of it.

"Does ZGC allocate the same way?"

Mostly, yes, at the thread level. ZGC also uses TLABs and bump-the-pointer allocation, so the fast path from the application's point of view is identical.

The difference is where the TLABs come from: ZGC hands out small regions of 2MB for ordinary objects, medium regions of 32MB for objects up to a quarter of that size, and dedicated large regions for anything bigger, and it has no eden as a contiguous area.

Generational ZGC also has a fast path that is slightly heavier because of the store barrier on reference writes.

Where ZGC allocation gets expensive is under allocation stall: if the application allocates faster than the concurrent collector frees memory, threads block in allocation until a cycle finishes, logged as "Allocation Stall", and that is the ZGC equivalent of a long pause.

"Is object pooling ever worth it in modern Java?"

Only for objects that are genuinely expensive to create or that carry non-heap resources — connections, threads, large direct buffers, compression contexts.

For ordinary small objects, pooling is usually a loss: it turns cheap young-generation garbage into long-lived old-generation objects that every marking cycle must trace, it adds synchronization to hand objects in and out, and it creates aliasing bugs when someone forgets to return or reset an object.

The generational collector was designed precisely so that short-lived objects cost almost nothing.

My rule is to profile first: if a JFR allocation profile shows that a specific large buffer is allocated per request and the young collection cost is measurable, I pool that one thing, and I reach for a bounded pool with clear ownership like Netty's PooledByteBufAllocator.

Q110. "What are GC roots, and how does the collector decide what is garbage?"

Reveal answer

The real test Whether you understand the collector finds the living, not the dead — the fact every leak diagnosis rests on.

Strong answer The collector never looks for garbage directly — it traces the live objects and everything left over is garbage by definition. Tracing starts from the GC roots: references the program can reach without going through another heap object.

The main ones are local variables and operand stacks of every running thread, the threads themselves, static fields of loaded classes, and references held by native code through JNI — the Java Native Interface, the bridge to C code.

From those roots the collector follows every reference transitively; whatever was never reached is unreachable and can be reclaimed.

This is also why Java does not use reference counting: counting cannot reclaim two objects that point at each other in a cycle, while tracing from roots handles cycles for free.

Land it A Java memory leak is therefore never "forgotten" memory — it is memory still reachable from a root that the program will never use again, which is exactly why the fix is always to cut a reference.

Likely follow-ups
"List the actual root categories a heap analyzer shows you, and which ones matter most for leaks."

Eclipse MAT lists them by name: System Class, meaning classes loaded by the bootstrap loader and their static fields; Thread, the thread objects themselves; Java Local, references on a thread's stack; Native Stack and JNI Local and JNI Global, references held by native code; Busy Monitor, objects whose monitor a thread currently holds; and Thread Block and Finalizable.

For leak hunting, three dominate. System Class and other static fields are the immortal roots, so a static map is the first suspect. Thread is next, because a live pooled thread pins its ThreadLocalMap and everything in it.

Java Local matters mainly for a stuck thread that holds a huge local graph. When MAT shows "path to GC roots", the root category at the top of the chain tells me which kind of fix I need: a bound, a remove(), or a thread shutdown.

"How does the collector know which stack slots and registers hold references at a safepoint?"

Through oop maps, which the JIT compiler records at every safepoint poll when it compiles a method. An oop map is a table saying, for this instruction address, these registers and these stack offsets contain object references and these contain plain numbers.

The interpreter does not need a table because it knows the types of everything on its operand stack from the bytecode verifier's analysis.

So when all threads stop at safepoints, the collector walks each stack frame, looks up the oop map for that frame's program counter, and treats exactly those slots as roots.

This is also why the JVM cannot stop a thread at an arbitrary instruction: between safepoints the compiled code may hold a reference in a form the map does not describe, such as a pointer to the middle of an array during a loop.

"Is 'unreachable' the same as 'collectable' in practice?"

Not quite; there are delays and exceptions. An unreachable object that has a registered Cleaner or a pending finalizer is discovered, queued, and only reclaimed after the cleanup action runs, which needs a later cycle.

An object reachable only through a soft reference is unreachable by the strong definition but is kept alive until memory pressure.

And an unreachable object in a region the collector has not chosen to collect stays in memory: G1 only evacuates the regions in the collection set, and ZGC only relocates the regions it selected, so garbage in an old region can sit there for many cycles.

That is why heap usage after a young collection is not the live set — only the occupancy after a full marking cycle and compaction gives me the true number.

"What is a dominator, and why does MAT organize the dump around it?"

An object A dominates object B if every path from the GC roots to B passes through A — so if A became unreachable, B would too.

The retained size of A is the total size of everything it dominates, which is exactly "how much memory would I get back if I cut this reference".

That is the question a leak hunt asks, so MAT builds the dominator tree once and sorts by retained size. A plain reference graph cannot answer it, because a shared object referenced from two places is retained by neither individually.

In practice the top of the dominator tree is usually a collection or a classloader, and expanding it shows what it retains — for instance, a ConcurrentHashMap retaining two million session objects.

Q111. "What really happens during a stop-the-world pause? What is a safepoint?"

Reveal answer

The real test Whether you know pauses have a coordination cost before the GC does any work at all.

Strong answer To move objects or scan the object graph safely, the JVM needs every application thread standing still at a point where it knows precisely which registers and stack slots hold object references. Such a point is a safepoint.

The JVM cannot interrupt a thread at an arbitrary instruction, so instead it sets a global flag, and compiled code polls that flag at method returns and at the back edge of loops; each thread parks itself at its next poll.

The pause therefore has two parts: time-to-safepoint — waiting for the slowest thread to reach a poll — and then the actual GC work. A thread stuck in a long counted loop without a poll, or returning from a long native call, delays everyone.

Land it When a "GC pause" looks mysteriously long, I check -Xlog:safepoint first — sometimes the collector was fast and the JVM spent the time waiting for one thread to stop.

Likely follow-ups
"What is a counted loop, and why does it delay safepoints?"

A counted loop is one the compiler can prove has a bounded integer trip count, like for (int i = 0; i < n; i++).

C2 removes the safepoint poll from the back edge of such loops as an optimization, on the assumption the loop will finish quickly.

When n is a billion, that assumption fails and the thread cannot stop until the loop ends, so every other thread sits parked waiting for it.

Since JDK 10 C2 does loop strip mining, controlled by -XX:+UseCountedLoopSafepoints and -XX:LoopStripMiningIter=1000, which splits the loop into chunks of a thousand iterations with a poll between chunks, so this is mostly fixed on modern JDKs.

A long-indexed loop was historically not counted at all and kept its polls, which is why the old advice was "use a long counter".

"How do you actually measure time-to-safepoint in production?"

With -Xlog:safepoint, which prints one line per safepoint operation with two numbers I care about: "Reaching safepoint" is the time-to-safepoint, and "At safepoint" is the time the operation itself took. A healthy service shows reaching times under a millisecond.

If I see 50ms reaching times, one thread was slow to stop, and -XX:+SafepointTimeout -XX:SafepointTimeoutDelay=100 makes the JVM print the names of threads that failed to reach a safepoint within 100ms, which identifies the culprit directly. JFR records the same data as jdk.SafepointBegin events.

I also watch the total safepoint count, because GC is not the only cause — deoptimization, class redefinition, biased-lock revocation on older JDKs, and jstack itself all need safepoints.

"Do ZGC and virtual threads change this picture?"

ZGC still uses safepoints but keeps them short, because the work inside the pause is limited to flipping phase bits and scanning thread stacks; the heavy marking and relocation happen concurrently with per-thread barriers.

Since JDK 16 ZGC has also made thread-stack scanning concurrent, using a stack watermark so a thread only fixes its own frames when it returns to them, which is why the pauses are consistently under a millisecond regardless of thread count.

Virtual threads help differently: a parked virtual thread has no native stack to scan at the safepoint, only a small heap object, so a service with a million virtual threads does not have a million stacks to walk.

What does not change is that a runaway counted loop or a long JNI call still blocks the safepoint for everyone.

"A GC log line says the pause was 12ms but the application observed a 200ms stall. How do you reconcile that?"

The GC log reports the time the collector spent inside the pause, not the time the application was stopped. Three things live outside that number. Time-to-safepoint, which I read from -Xlog:safepoint.

Page faults when the JVM touches newly committed heap for the first time, which -XX:+AlwaysPreTouch eliminates.

And the operating system: if the container is CPU-throttled by its cgroup quota, the GC threads themselves get descheduled mid-pause, so a 12ms pause of work spreads over 200ms of wall clock. I check nr_throttled in the container's cpu.stat for that.

A fourth cause is the log write itself blocking on a slow disk, which is why I log to local disk and ship asynchronously, or use -Xlog:async on JDK 17 and later.

Q112. "A minor GC doesn't scan the old generation — but an old object might hold the only reference to a young one. How does the collector not miss it?"

Reveal answer

The real test Card tables and write barriers — the piece most candidates have never had to articulate.

Strong answer The JVM tracks old-to-young pointers with a card table.

The old generation is divided into small "cards" of 512 bytes each, and every time the program stores a reference into an object, a tiny piece of compiler-injected bookkeeping code — a write barrier — marks the card containing that object as dirty.

During a minor GC the collector scans only the dirty cards for references into the young generation and treats those references as extra roots, instead of scanning gigabytes of old generation.

G1 generalizes this into per-region remembered sets — each region keeps a summary of which outside cards point into it, so any subset of regions can be collected independently.

The price is a couple of instructions on every reference store, paid by all application threads all the time.

Land it The write-barrier tax is the deal that makes generational and regional collection possible — you pay a little on every pointer store to avoid scanning the whole heap on every young collection.

Likely follow-ups
"How expensive is the write barrier, concretely, and does it differ between collectors?"

For Parallel and Serial the barrier is a single store of a byte into the card table — two or three instructions, no branch, cheap enough to be invisible.

G1's barrier is heavier because it maintains remembered sets: it filters out stores within the same region and stores of null, then enqueues the card into a per-thread dirty-card buffer for concurrent refinement threads to process, which is closer to a dozen instructions and a branch.

ZGC and Shenandoah use load barriers instead, on reference reads, which are more frequent than writes but each is a test-and-branch on a mask. Generational ZGC adds a store barrier too.

Measured throughput differences across collectors are typically 5 to 15 percent, and the barrier is a large part of that gap.

"What are G1's remembered sets, and why can they become a memory problem?"

A remembered set is the per-region list of cards elsewhere in the heap that hold references pointing into that region. When G1 evacuates a region it only needs to scan those cards for roots, not the whole heap.

The problem is the size: a popular old region referenced from thousands of places has a huge remembered set, and before JDK 18 those sets were built up eagerly for all old regions, sometimes consuming 10 to 20 percent of the heap in bookkeeping.

JDK 18 changed this so remembered sets are only maintained for regions that are candidates for the next mixed collection, cutting the overhead substantially.

I can see the cost with -Xlog:gc+remset*=trace, and a service with very large interconnected object graphs is the one that pays for it.

"Why 512 bytes for a card? What is the trade-off in that number?"

A card is the unit of "something in here may have changed".

Smaller cards mean the collector scans less memory per dirty card but the card table is larger — one byte per 512 bytes of heap is a 0.2 percent overhead, which is acceptable; one byte per 64 bytes would be 1.6 percent and thrash the cache.

Larger cards mean fewer table bytes but more wasted scanning, because a single reference store dirties the whole card and the collector must then examine every reference in those 512 bytes.

There is also false sharing on the barrier: two threads storing into objects in the same card write the same card-table byte, which bounces the cache line. -XX:+UseCondCardMark checks the byte before writing it to avoid this on highly parallel workloads.

"How would you verify that card scanning is what makes your young pauses slow?"

The phase breakdown in -Xlog:gc+phases=debug. A G1 young pause is split into named phases: Ext Root Scanning, Update RS or Merge Heap Roots, Scan RS or Scan Heap Roots, Object Copy, and Termination.

If Scan Heap Roots or Merge Heap Roots dominates, the pause is being spent on old-to-young references, which means the application writes references into old objects at a high rate — typically a large old-generation cache or queue being updated per request.

If Object Copy dominates, the issue is simply too much live data in the young generation. Ext Root Scanning being large points at many threads with deep stacks or a huge number of classes with static references.

Each phase points to a different fix, which is why I never tune from the total pause time alone.

Q113 · Scenario. "Your service's minor GCs are quick, yet the old generation fills within hours and a full GC runs daily. Profiling shows almost all allocations are short-lived request objects. What is happening and how do you fix it?"

Reveal answer

The real test Premature promotion — recognizing that short-lived objects can still end up in the old generation.

Strong answer This is premature promotion. Promotion is the copy of an object from the young generation to the old one, which normally happens after it survives enough minor GCs — the tenuring threshold, at most 15 — or immediately when the survivor spaces overflow.

Short-lived objects get promoted anyway in two situations: the young generation is so small that minor GCs fire every few hundred milliseconds, so an object alive for one second "ages" through many GC cycles despite being young in wall-clock time; or an allocation burst overflows the survivor spaces and the overflow is dumped straight into the old generation. Diagnosis, in order:

  1. Turn on -Xlog:gc+age=trace and read the tenuring distribution — it shows how many bytes survive to each age, and whether survivors are being cut off early by "new threshold" messages.
  2. Watch the promotion rate: old-generation occupancy growth between collections in jstat -gcutil or the GC log, correlated with request rate.
  3. Fix by giving the young generation room — with G1, usually raising the whole heap and letting the adaptive sizing breathe; with Parallel, sizing -Xmn up — so objects get time to die in eden.
  4. Also check for allocation spikes and, on G1, for humongous allocations, which skip the young generation entirely.

Prevention: track promotion rate as a first-class metric, because it is the leading indicator of full GCs.

Land it When young-at-heart objects flood the old generation, cheap minor GCs turn into expensive full ones — you fix the front of the pipeline, not the full GC itself.

Likely follow-ups
"You raised the heap and gave the young generation room, and the daily full GC still happens. What next?"

Then the premise was wrong, and something genuinely long-lived is being created. I go back to the evidence in a different way: a heap dump taken just before the full GC, compared against one taken just after.

If the after-dump is much smaller, the promoted objects really were dead and the collector is simply not running mixed collections early enough — I check -XX:InitiatingHeapOccupancyPercent and whether G1's adaptive IHOP is being confused by a bursty pattern.

If the after-dump is nearly the same size, the objects are still reachable, and this is a slow leak wearing a promotion costume. Then the dominator tree tells me the owner.

The distinguishing question is always the same: after the full GC, did the memory come back?

"What is the tenuring threshold exactly, and would you ever set it manually?"

It is the number of young collections an object must survive before promotion, capped by -XX:MaxTenuringThreshold, whose maximum is 15 because the age lives in four bits of the object header.

The JVM adapts the actual threshold each collection: if survivor space is at more than -XX:TargetSurvivorRatio, 50 percent by default, it lowers the threshold so the overflow is promoted rather than copied around. I set it manually in two cases.

For a service where I know almost everything dies within two collections, lowering it to 2 or 3 cuts copying cost with no downside. For a batch job where objects are all long-lived, setting it to 1 or 0 promotes immediately and avoids pointless copying. Otherwise I leave it adaptive and fix the young-generation size instead.

"Does this problem exist with ZGC?"

In generational ZGC, yes, with the same shape: young collections promote survivors to the old generation after they reach a tenuring age, and medium-lived objects still get promoted and then die in the old generation, making old-generation marking cycles more frequent than they should be.

The difference in consequence is significant, though: a ZGC old-generation cycle is concurrent, so the cost shows up as GC CPU and heap headroom consumption, not as a multi-second pause.

If allocation outruns the collector I see "Allocation Stall" lines, which is the ZGC equivalent of pain. ZGC also sizes its young generation automatically and adaptively, so the fix is usually more heap and, as always, allocating less of the medium-lived data in the first place.

"Show me the exact log lines you would read for the tenuring distribution."

With -Xlog:gc+age=trace each young collection prints a block like "Desired survivor size 67108864 bytes, new threshold 15 (max threshold 15)" followed by one line per age: "age 1: 12,345,678 bytes, 12,345,678 total", "age 2: 3,456,789 bytes, 15,802,467 total", and so on.

Healthy is a steep drop between age 1 and age 2, meaning most survivors of one collection die before the next.

The bad signs are "new threshold 1" or "new threshold 2", which means survivor space overflowed and the JVM is promoting early, and a flat distribution where age 5 holds nearly as many bytes as age 1, which means the objects are not dying on the young timescale at all.

Those two shapes have different fixes: bigger survivors for the first, less medium-lived allocation for the second.

Q114. "Strong, soft, weak, phantom references — give me one concrete production use for each."

Reveal answer

Strong answer A strong reference is the normal kind — the object stays alive while any strong path from a GC root reaches it; every field and variable is one.

A soft reference is cleared only when the JVM is under memory pressure, so its textbook use is a memory-sensitive cache that shrinks instead of causing an OutOfMemoryError — with real caveats I would flag.

A weak reference is cleared at the very next collection once no strong references remain; the canonical use is WeakHashMap for attaching metadata to objects you do not own, so your map never keeps them alive — it is also how ThreadLocal keys work.

A phantom reference never lets you retrieve the object at all; it is enqueued after the object is unreachable, which makes it the right hook for scheduling cleanup of native resources once the object is truly dead — it is the machinery underneath java.lang.ref.Cleaner.

the four reference strengths, with a real use for eachruns offline
// STRONG — the default. Collected only when unreachable.
var config = new Config();

// SOFT — cleared at the GC's discretion, but only when memory is tight.
// USE: a memory-sensitive cache you would rather keep than recompute.
// WARNING (see Q115): the JVM clears them only when close to OOM, so under
// pressure it does a full GC, clears them, and immediately refills the cache.
// You get GC thrash rather than graceful degradation. Prefer a bounded
// cache with an explicit size — Caffeine — over SoftReference.
SoftReference<byte[]> thumbnail = new SoftReference<>(render());

// WEAK — cleared as soon as no strong reference remains, at the next GC.
// USE: metadata keyed by an object whose lifetime you do not control.
// This is what WeakHashMap and ThreadLocal's internal map use.
WeakReference<Session> ref = new WeakReference<>(session);
Session s = ref.get();          // may be null at ANY time -- always null-check

// PHANTOM — get() ALWAYS returns null. Its only purpose is to be enqueued
// after the object is finalized, so you can run cleanup deterministically.
// USE: releasing a native resource. This is what replaced finalize().
// In practice, use Cleaner, which wraps exactly this:
private static final Cleaner CLEANER = Cleaner.create();

class NativeBuffer implements AutoCloseable {
    private final long addr;
    private final Cleaner.Cleanable cleanable;

    NativeBuffer(long size) {
        this.addr = malloc(size);
        long a = this.addr;                     // MUST NOT capture `this`,
        this.cleanable = CLEANER.register(this, // or the object is never collectable
                                          () -> free(a));
    }
    @Override public void close() { cleanable.clean(); }   // deterministic path
}

The Cleaner comment is the trap. If the cleanup lambda captures this, the registered object is strongly reachable from the cleaner and can never become phantom-reachable — so the cleanup never runs, which is the opposite of what was intended.

Land it The senior distinction is when each is cleared: weak at the next GC, soft only under pressure — which is precisely why soft references make dangerous caches.

Likely follow-ups
"What is a ReferenceQueue for, and when do you need one?"

A ReferenceQueue is where the collector enqueues a reference object after clearing it, so the program can find out that the referent is gone.

Without it, the only way to notice is to poll get() and see null, which is fine for a cache lookup but useless for cleanup.

With it, a thread calls queue.remove(), receives the cleared reference object, and does whatever housekeeping it needs — removing the entry from a map, closing a native handle.

WeakHashMap uses one internally to expunge stale entries on access, and Cleaner is essentially a phantom reference plus a queue plus a daemon thread that drains it.

The design rule is that the reference object must carry the information needed for cleanup, because by the time it is dequeued the referent is unreachable.

"Why must a Cleaner's cleanup action not reference the object it cleans?"

Because the cleaner holds the action strongly for as long as it is registered, and if the action captured the object — a lambda that calls this.close(), or a non-static inner class — then the object is reachable through the action, the action is reachable through the cleaner, and the object can never become phantom-reachable.

The cleanup would simply never run and the resource would leak forever, silently. The correct shape is a static nested class holding only the raw resource, such as a native pointer or a file descriptor, registered with cleaner.register(obj, new State(handle)).

IDEs and static analysis tools flag a capturing lambda here, and I would check for it in review because it is the one mistake that defeats the whole mechanism.

"WeakHashMap keys are weak, but are the values? What is the classic bug?"

Values are strong. The classic bug is a value that references its own key: map.put(widget, new Metadata(widget)).

The entry holds the value strongly, the value holds the widget strongly, so the widget is always reachable and the weak key never clears — the map leaks exactly the objects it was supposed to release.

The fix is to make sure values do not reference keys, or to store a WeakReference to the key inside the value if the value truly needs it. The same trap exists in ThreadLocal: the key is weak, the value strong.

Also worth knowing: WeakHashMap uses equals and hashCode, so a key type with value equality gets deduplicated in ways that may surprise you; for identity semantics I pair a weak map with identity keys or use Caffeine's weakKeys().

"What does the collector actually do with reference objects during a cycle, and can that be slow?"

Reference processing is a distinct phase after marking.

The collector discovers every reference object whose referent was not strongly reached, decides by type — soft references are kept or cleared by the LRU policy, weak references are cleared, phantom references are enqueued — and then, for cleared ones, appends them to their queues.

With hundreds of thousands of references this phase can dominate a pause; I have seen it add tens of milliseconds to G1 young pauses on a service that wrapped every cache entry in a SoftReference.

The log shows it under -Xlog:gc+ref=debug, with counts per type and time spent, and -XX:+ParallelRefProcEnabled, on by default since JDK 17, spreads the work across GC threads. Cutting the count of reference objects is the real fix.

Q115 · Scenario. "You built a cache on SoftReference. Load tests were fine, but in production the service alternates between long GC pauses and a suddenly cold cache. Explain the behavior."

Reveal answer

The real test Whether you have seen the failure mode, not just the Javadoc promise.

Strong answer Soft references are cleared only under memory pressure, so this cache has no working eviction until the heap is nearly full. Three things then go wrong together.

First, the collector must still trace all those soft-reachable objects on every cycle, so as the cache swells toward the heap limit, GC cycles get longer and run closer together — the long pauses.

Second, when pressure finally peaks, the JVM clears soft references in bulk, so the cache empties at exactly the moment the system is busiest, because busy is when pressure exists.

Third, the resulting miss-storm hammers the backing store and allocates heavily to refill, recreating the pressure — a self-sustaining oscillation. The clearing policy is one JVM-wide heuristic, -XX:SoftRefLRUPolicyMSPerMB; you cannot tune it per cache or reason about hit rates with it.

The fix is a bounded cache with an explicit policy: Caffeine with maximumSize or maximumWeight, a sensible expiry, and hit-rate metrics, sized from measurement. Prevention: treat any soft-reference cache in a code review as a design smell requiring justification.

Land it A SoftReference cache outsources your eviction policy to the garbage collector, and the collector optimizes for not running out of memory — never for your hit rate.

Likely follow-ups
"You replaced it with Caffeine and the miss-storm still happens at the same time of day. What next?"

Then the oscillation was not caused by the reference type; it is coming from expiry.

If the cache uses a fixed expireAfterWrite and the entries were all loaded in a burst — a restart, a deploy, a nightly refresh — they all expire together, and the backing store gets the same stampede.

I would confirm by charting the eviction count and miss rate with the cache's stats() exposed as metrics, expecting a spike at the same clock time as the load.

The fixes are jitter, adding a random 10 to 20 percent to each entry's lifetime; refreshAfterWrite, so the cache serves the stale value while reloading in the background; and a single-flight loader, which Caffeine's LoadingCache already gives me, so concurrent misses for one key produce one backend call.

"What does -XX:SoftRefLRUPolicyMSPerMB actually mean?"

It is the number of milliseconds a softly reachable object survives per megabyte of free heap since its last access. The default is 1000.

So with 1GB of free heap, an untouched soft reference survives roughly 1000 seconds, about 17 minutes; with 10MB free, it survives 10 seconds.

The "free heap" number is computed after the previous collection, so the policy reacts one cycle late, which contributes to the oscillation: a burst allocates heavily, free heap collapses, the next cycle clears nearly everything, free heap is now large, the refilled cache is protected again, and around it goes.

The setting is global, so tightening it to help one cache also clears every other soft reference in the process, including ones inside libraries you never wrote.

"When would a soft reference be legitimately correct?"

When the thing cached is purely a reconstruction cost with no correctness or latency requirement, the object is large, the number of such references is small, and losing them all at once is harmless.

An example is a decoded image cache in a desktop application, or a compiled regex or parsed template in a tool that runs interactively.

The requirement that makes it wrong is any SLO on the miss path: if a cold cache causes user-visible latency or load on a shared backend, I need eviction I can reason about.

I also insist the count be small, because reference processing during GC scales with the number of reference objects, so a million soft references is a GC cost even before any are cleared.

"How would you size the bounded replacement cache?"

From measurement, not guesswork.

I take a heap histogram or dump under peak load to learn the average retained size of one entry, including its key and value graph — say 4KB. I decide a memory budget for the cache, for instance 15 percent of the heap, and divide: a 4GB heap gives 600MB, which is 150,000 entries, so maximumSize(150_000), or better maximumWeight with a weigher that estimates bytes so variable-size values do not break the budget.

Then I watch the hit rate metric. If it plateaus well below the target at that size, the working set is larger than the budget and I either grow the budget or accept the miss rate.

Caffeine's TinyLFU admission means a cache sized at half the working set often still achieves a high hit rate.

Q116. "Why is finalize() effectively dead, and what replaced it?"

Reveal answer

Strong answer finalize() promised cleanup before collection and delivered problems instead.

There is no guarantee when it runs or that it ever runs, so resources leak until some future GC. It needs at least two collection cycles to reclaim an object — one to discover it and queue the finalizer, one after the finalizer runs.

All finalizers share a single low-priority thread, so one slow finalize() backs up the queue and can itself cause an OutOfMemoryError. Worst, a finalizer can "resurrect" its object by storing this somewhere reachable.

The replacements split the job: try-with-resources gives deterministic, scope-based release and is the real fix — close() runs at a known line, exceptions or not.

Cleaner is the safety net for objects that escape that discipline: you register a cleanup action that deliberately must not reference the object, so resurrection is impossible by construction, and it runs after the object is genuinely unreachable.

Land it Deterministic release beats GC-triggered release every time — Cleaner is the backstop for leaked resources, never a substitute for close().

Likely follow-ups
"What is the current status of finalize in the JDK? Can it be turned off?"

As of Aug 2026, finalize() is deprecated for removal under JEP 421, which shipped in JDK 18, and it remains callable by default but can be disabled at runtime with --finalization=disabled.

With that flag the JVM never runs finalizers, and objects with a finalize method are reclaimed like any other. The JEP's plan is to make disabled the default in a future release and then remove the feature.

To find out whether my process depends on finalization I run with JFR and look at the jdk.FinalizerStatistics event, which lists every class that has a finalizer and how many instances have been finalized — those classes are the ones I would need to migrate to Cleaner or try-with-resources before flipping the flag.

"How does the JDK itself clean up things like FileInputStream now?"

With a Cleaner. Since JDK 9 the core I/O classes stopped using finalize() and instead register a cleanup action holding only the file descriptor, and JDK 12 removed the last of the finalizers in FileInputStream and FileOutputStream.

Direct ByteBuffer instances use the same approach with an internal Deallocator.

The behavior from outside is the same: forgetting to close a stream leaks the descriptor until a GC notices the object is unreachable and the cleaner thread runs the action — which means leaked descriptors accumulate between collections and a "too many open files" error is still possible.

So the change was about safety and predictability, not a license to skip close().

"Why does finalization need two GC cycles, mechanically?"

During the first cycle the collector finds the object unreachable, but because it has a finalizer it cannot reclaim it — the finalizer may need the object.

So the collector puts it on the finalization queue, which is a strong reference, and the object is now reachable again. The single finalizer thread eventually runs finalize().

Only during a later cycle, after the finalizer has run and the queue no longer holds the object, is it discovered unreachable again and reclaimed. Everything the object references gets the same reprieve, so a large graph hanging off one finalizable object survives an extra cycle.

A slow or blocked finalizer thread stretches that gap indefinitely, which is how a finalizer backlog manifests as an OutOfMemoryError with plenty of garbage waiting to be freed.

"When would you register a Cleaner in addition to implementing AutoCloseable?"

When the object wraps a resource whose leak is expensive and I do not fully control the callers — a library type that holds native memory, a GPU handle, a temp file.

The pattern is: implement AutoCloseable so correct callers get deterministic release, and register a cleaner that calls the same release logic as a backstop. The state object records whether close() already ran so the cleanup is idempotent.

I also log or count the cases where the cleaner had to do the work, because each one is a caller who forgot to close, and that metric is how I find the leaks.

What I do not do is rely on the cleaner for correctness: in a server with a large heap, GC may not run for minutes, and a resource leak measured in minutes is an outage.

Drill · Collectors & the performance edges

This group tests whether you can choose a collector from an SLO, explain its mechanics in plain words, and admit what each choice costs.

Q117. "Serial, Parallel, G1, ZGC — what does each optimize for, and how do you actually choose one?"

Reveal answer

The real test Whether you choose from requirements, with the decision table a senior carries in their head.

Strong answer Serial collects with one thread and has the smallest footprint — right for tiny containers and single-CPU sidecars where GC overhead matters more than pauses.

Parallel maximizes throughput: it stops the world and collects with all cores, accepting long pauses — right for batch and offline work.

G1 — Garbage-First, the default since Java 9 — is the balanced choice: it aims at a pause target, 200ms by default, and suits most services on heaps from a few to tens of gigabytes.

ZGC delivers sub-millisecond pauses almost independent of heap size, paying roughly 5–15% throughput and extra memory — right when a tail-latency SLO (service-level objective, the latency promise you make) is strict, or heaps are very large.

My decision line: batch job, Parallel; typical service, G1 defaults; hard p99.9 latency promise or huge heap, generational ZGC; tiny sidecar, Serial.

Land it You pick a collector from the SLO and verify with GC logs under real load — never from fashion.

Likely follow-ups
"Which collector does the JVM actually pick by default, and when does it pick Serial?"

The JVM picks by ergonomics: if it considers the machine a "server-class" machine — at least two CPUs and at least 2GB of memory visible to it — it selects G1; otherwise it selects Serial.

In containers that means a pod limited to one CPU or less than 2GB gets Serial silently, which surprises teams who assumed G1. I check with java -XX:+PrintFlagsFinal -version | grep Use.*GC inside the container image, or jcmd <pid> VM.flags on a running process.

Also relevant as of Aug 2026: on JDK 21 and later the Parallel collector is chosen for nothing by default, ZGC must be requested explicitly with -XX:+UseZGC, and Shenandoah is available in most builds with -XX:+UseShenandoahGC but is never the default.

"What is Shenandoah, and why did you leave it out?"

Shenandoah is the other low-pause collector, developed at Red Hat and included in most OpenJDK builds.

It achieves the same goal as ZGC — pauses in the low milliseconds independent of heap size — with a different mechanism: a load-reference barrier and, historically, a forwarding pointer per object, rather than colored pointers.

It supports compressed oops, which ZGC does not, so it can be a better fit for heaps under 32GB where reference density matters, and it works on 32-bit platforms. It became generational in JDK 24 as an experimental feature.

I left it out because on Oracle's JDK builds it is absent, and in most teams the choice comes down to G1 versus ZGC; but on a Red Hat or Amazon Corretto runtime with a 16GB heap and a tight latency SLO, I would benchmark Shenandoah alongside ZGC.

"How would you run a fair comparison between G1 and ZGC for a service?"

Same build, same container size, same traffic replay, and measure the numbers the SLO actually cares about.

I deploy two canaries behind the same load balancer with identical -Xmx — noting that ZGC wants more headroom, so I also run ZGC with 20 percent more heap as a third variant to be fair to it.

I collect p50, p99, and p99.9 latency from the load balancer, not from the application, because the application cannot observe its own pauses; I collect GC CPU time from -Xlog:gc+cpu; and I collect container CPU and RSS. I run for at least a full daily traffic cycle.

The typical outcome is G1 with lower CPU and higher p99.9, ZGC with a flatter tail and 10 percent more CPU; then the SLO decides.

"What would you pick for a 200MB microservice with 0.5 CPU?"

Serial, and I would set it explicitly with -XX:+UseSerialGC so nobody is surprised. With half a CPU there is no parallelism for G1's concurrent threads to exploit, and G1's remembered sets and refinement machinery cost memory that a 200MB budget cannot spare.

Serial has the smallest footprint and its pauses on a 100MB heap are a few milliseconds — the same order as G1's, without the overhead.

I would pair it with -XX:MaxRAMPercentage=50, -Xss512k, and -XX:TieredStopAtLevel=1 if startup matters more than peak throughput, because C2 compilation also competes for that half CPU. The general rule is that below about two CPUs and two gigabytes, the JVM's own ergonomics reach the same conclusion.

Q118. "Explain how G1 actually works — regions, the collection set, mixed collections, and the pause target."

Reveal answer

Strong answer G1 divides the heap into a few thousand equal regions of 1 to 32MB. A region plays a role — eden, survivor, old, or humongous — so the generations are logical sets of regions scattered across the heap, not contiguous halves.

Concurrent marking runs alongside the application and measures how much garbage each old region holds. Each pause evacuates a collection set: the regions chosen for this cycle, whose live objects are copied out so the regions come back empty.

Young collections evacuate all young regions; mixed collections add the most garbage-laden old regions — that is the "garbage first" idea, because copying a region that is 90% dead reclaims the most memory per millisecond of pause.

The pause target, -XX:MaxGCPauseMillis at 200ms by default, is a goal, not a guarantee: G1 keeps a cost model of past pauses and sizes the collection set and young generation to fit under it.

Land it G1 pays off the old generation in small installments instead of one big bill — it only falls back to a monolithic full GC when it loses the race, and that log line is the one to alert on.

Likely follow-ups
"What starts a concurrent marking cycle in G1, and which flag controls it?"

Old-generation occupancy crossing the Initiating Heap Occupancy Percent.

The flag is -XX:InitiatingHeapOccupancyPercent, 45 by default, but since JDK 9 G1 treats that only as the starting value: with -XX:+G1UseAdaptiveIHOP, on by default, it measures how long marking takes and how fast the old generation fills, and moves the threshold so marking finishes just before the heap runs out.

The log shows the decision as "Pause Young (Concurrent Start)" followed by "Concurrent Mark Cycle" lines.

If I see cycles starting too late — marking still running when a full GC hits — I either give the heap more headroom or set the IHOP lower manually, which switches the adaptive behavior off, and I check whether humongous allocations are forcing cycles early instead.

"How does G1 decide which old regions go into a mixed collection?"

After marking it knows the live bytes in every old region and sorts them by garbage percentage. Regions with less than -XX:G1MixedGCLiveThresholdPercent, 85 percent, live data are candidates — regions that are mostly alive are not worth copying.

It then spreads those candidates across up to -XX:G1MixedGCCountTarget, 8 by default, mixed pauses, taking at least an eighth of the candidates per pause and as many more as fit under the pause target.

Mixed collections stop when the reclaimable space drops below -XX:G1HeapWastePercent, 5 percent, because at that point the remaining garbage is not worth the pause.

So a heap full of 80-percent-live regions is G1's worst case: everything is a candidate, each region yields little, and the copying cost per reclaimed byte is high.

"What happens when G1 misses the pause target badly?"

Nothing dramatic in the moment; the target is advisory. G1 records the overshoot in its cost model and responds on the next cycles by shrinking the young generation, so fewer regions are evacuated per pause, and by putting fewer old regions into each mixed collection.

The side effect is that a smaller young generation means more frequent pauses and more premature promotion, so a target that is set too aggressively, say 20ms on a busy 16GB heap, makes the collector run constantly and can be worse for throughput than a relaxed target.

The honest reading of -Xlog:gc is to look at the pause distribution: if the target is 200ms and the pauses cluster at 190ms, G1 is working hard to hit it, and more heap is a better lever than a tighter target.

"Are regions still capped at 32MB?"

Not for manual settings. By default G1 picks a region size so the heap has roughly 2048 regions, rounding to a power of two between 1MB and 32MB, and the ergonomic choice still stays at 32MB or below.

But since JDK 21 the manual maximum for -XX:G1HeapRegionSize was raised to 512MB, so a very large heap can use bigger regions, which reduces remembered-set overhead and lets larger objects avoid being humongous.

The trade is granularity: bigger regions mean coarser collection sets and more wasted space when a region is partially used.

For most services I let ergonomics choose and override only when the humongous threshold — half a region — is the problem, as in the 20MB buffer scenario.

Q119 · Scenario. "A service allocates a 20MB byte[] per request. On G1 you see constant 'humongous allocation' activity, early concurrent cycles, then full GCs — with the heap only 60% used. Explain it and fix it."

Reveal answer

The real test Humongous allocation mechanics and the honesty to say the real fix is in the application.

Strong answer In G1, any object of half a region or more is humongous: it skips eden entirely and must be placed in contiguous free regions of the old generation.

With an 8GB heap the default region is 4MB, so every 20MB buffer needs five adjacent free regions. Two problems follow.

Fragmentation: after a while plenty of free regions exist but not five in a row, so allocation fails even at 60% occupancy — and G1's escape hatch for that is a full compacting GC. Pressure: humongous allocations also push G1 to start concurrent cycles early, burning CPU. The GC log makes it unmistakable — young pauses tagged with the cause G1 Humongous Allocation, followed eventually by Pause Full (G1 Compaction Pause) lines lasting whole seconds. The fixes, in the order I would apply them:

  1. Confirm with -Xlog:gc*: the cause string "G1 Humongous Allocation" and the region size printed at startup.
  2. Fix the allocation itself — this is the real cure: stream the payload in chunks instead of materializing 20MB, or reuse pooled buffers so the allocation happens once, not per request.
  3. If the object size is irreducible, raise -XX:G1HeapRegionSize=32m: a 20MB array is still humongous against the 16MB threshold, but it now needs one region, not five, which largely defuses the contiguity problem.
  4. Add heap headroom, and alert on humongous allocation rate so it cannot regress silently.

Land it G1's worst enemy is a big contiguous allocation on a hot path — shrink the object first, then grow the region, and treat more heap as the last resort.

Likely follow-ups
"You raised the region size to 32MB and the full GCs stopped, but young pauses got longer. Why?"

Because region size sets the granularity of everything G1 does.

With 32MB regions on an 8GB heap there are only 256 regions, so the young generation is sized in coarse steps and the smallest useful eden is larger than before, which means more live data to copy per pause.

Remembered sets also become coarser: a card that points into a 32MB region is more expensive to scan. And a humongous object that is 20MB in a 32MB region wastes 12MB per allocation, so the heap fills faster with unusable tails.

This is the trade I would state before making the change: region size defuses the contiguity problem, but the real fix is still to stop allocating 20MB per request. If the pauses matter, I would rather stream the payload than keep the larger regions.

"When does G1 reclaim a humongous object — does it wait for a full marking cycle?"

Not necessarily.

Since JDK 8u60, G1 has eager reclaim: at the end of a young pause it checks humongous regions that contain a primitive array — a byte[] or int[], which cannot point to anything — and, if the region's remembered set shows no references into it, frees it immediately without waiting for marking.

That is why per-request byte[] buffers often get reclaimed quickly. An object array or an object with references does not qualify, because G1 cannot cheaply prove nothing inside it matters, so those wait for a marking cycle.

The relevant flag is -XX:+G1EagerReclaimHumongousObjects, on by default, and the log line "Humongous Reclaim" under -Xlog:gc+phases=debug shows how many were freed.

"How do you find which code path is making the humongous allocations?"

A JFR recording with allocation profiling.

The jdk.ObjectAllocationSample event, which is on by default in JDK 16 and later, records the stack trace and size of sampled allocations, and JDK Mission Control's allocation view lets me sort by object size or by allocation outside TLAB — a humongous allocation is by definition outside a TLAB. Filtering for byte[] larger than the humongous threshold gives the exact call sites.

As a cross-check without JFR, async-profiler in allocation mode with --alloc produces a flame graph of allocation sites weighted by bytes, and the 20MB arrays stand out. The number to compare against is the region size printed by -Xlog:gc+heap=debug at startup, halved.

"Would ZGC have this problem?"

Not this one.

ZGC has no humongous concept in the G1 sense: objects above 4MB go into a dedicated large region sized to fit that single object, allocated from virtual address space, so there is no search for contiguous free regions and no fragmentation of the old generation from large arrays.

Large regions are never relocated, only freed as a whole when the object dies.

The remaining cost is that a 20MB allocation per request is 20MB of memory bandwidth to zero and a large region to map and unmap, so the allocation rate would still be high and the young cycles frequent.

So switching collectors would remove the full GCs, but it would not remove the reason to stream the payload instead of materializing it.

Q120. "Explain ZGC at an intuition level — colored pointers, load barriers, and what the sub-millisecond pauses cost."

Reveal answer

The real test An honest mental model — including the throughput bill — without drowning in implementation detail.

Strong answer ZGC does nearly all its work — marking, relocation, reference fixing — while the application keeps running, so its pauses are tiny synchronization points, well under a millisecond even on terabyte heaps. Two ideas make that possible.

Colored pointers: ZGC hides a few metadata bits inside each 64-bit reference, recording essentially "has this reference been examined since the current GC phase began?

" Load barriers: a tiny injected check runs every time the program loads a reference; if the color says the reference is stale — the object may have been moved — the barrier repairs it on the spot, looking up the new address and healing the pointer, then execution continues.

So relocation never needs the world stopped; each thread fixes exactly the references it touches. The honest costs: the barrier taxes every reference load, typically 5–15% throughput plus GC CPU; ZGC wants extra memory headroom to work concurrently; and it cannot use compressed pointers.

The generational ZGC that became the default form recovers much of the throughput gap.

Land it You buy ZGC with CPU and memory when the SLO is a p99.9 pause — if nobody measures your pauses, you are paying for a guarantee nobody asked for.

Likely follow-ups
"Which bits are the colored bits, and how does the CPU tolerate a pointer with metadata inside it?"

On JDK 21 and earlier, ZGC used four metadata bits in the pointer itself, above the 44 address bits — Marked0, Marked1, Remapped, and Finalizable — and relied on multi-mapping: the same physical heap memory was mapped at three different virtual addresses, so a pointer with any color combination was a valid address to the hardware and the CPU never had to strip anything. Generational ZGC changed this: the colored bits moved to the low bits of the pointer, and the load barrier explicitly shifts them away before dereferencing, which removed the multi-mapping and made RSS accounting far simpler — a JDK 21 and earlier ZGC process famously showed three times the heap in some tools. The practical takeaway as of Aug 2026 is that the metadata cost is a shift instruction, not an address trick.

"What happens when the application allocates faster than ZGC can collect?"

An allocation stall. ZGC does not have a stop-the-world fallback; when a thread cannot get memory it blocks in the allocation path until the current cycle frees some, and the GC log prints "Allocation Stall" with the thread name and the wait time.

From the application's perspective this looks like a pause on that specific thread, but not a global one. It means the heap is too small for the allocation rate: the concurrent collector needs enough headroom to complete a cycle before the free memory runs out.

The fixes are more heap, a higher -XX:ConcGCThreads so cycles finish faster at the cost of CPU, or less allocation. I alert on the stall count because a service that stalls under peak load has lost the whole point of choosing ZGC.

"What about memory — why does ZGC want extra headroom and how much?"

Two reasons. During relocation an object exists in both its old and new region until the old one is freed, so the heap needs room for in-flight copies; and the collector works concurrently, so the application keeps allocating during a cycle and that allocation must fit.

The rule of thumb is that ZGC wants the maximum heap to be at least 30 to 50 percent larger than the live set plus one cycle's worth of allocation, whereas G1 is comfortable at about 25 percent headroom.

Generational ZGC reduced this a lot because young collections are cheap and frequent, so the live set in flight is smaller.

I also set -XX:SoftMaxHeapSize to the size I want ZGC to aim for, keeping -Xmx as the emergency ceiling, which gives the collector room to absorb bursts without committing it all.

"How would you measure the throughput cost of the barriers on your own service?"

Not with a microbenchmark; with the CPU counters of the real service.

I run the same traffic against a G1 canary and a ZGC canary and compare total container CPU per request, taken from cgroup cpu.stat, not from the JVM, because the JVM's GC CPU accounting does not include the barrier cost — that is spread across every application thread.

The difference between the two CPU-per-request numbers is the combined cost of barriers plus concurrent GC threads. To separate them, -Xlog:gc+cpu reports the collector's own CPU time, so the remainder is the barrier tax.

On a pointer-heavy service — deep object graphs, many collections — I have seen 10 to 15 percent; on a service that mostly moves bytes, under 5 percent.

Q121 · Scenario. "Your nightly ETL job was switched to ZGC 'because it's newer', and the run went from 40 to 48 minutes. Why, and what should it run instead?"

Reveal answer

Strong answer The job regressed because ZGC optimizes the one thing a batch job does not care about. At 3am nobody observes a pause; the only metric is wall-clock completion, which is throughput.

ZGC charges for its concurrency twice: load barriers tax every reference read the ETL code performs, and concurrent GC threads compete with the job for cores the whole run.

Parallel GC is the opposite trade: stop everything, collect with every core at once, resume — no barrier overhead and the GC work done in efficient batches, which is the highest total throughput per CPU. My steps: confirm in the GC logs how much CPU time GC consumed under each collector; switch to -XX:+UseParallelGC; size the heap generously so full collections are infrequent; re-measure the run time.

G1 with a relaxed pause target is also acceptable, but for pure batch, Parallel usually wins by a few percent more.

Land it Collector choice is an SLO decision, and pauses are free when no one is waiting — so a batch job should spend its CPU on the batch, not on concurrency machinery.

Likely follow-ups
"You switched to Parallel and the run is now 42 minutes, still slower than the original 40. What next?"

Then GC was not the only thing that changed, or Parallel needs sizing.

First I check the GC log with -Xlog:gc* for the total pause time across the run; if it is under a minute, the collector is not the bottleneck and I compare the two deployments for other differences — JDK version, heap size, CPU quota, data volume.

If pause time is several minutes, Parallel is running too many full collections, which means the old generation is too small for the job's working set: I raise -Xmx and set -Xms equal to it, so the JVM does not spend the first ten minutes growing, and I consider -XX:NewRatio=1 so half the heap is young, since a batch job's per-record garbage dies fast.

With Parallel, -XX:ParallelGCThreads should match the container's CPU limit, not the host's core count.

"What flag makes Parallel optimize for throughput rather than pause time?"

Parallel has an adaptive size policy driven by three goals in priority order: a pause goal from -XX:MaxGCPauseMillis, unset by default; a throughput goal from -XX:GCTimeRatio, 99 by default, meaning at most one percent of time in GC; and footprint last.

For a batch job I leave the pause goal unset, because setting it makes Parallel shrink the young generation to hit it, which raises collection frequency and lowers throughput.

If the job is memory-rich I can set -XX:GCTimeRatio=199 to ask for half a percent, and Parallel will grow the generations to achieve it.

And if the adaptive sizing is thrashing — visible as generation sizes bouncing in the log — -XX:-UseAdaptiveSizePolicy with explicit -Xmn makes it predictable.

"Is there a case where ZGC would make the batch job faster?"

Yes, one: when the job's heap is very large and the live set is huge, so Parallel's full collections take minutes each and dominate the run.

A 100GB heap with 60GB of live data means every Parallel full GC marks and compacts 60GB, which at a few gigabytes per second per thread is tens of seconds of wall clock, repeated every time the old generation fills.

ZGC would mark that concurrently while the job continues, so the job pays the barrier tax but never waits.

The crossover point depends on the promotion rate: a job that promotes a lot and dies slowly benefits, a job that streams records and keeps little does not. I would test it, but for the 40-minute job in the question, with a normal heap, Parallel wins.

"How do you explain to the team that 'newer' is not 'better' here without sounding dismissive?"

I frame it as what the collector is designed to spend CPU on.

ZGC is engineered to move work off the critical path of request threads and onto concurrent GC threads plus a per-load barrier, which is a great deal when someone is waiting on a request.

A batch job's critical path is the whole job, so moving GC work off it is impossible — every cycle of GC CPU is a cycle the job does not get, and the barriers are pure overhead.

Then I show the numbers: the -Xlog:gc+cpu totals under each collector, and the CPU-per-record figure. Making the decision visible in a small table, with the SLO written at the top, is what turns "newer versus older" into "which one matches this workload's requirement".

Q122 · Scenario. "GC is eating 15% of CPU, pauses meet the SLO, there is no leak — and the team is three days deep into tuning exotic flags. What do you check before touching another flag?"

Reveal answer

The real test Whether you know when the boring answer — more heap — is the correct senior answer.

Strong answer I check headroom first, because GC cost is driven by how often collections must run, and that is allocation rate divided by free space. The steps:

  1. Read the GC log and find the live set — the occupancy right after full or mixed collections, the floor of the sawtooth pattern heap usage draws.
  2. Compare it to -Xmx. If the live set is 3GB in a 4GB heap, the collector is running continuously to recycle a 1GB working band — no flag fixes that arithmetic.
  3. Raise -Xmx (and the container limit with it) so the heap is roughly 2.5 to 4 times the steady live set, then re-measure GC CPU share; doubling the free band roughly halves collection frequency at the same allocation rate.
  4. Only if generous headroom still is not enough do I reach for flags — and then targeted ones justified by the logs, not folklore.

The economics matter in the answer: memory is one of the cheapest resources we buy, while engineer days and the operational risk of a bespoke flag soup are expensive and permanent.

Land it The most effective GC tuning flag ever shipped is -Xmx — headroom first, exotic flags only after the logs prove headroom was not the problem.

Likely follow-ups
"You doubled -Xmx and GC CPU only dropped from 15 to 12 percent. Why so little, and what next?"

Then the cost is not dominated by collection frequency, and I look at what each collection is spending time on. Two usual causes.

First, the live set is large and mostly old, so each cycle's marking cost is proportional to live data, not free space — doubling the heap halves the frequency of old cycles but each is just as expensive, and with G1 the concurrent marking threads are the CPU consumers.

Second, the young pauses are dominated by copying a large survivor population, which more heap does not shrink. So I read -Xlog:gc+phases=debug to split the time, and I take a JFR allocation profile.

If the live set is the driver, the fix is holding less in memory — smaller caches, fewer retained objects per request. If copying is the driver, the fix is reducing medium-lived allocation.

"What is the relationship between allocation rate, heap headroom, and GC frequency, in numbers?"

Young-collection frequency is allocation rate divided by eden size, and old-collection frequency is promotion rate divided by old-generation free space.

Concrete: a service allocating 400MB per second with a 1GB eden collects every 2.5 seconds; if each young pause copies 50MB of survivors at roughly 1GB per second per thread, that is 50ms of GC work per pause, or 2 percent of wall-clock time on one thread.

Double eden and it becomes 1 percent. For the old generation, promoting 5MB per second into 2GB of free space means an old cycle every 400 seconds; with 500MB free it is every 100 seconds, four times the marking cost.

That is the arithmetic behind "headroom first": every doubling of free space halves the cycle count at constant per-cycle cost.

"When is more heap the wrong answer?"

When the extra heap will be used to hold more garbage that must then be traced, or when the container budget cannot afford it. A heap that is already at 31GB has the compressed-oops cliff in front of it, so going to 40GB may hold less.

A heap that runs on a node with other pods may steal memory from them, which trades my GC CPU for their eviction.

And with G1, a larger heap means longer full GCs if one does happen, so the worst case gets worse even as the average gets better.

More heap is also the wrong answer if the 15 percent is caused by a leak, because the leak will fill the new headroom on a slightly longer timer. That is why the first step is confirming the post-GC floor is flat before buying memory.

"Give me one exotic flag that was actually justified by logs in your experience."

-XX:+ParallelRefProcEnabled on JDK 11, before it became the default in JDK 17.

The GC log with -Xlog:gc+ref=debug showed reference processing taking 40 to 60ms of every young pause on a service that used a large number of WeakReference objects inside a third-party cache, and that phase was running on a single thread.

Enabling parallel reference processing dropped it to under 10ms on an 8-core box, and the flag was justified by one specific log line, tested on a canary, and documented with that line in the runbook.

That is the standard I hold: a flag needs a phase in the log that it demonstrably shortens. A flag that "makes GC better" with no measurement attached gets removed at the next JDK upgrade.

Q123. "What are escape analysis and scalar replacement — why do people say small allocations are sometimes free?"

Reveal answer

Strong answer Escape analysis is a proof the JIT — the just-in-time compiler that turns hot bytecode into machine code — runs on a compiled method: does this object ever escape, meaning get stored into a field, passed to code that might keep it, or handed to another thread?

If it provably never escapes, the JIT applies scalar replacement: the object is never allocated at all — its fields are broken apart into plain local variables living in registers, so a new Point(x, y) used only inside the method dissolves into two integers.

That is why "allocation is free" is sometimes literally true: there was no allocation. The catch is fragility: if any code path lets the object escape, or a call in between is not inlined, the optimization silently switches off.

So I do not contort code to avoid small short-lived objects on faith — I check with an allocation profiler such as async-profiler in allocation mode.

Land it Write the clear version, let the JIT delete the allocations it can prove away, and let the profiler — not folklore — tell you where allocation actually costs something.

Likely follow-ups
"What are the common things that make an object escape when the developer thinks it doesn't?"

The usual culprits: passing the object to a method that was not inlined, because C2 cannot see inside a call it did not inline and must assume the callee kept the reference; storing it into any field, even of another local object, because that other object may escape; capturing it in a lambda that gets stored or passed along; throwing it, since exceptions are stored in the thread's state; and synchronizing on it, which on older JDKs forced it to be a real object with a header. Also, any object that reaches a loop with a merge point where it might or might not be the same object — C2's escape analysis is control-flow sensitive but gives up on complex merges. The inlining limit is the big one: a method above -XX:FreqInlineSize of 325 bytecodes will not inline, and everything passed into it escapes.

"How would you verify that scalar replacement actually happened for a given method?"

The direct evidence is an allocation profile: with JFR's jdk.ObjectAllocationSample or async-profiler's allocation mode, a scalar-replaced allocation site simply does not appear, because no allocation happens. The indirect evidence is the JIT's own output: -XX:+UnlockDiagnosticVMOptions -XX:+PrintEscapeAnalysis -XX:+PrintEliminateAllocations prints each allocation C2 eliminated with its bytecode index.

For a JMH benchmark, -prof gc reports the normalized allocation rate per operation, and a value of zero bytes per operation means the object was scalar replaced.

The quickest sanity check in a real service is a heap histogram: if a class I expect to be allocated millions of times per second shows only a handful of instances, the JIT is removing it.

"Does escape analysis remove the object in the interpreter or C1?"

No, only C2 performs it. The interpreter allocates everything; C1 does trivial inlining but no escape analysis, so a method running at tier 3 allocates every object it creates. That has two practical consequences.

A cold method — one below the C2 threshold — pays full allocation cost even for objects that would be eliminated when hot, which is fine because cold code by definition does not allocate much.

And during warmup, allocation rate is much higher than at steady state, which is part of why GC activity is heavier in the first minute after a deploy.

It also means that a deoptimization of a hot method briefly reintroduces allocations that had been eliminated, which shows as a small blip in the allocation profile.

"Is this related to Valhalla value classes?"

Yes, they attack the same cost from the other side. Escape analysis is a compiler proof that a particular object does not need an identity at a particular site, and it is fragile because the proof fails as soon as the object crosses a non-inlined boundary.

Project Valhalla's value classes declare at the type level that the object has no identity — no synchronized, no identity ==, no mutation — which lets the JVM flatten it into its containing object or array and pass it in registers without needing any proof.

As of Aug 2026 value classes are in preview, under JEP 401, so I do not use them in production code, but the direction is that a Point or Money type will stop depending on the JIT's mood to be allocation-free.

Q124. "What are compressed oops, and what is the 32GB cliff people warn about?"

Reveal answer

Strong answer "Oops" are ordinary object pointers — the JVM's internal references between objects.

On a 64-bit JVM a raw pointer is 8 bytes, but Java heaps are dense with references, so the JVM compresses them: because objects are aligned on 8-byte boundaries, a 32-bit number can address 4 billion times 8 bytes — 32GB — so any heap under about 32GB can store references as 32-bit offsets, roughly halving reference overhead and improving cache behavior.

The cliff: set -Xmx past the limit and compression switches off, every reference doubles to 8 bytes, and a 36GB heap can hold less live data than a 31GB one while collecting more.

So the sizing rule is binary: stay at 31GB or below, or jump well past — 48GB and up — so the extra space outweighs the fatter pointers.

-Xlog:gc+heap+coops at startup tells you which mode you got; ZGC is the exception, as it never uses compressed oops.

Land it Heap sizing near the boundary is all-or-nothing: 31GB or go big — a 33GB heap is the worst of both worlds.

Likely follow-ups
"What is the difference between zero-based and non-zero-based compressed oops?"

Compressed oops decode a 32-bit offset into a 64-bit address by shifting it left by 3 and adding the heap base.

If the JVM can reserve the heap at a low virtual address so that the base is zero, the add disappears and decoding is a single shift — that is zero-based mode, available when the heap fits below the 32GB boundary of the address space.

Below about 4GB the JVM can even skip the shift, so a reference is used raw. When the heap must sit at a higher address, non-zero-based mode adds the base on every decode.

It is a small cost, but on a pointer-heavy workload it is measurable, and -Xlog:gc+heap+coops tells me which mode I got: "Zero based" is what I want, and a large -Xmx or address-space pressure from other mappings can lose it.

"Can you push the cliff past 32GB?"

Yes, with -XX:ObjectAlignmentInBytes=16, which aligns objects on 16-byte boundaries so the 32-bit offset addresses 64GB.

The trade is padding: every object is rounded up to a multiple of 16 bytes instead of 8, so small objects waste more space — a 24-byte object becomes 32 bytes — and on a heap full of small objects the padding can eat much of what compression saved.

It is a reasonable choice for a heap between 32GB and 48GB where the alternative is uncompressed 8-byte references, and I would measure the actual live-set size in both configurations with a heap histogram before committing.

Above 64GB the same arithmetic applies with alignment 32, but at that point the padding cost usually makes plain 64-bit references the better deal.

"How much does compression actually save on a typical heap?"

A typical enterprise heap is roughly 30 to 40 percent references by volume — object headers, collection nodes, fields pointing to other objects.

Halving those from 8 to 4 bytes saves 15 to 20 percent of the heap, and the class pointer in every object header is also compressed, saving another 4 bytes per object.

With JDK 25's compact object headers, enabled by -XX:+UseCompactObjectHeaders and made a product feature under JEP 519, the header drops from 12 to 8 bytes, which stacks with compressed oops.

Beyond raw size, smaller references mean more objects per cache line, so throughput improves by a few percent on pointer-chasing code. That is why the same live set at 31GB can outperform the same data at 40GB with compression off.

"Does ZGC's lack of compressed oops make it a bad fit for small heaps?"

It is a cost, and it is honest to say so.

On a 4GB heap running ZGC, references are 8 bytes, so the same data occupies roughly 15 percent more memory and touches more cache lines than under G1 — and generational ZGC's colored pointers are the reason it cannot compress them, since the metadata bits need the full 64-bit word.

For a small-heap service with a strict tail-latency SLO it can still be the right choice, because G1's pauses on a 4GB heap are already modest and the question is whether the last few milliseconds matter. ZGC does still compress class pointers in headers.

If both memory and pauses matter on a small heap, Shenandoah is the low-pause collector that keeps compressed oops.

Q125. "What does -XX:+UseStringDeduplication do, and when would you actually enable it?"

Reveal answer

Strong answer With G1, this flag runs a background task that finds String objects whose backing character arrays hold identical content and quietly rewires them to share a single array — safe because strings are immutable, and applied only to strings that have survived a few collections, so temporaries are not churned.

It pays off when the heap genuinely carries duplicate string data, which is common in servers holding parsed JSON, XML, or database rows: string data is often a quarter of the heap, and measured duplication in typical enterprise heaps runs around 10–15%.

Before flipping it I measure: a heap dump histogram or MAT's duplicate-strings query shows the real duplication, and -Xlog:stringdedup*=debug reports bytes saved once enabled.

It is different from String.intern(), which is manual, deduplicates whole String objects through a global table, and becomes a maintenance liability — deduplication shares only the arrays, automatically.

Going deeper One update to the "with G1" framing: string deduplication started as a G1-only feature under JEP 192 in JDK 8u20, but JDK 18 extended it to Serial, Parallel, and ZGC, and Shenandoah supports it too, so as of Aug 2026 the flag works with every collector.

The mechanism is the same everywhere: when an object is promoted or reaches -XX:StringDeduplicationAgeThreshold, 3 by default, the collector queues candidate strings, and a background thread hashes their byte arrays, looks them up in a deduplication table, and rewrites the string's value field to the shared array.

The savings come from Latin-1 compact strings being small; a heap of parsed JSON where every record repeats the same field names and enum values is where I have seen 5 to 10 percent of heap come back.

It is not the same as interning: two deduplicated strings are still distinct objects, so == is still false.

Land it Measure duplication in a real heap dump first, then enable the flag when the savings are demonstrated — it is nearly free CPU-wise, but it is not a default for a reason.

Likely follow-ups
"How exactly do you measure duplication in a heap dump before enabling it?"

In Eclipse MAT, the histogram already tells me how much of the heap is byte[] held by strings — I open the histogram, find java.lang.String, and look at its retained size.

Then I run the "Group by value" query on java.lang.String, which groups all string instances by content and reports the count per distinct value; sorting by count shows the top duplicated values and, with the size column, how many bytes the duplicates cost.

MAT also ships a "Duplicate Strings" leak-suspect report under the Java Collections queries. If the total wasted bytes are 5 percent of the heap or more, the flag will pay for itself; if it is under 1 percent, I skip it.

I also note which values are duplicated, because a field name repeated a million times is a hint that the parser could intern them itself.

"What is the runtime overhead of leaving it on?"

Small but nonzero. The background deduplication thread consumes CPU proportional to the promotion rate, since every string that survives to the age threshold is a candidate; on a service that promotes little, that is a fraction of one percent of a core.

The deduplication table itself is native memory, sized by the number of distinct strings, which can be tens of megabytes on a heap with millions of unique values.

And there is a subtle effect: the shared byte arrays live in the old generation and are referenced from many strings, so they become popular objects with large remembered sets under G1.

I enable it, watch -Xlog:stringdedup*=debug for the reported savings and the table size for a day, and keep it only if the bytes saved are worth the overhead measured.

"When would you fix the duplication in code instead of with the flag?"

When the duplication has a single obvious source I control.

If a JSON parser is creating a fresh string for the same twenty field names on every record, I configure the parser to intern field names — Jackson has JsonFactory.Feature.INTERN_FIELD_NAMES, on by default, and canonicalization for values — so the duplicates are never created, which saves allocation as well as memory.

If a database result set produces the same status codes millions of times, I map them to an enum at the boundary. The flag deduplicates after the fact and only saves memory; a code fix saves allocation, GC work, and memory.

I use the flag for the diffuse case where duplication is spread across many libraries and no single fix would cover it.

Drill · Every flavour of OutOfMemoryError

Each OutOfMemoryError message names a different exhausted resource — these scenarios test whether you can read the message, name the resource, and run the right diagnosis instead of reflexively raising -Xmx.

Q126 · Scenario. "You are paged at 4am: java.lang.OutOfMemoryError: Java heap space. How do you tell a leak from an undersized heap?"

Reveal answer

The real test The trend-based diagnosis — juniors guess, seniors read the post-GC floor.

Strong answer The message means a collection just ran and the heap still could not fit an allocation. That has exactly two causes — the live set has grown without bound (a leak), or the workload legitimately needs more than -Xmx (undersized) — and the trend tells them apart:

  1. Pull the GC logs, or jstat -gcutil history if you have it, and chart occupancy immediately after each full GC — the floor. That floor is the truth signal; peak usage is noise.
  2. Undersized looks like a floor that is high but flat, tracks traffic, and drops when load drops — the service simply needs a bigger working set than it was given.
  3. A leak looks like a floor that ratchets upward monotonically regardless of traffic, with each full GC reclaiming less than the last.
  4. Make sure the death leaves evidence: run permanently with -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps, so the 4am crash writes the heap dump you will analyze at 10am.
  5. If undersized: raise -Xmx and the container limit together and capacity-plan. If leaking: the dump goes into the MAT workflow I would walk through separately.

Prevention: alert on the post-full-GC occupancy trend, not on instantaneous heap usage, which crosses any threshold you pick during normal operation.

Land it One heap dump at the moment of death plus a week of GC logs answers this question in an hour — without them, everyone in the incident channel is guessing.

Likely follow-ups
"The dump on OOM never got written — the pod just restarted. What went wrong and what do you change?"

Three usual causes. The dump path was inside the container's ephemeral filesystem, so the file was written and then lost with the pod — the fix is a persistent volume or an emptyDir with a sidecar that uploads it.

The disk had no room, because a heap dump is roughly the size of the used heap, so a 4GB heap on a 2GB volume fails silently — I size the volume at heap size plus headroom.

Or the liveness probe killed the pod while the dump was being written, since writing 4GB can take a minute during which the JVM is paused — I lengthen the probe's failure threshold or set terminationGracePeriodSeconds generously.

I verify the whole path by deliberately triggering an OOM in staging and confirming the file lands where the runbook says it does.

"The floor is high and flat, so you called it undersized and raised -Xmx. A week later the same error. Now what?"

Then the working set grew with the new limit, which means it scales with something I did not account for — usually the number of connections, sessions, or cached items, which grew because the service now had room.

I go back to the floor chart and this time correlate it with a business metric: active users, queue depth, cache size.

If the floor tracks the cache size, the cache has no bound, and it is a leak with a bound set by heap size rather than by policy.

If it tracks connections or sessions, something per-connection is retained past its lifetime, and I take a dump and look at the dominator tree for the per-connection object count against the actual connection count.

The tell is that a truly undersized heap has a floor that tracks traffic and drops overnight; this one did not drop.

"What does the alert on the post-GC trend look like in a real monitoring stack?"

With Micrometer and Prometheus, the gauge is jvm_memory_used_bytes filtered to the old-generation pool — G1 Old Gen or ZGC Old Generation — and the trick is to sample it at the right moment.

Micrometer's JvmGcMetrics updates jvm_gc_live_data_size_bytes only after a collection that reclaims old-generation space, which is precisely the floor. The alert is a linear regression: predict_linear(jvm_gc_live_data_size_bytes[6h], 24*3600) > jvm_gc_max_data_size_bytes * 0.9 fires when the trend would reach 90 percent of the maximum within a day.

That fires days before the error and stays quiet during normal sawtooth. I pair it with a simple alert on any full GC count increment for the fast-moving case.

"Would a live-object heap dump lose evidence compared to a full dump?"

Sometimes. jcmd GC.heap_dump with the default -all=false forces a full collection and writes only reachable objects, which is what I want for a leak, because unreachable objects are by definition not the leak.

But for a different question — why was so much garbage produced, or what was that object that is now dead — the unreachable objects are the evidence.

Two cases where I use -all=true: diagnosing a high allocation rate where I want to see the shapes of the short-lived objects, and a suspected finalizer or reference-queue backlog, where objects are unreachable but not yet reclaimed.

The dump written by -XX:+HeapDumpOnOutOfMemoryError is always a live dump after the failed collection, so it is the right one for the 4am question.

Q127 · Scenario. "The log says OutOfMemoryError: GC overhead limit exceeded. What is the JVM actually telling you?"

Reveal answer

Strong answer It is telling me the process was dying by inches and the JVM chose a mercy kill.

The rule behind the message: the JVM was spending more than 98% of its time in garbage collection while recovering less than 2% of the heap, across several consecutive collections.

That happens when the heap is almost entirely live objects — the collector runs back to back, scavenges crumbs, the application makes nearly no progress, and without this check the service would limp for hours at one percent throughput, timing out every request while technically "up".

So the JVM throws early to give you a clean failure with a stack trace while the process can still write one.

The diagnosis fork is identical to Java heap space — it is the same disease caught at an earlier stage: read the post-full-GC occupancy trend to separate leak from undersized heap, and capture the dump with -XX:+HeapDumpOnOutOfMemoryError.

Disabling the check with -XX:-UseGCOverheadLimit only postpones the inevitable heap-space error and prolongs the brownout — it is never the fix.

Going deeper A senior interviewer will expect one more fact: this error exists only in the Parallel collector, and historically in CMS.

G1, ZGC, and Serial do not implement the overhead-limit check, so a G1 service in the same condition never says "GC overhead limit exceeded" — it simply runs back-to-back full GCs, each reclaiming a sliver, until an allocation finally fails with "Java heap space" or the liveness probe kills the pod.

The thresholds are -XX:GCTimeLimit=98 and -XX:GCHeapFreeLimit=2, both tunable, and the check requires the condition to hold for five consecutive full collections.

The practical consequence is that on G1 you must build the detection yourself: alert when the fraction of wall-clock time in GC, from -Xlog:gc+cpu or the jvm.gc.pause timer, exceeds 50 percent over a minute — that is the brownout signal the Parallel collector would have thrown for you.

Land it Treat it as "Java heap space, but the JVM did you the favor of failing fast" — same evidence, same workflow, and be grateful you were not paged for the slow-brownout version.

Likely follow-ups
"You're on G1, so you never see this message. How do you detect the same brownout?"

By measuring GC time as a fraction of wall-clock time, which is what the Parallel check does internally.

From metrics, Micrometer's jvm.gc.pause timer gives me the summed pause duration per interval; dividing by the interval length gives the GC fraction, and I alert when it stays above 30 percent for two minutes — a healthy service is under 5 percent.

From logs, -Xlog:gc+cpu prints user, system, and real time per collection.

In the moment on a terminal, jstat -gcutil <pid> 1000 shows the FGC and FGCT columns; if the full GC count increments every few seconds and the old-generation column barely drops after each, that is the brownout in progress.

I also watch application-side signs: request latency climbing in steps that line up with pauses, and a CPU profile where GC threads dominate.

"The error happened once during a nightly report, then never again. Do you still act?"

Yes, because it tells me the job's working set came within 2 percent of the heap, which is a sizing fact, not an anomaly. Reports tend to grow with data, so the next run is likely to fail outright.

I would pull the GC log for that window and read the occupancy after each full GC to learn the actual peak live set, compare it to -Xmx, and then decide: raise the heap to give the job at least 30 percent headroom above that peak, or change the report to stream its rows instead of collecting them.

I would also add the GC-fraction alert so the next near-miss pages someone instead of being found in the log after the fact. A one-time OOM of any kind is a free warning; ignoring it is choosing to be paged later.

"Is disabling the check ever justified?"

Almost never for a service.

The one case I would accept is a batch job with a known, bounded working set that is very close to the heap limit for a short phase near the end — say, a final sort — where the alternative is failing a job that would have finished thirty seconds later.

Even then I would rather add heap, because a job that spends 98 percent of its time in GC for thirty seconds is fragile to the smallest data growth.

Disabling it in a service just converts a clean failure with a stack trace into a slow brownout where every request times out, the pod still passes a simplistic liveness check, and the on-call engineer has to reason about a process that is technically alive. The check is doing you a favor.

Q128 · Scenario. "After a handful of hot redeploys, the app server dies with OutOfMemoryError: Metaspace. Tell me the classic story behind it."

Reveal answer

The real test The classloader-leak chain — one leaked object pinning an entire application's classes.

Strong answer Metaspace holds class metadata, and a class can only be unloaded when its classloader — the object responsible for loading it — becomes unreachable.

Every hot redeploy creates a fresh classloader for the new version of the application, and the old one is supposed to die.

The classic leak: one single object from the old deployment stays referenced from outside it — a thread the app started and never stopped, a JDBC driver still registered in the JVM-wide DriverManager, a value parked in a ThreadLocal on a container worker thread, a shutdown hook, a listener on a shared library's static registry.

The retention chain has brutal leverage: that object references its class, the class references its classloader, and the classloader references every class it ever loaded — the entire old application. After N redeploys, metaspace holds N copies of all your classes, and dies.

Diagnosis: heap dump into Eclipse MAT, look for multiple instances of the webapp classloader, then "path to GC root" on the old one shows exactly which reference pins it.

Fix: deregister drivers, stop your threads, and clear ThreadLocals in the shutdown hook of the app — or the modern answer: stop hot-redeploying and restart the container or pod instead.

Land it One leaked object retains a whole application's classes — that leverage is why redeploy leaks are vicious, and why immutable deployments made the problem largely extinct.

Likely follow-ups
"How do you prove it is a classloader leak from a heap dump, step by step?"

Open the dump in MAT and run the histogram filtered on the classloader class — for Tomcat that is org.apache.catalina.loader.ParallelWebappClassLoader. One instance per deployed application is healthy; five instances after five redeploys is the proof.

Then I select an old one — MAT shows each loader's state field, and a stopped webapp's loader has state set to a destroyed value — and run "Path to GC Roots" excluding weak and soft references.

The chain ends at the pinning object: a Thread whose context classloader is the old loader, a ThreadLocal value, a DriverManager registration, a JMX MBean, or a static field in a shared-library class.

MAT's "Leak Suspects" report often names this chain directly, and the "Class Loader Explorer" shows how many classes each loader retains, which is the metaspace cost.

"Does this still happen in a Spring Boot fat jar that never hot-redeploys?"

Not the redeploy version, but two relatives do.

First, dynamically generated classes: frameworks that create proxies, lambdas, or generated classes per call rather than per type — a misconfigured Groovy script engine, a JSON library creating a new deserializer class per request, a mapping library generating a class per invocation — grow metaspace continuously with a single classloader.

jcmd <pid> VM.classloader_stats shows the loaded class count climbing. Second, hidden classes for lambdas and method handles are unloaded when their defining loader dies, which in a fat jar is never, so a pattern that spins lambdas through MethodHandles.Lookup.defineHiddenClass in a loop leaks too.

The fix in both cases is caching the generated class per shape rather than per call.

"What is the JDBC driver retention chain exactly?"

java.sql.DriverManager is loaded by the bootstrap loader, so it lives forever. When the application's classloader loads the MySQL or Postgres driver jar, the driver class's static initializer calls DriverManager.registerDriver(new Driver()).

Now the immortal DriverManager holds a strong reference to the driver instance, the instance references its class, the class references the webapp classloader, and the loader references every class it loaded.

On undeploy, the application never calls DriverManager.deregisterDriver, so the entire application stays pinned by one static list in the JDK. The fixes are a ServletContextListener that deregisters drivers in contextDestroyed, putting the driver jar in the container's shared lib so it is loaded once by a loader that outlives applications, or, best, not hot-redeploying at all.

"What are MaxMetaspaceSize and CompressedClassSpaceSize, and how do they interact?"

Metaspace has two parts.

The main part holds method bytecode, constant pools, and other class data; the compressed class space holds the Klass structures that compressed class pointers in object headers point to, which must live in one contiguous reservation so a 32-bit pointer can address it.

-XX:CompressedClassSpaceSize, 1GB by default, sizes that reservation and cannot grow at runtime; -XX:MaxMetaspaceSize caps the total. The error message tells you which one hit: "Metaspace" for the general area and "Compressed class space" for the other.

Both are reported by jcmd <pid> VM.metaspace, which also shows how much space is committed but unused because of chunk fragmentation — a leak of thousands of small classes shows up as high committed with low used.

Q129 · Scenario. "A Netty service throws OutOfMemoryError: Direct buffer memory while the heap sits half empty. What is going on?"

Reveal answer

Strong answer Direct buffers live in native memory outside the heap, capped by -XX:MaxDirectMemorySize, which defaults to roughly the heap size.

The half-empty heap is a clue, not a comfort: for plain NIO buffers, the native memory is released only when the small Java wrapper object gets collected — and a quiet heap means little GC, so wrappers linger and native memory stays claimed.

Netty makes it sharper: its pooled ByteBufs are reference-counted, meaning memory is returned when code explicitly calls release() — miss a release on any code path, especially an exception path, and that buffer is gone forever. My steps:

  1. Turn on Netty's leak detector in staging with -Dio.netty.leakDetection.level=paranoid — it logs the allocation stack trace of buffers that were garbage-collected without being released, naming the guilty handler.
  2. Watch the allocator's own metrics — PooledByteBufAllocator exposes used direct memory — and correlate the climb with traffic patterns or slow consumers holding responses in flight.
  3. Fix the release discipline (try/finally around buffer use, ReferenceCountUtil.release in exception handlers) and add backpressure so unbounded in-flight data cannot accumulate.
  4. Only then size -XX:MaxDirectMemorySize deliberately for the legitimate working set.

Land it Reference-counted buffers bring back manual memory management — the leak discipline of C, thankfully with the stack traces of Java.

Likely follow-ups
"The leak detector reports nothing, yet direct memory still climbs. What next?"

Then either the buffers are not being garbage-collected — the detector only reports a buffer when its wrapper is collected without release, so a buffer that is still strongly referenced somewhere is invisible to it — or the memory is not Netty's. For the first case, I take a heap dump and look at the dominator tree for io.netty.buffer.PooledUnsafeDirectByteBuf instances and what retains them; a common answer is a queue of pending responses for a slow client, which is a backpressure problem, not a release bug, and the fix is Channel.isWritable() checks and high-water marks. For the second case, I check whether the JDK's own direct memory is the consumer with jcmd <pid> VM.native_memory summary under the Other category and the BufferPool MXBean, and I check whether Netty is even using the JDK counter, since by default it allocates with its own accounting when io.netty.maxDirectMemory is set.

"How does a plain NIO direct buffer get freed, and what does -XX:+DisableExplicitGC have to do with it?"

When ByteBuffer.allocateDirect runs, the JDK first reserves the size against MaxDirectMemorySize in a counter.

If the reservation would exceed the limit, the JDK does not fail immediately: it triggers System.gc() and retries for a short while, hoping the collection will run the cleaners of dead buffers and free their native memory.

That is why direct memory exhaustion in NIO code often looks like a full GC followed by recovery. With -XX:+DisableExplicitGC that call does nothing, so the retry cannot free anything and the allocation fails with the OOM even when plenty of dead buffers exist.

The safer alternative is -XX:+ExplicitGCInvokesConcurrent, which lets the request through as a concurrent cycle, or better, sizing the limit properly and reusing buffers.

"How do reference counts get lost on an exception path — show me the shape of the bug."

The typical shape is a handler that receives a ByteBuf, calls a decoder that throws on malformed input, and the release line sits after the decode call. The exception skips the release, the handler's exceptionCaught closes the channel, and the buffer's refcount stays at one forever.

In a pipeline, the same thing happens when a handler consumes a message but does not pass it on and does not release it. The fixes are structural: try { ... } finally { ReferenceCountUtil.release(msg); } around any code that takes ownership; extending SimpleChannelInboundHandler, which releases automatically after channelRead0; and never storing a ByteBuf beyond the handler call without calling retain() and documenting who releases it.

The leak detector's stack trace shows exactly where the last touch() happened, which is usually the guilty handler.

"Would you use heap buffers instead to avoid all this?"

For most services outside the hot I/O path, yes. Heap ByteBufs are ordinary garbage-collected memory, so a forgotten release costs nothing but a slightly earlier collection, and the leak class disappears.

The cost is a copy: when Netty writes a heap buffer to a socket, the JDK copies it into a temporary direct buffer first, and the same for reads, so at very high throughput, tens of gigabits, the copy is measurable.

Netty's default is direct buffers with pooling precisely for that path.

My rule is: direct pooled buffers for the transport layer where Netty's own handlers manage lifecycle, heap buffers for anything application code touches, and io.netty.allocator.type=unpooled plus heap in tests so leaks are not masked by the pool.

Q130 · Scenario. "OutOfMemoryError: unable to create new native thread — but heap usage is low. Where do you look?"

Reveal answer

Strong answer This one is not a heap problem at all: the JVM asked the operating system for a new thread and the OS refused.

Every Java thread costs a native stack — about 1MB by default, set by -Xss — plus a kernel task, and several limits can be the wall: ulimit -u, the per-user cap on processes and threads; the container's pids limit under Kubernetes; kernel settings like threads-max; or genuine native memory exhaustion from thousands of stacks.

My steps: first, get the thread count cheaply — ls /proc/<pid>/task | wc -l or the JVM's thread metrics — and compare it against ulimit -u and the container's pids limit.

A count in the thousands and climbing means a thread leak, and the classic cause is code creating an ExecutorService per request and never shutting it down; identifying exactly which threads those are is thread-dump work I would do next, which is its own drill.

The fix is structural: create pools once and share them, cap their sizes, and only raise ulimit if the measured count is legitimate for the workload.

Land it This error is an operating-system resource limit wearing a Java costume — measure the thread count against the OS limits before touching a single heap flag.

Likely follow-ups
"The thread count is only 400, well under every limit, and it still fails. Why?"

Then the wall is not the count limit but memory or address space.

Each thread needs its stack reserved as a contiguous mapping, and on a 64-bit system the address space is not the issue, but the container's memory limit can be: if the cgroup is close to its limit, the kernel refuses the mmap for a new stack, and the JVM reports it as this same error.

I check memory.current against memory.max in the cgroup and the JVM's committed sizes with NMT. The other candidate is a virtual-memory overcommit setting: with vm.overcommit_memory=2 the kernel enforces a strict commit limit and thread stacks count against it fully.

The fix is the budget from the OOMKilled discussion — smaller -Xss, a smaller heap fraction, or a larger container.

"How would you find which code is leaking threads?"

The thread names in a dump.

jcmd <pid> Thread.print or jstack lists every thread with its name and stack, and a leak shows as hundreds of threads with the same name pattern — pool-1234-thread-1, which is the default from Executors, is the classic signature of an executor created per request and never shut down.

The numbering tells the story: pool numbers climb by the thousand, and each pool has one idle thread parked in LinkedBlockingQueue.take.

If names are unhelpful, JFR's jdk.ThreadStart event records the stack trace of the thread that created each new thread, which points straight at the new ThreadPoolExecutor call. Then the fix is a shared pool injected as a dependency with a ThreadFactory that names threads by purpose.

"Would virtual threads make this error go away?"

For the case of many concurrent blocking tasks, yes.

A virtual thread is a heap object of a few hundred bytes with a stack that lives in the heap as chunks, and it is mounted on a small pool of carrier threads only while running, so a million of them costs heap memory rather than a million OS threads and stacks.

The pids limit and ulimit -u never see them. It does not fix a leak of executors, though: an Executors.newVirtualThreadPerTaskExecutor() created per request and never closed still leaks the executor object, just more cheaply.

And code that pins the carrier — long synchronized blocks were the notable case before JDK 24 fixed it under JEP 491, and native calls still are — can starve the carrier pool, which shows as stalls rather than thread-creation errors.

"What is the actual cost of one platform thread, so we can size the limit sensibly?"

Roughly: the stack reservation, 1MB by default via -Xss, of which typically 50 to 200KB gets touched and becomes resident; the kernel task structure, a few kilobytes; the JVM's own thread structure with its TLAB and handshake state, tens of kilobytes; and, in a container, one entry against the pids cgroup limit, which Kubernetes often sets to a few thousand by default.

Creation takes on the order of 50 to 100 microseconds. So 2,000 platform threads is around 300MB resident, which is fine, but 20,000 is 3GB and a scheduler juggling that many runnable tasks.

That arithmetic is why I set an explicit thread budget per service, expose the live thread count as a metric, and alert at half the lowest hard limit.

Q131 · Scenario. "Kubernetes shows your pod OOMKilled with exit code 137, but there is no OutOfMemoryError anywhere in the logs. Explain the two different deaths."

Reveal answer

The real test Whether you understand the kernel and the JVM enforce two different budgets, and how to make them agree.

Strong answer These are two different killers enforcing two different limits. An OutOfMemoryError is thrown inside the JVM when a Java-managed area — heap, metaspace, direct memory — hits its configured cap; the JVM is alive to log a stack trace and write a heap dump.

OOMKilled is the Linux kernel's out-of-memory killer sending SIGKILL because the container's total physical memory — the RSS, resident set size — exceeded the cgroup limit, the kernel-enforced ceiling on the container.

The JVM gets no warning and no chance to log anything; exit code 137 is just 128 plus signal 9.

The gap between the two: RSS is heap plus metaspace, thread stacks, direct buffers, the JIT code cache, and GC bookkeeping — so a JVM comfortably under -Xmx can still blow the container limit. The fix is budgeting.

Modern JVMs are container-aware and read the cgroup limit, so I size heap as a fraction and cap the rest explicitly:

container-jvm-flags.sh
# pod memory limit: 4Gi — leave ~30-40% for non-heap
JAVA_OPTS="-XX:MaxRAMPercentage=60.0 \
  -XX:MaxMetaspaceSize=256m \
  -XX:MaxDirectMemorySize=512m \
  -Xss512k \
  -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps"

Then verify under load that steady RSS sits well below the limit, because the kernel's verdict is not appealable.

Land it OutOfMemoryError is the JVM enforcing your budget; OOMKilled is the kernel enforcing its own — leave the kernel enough headroom and it never gets a vote.

Likely follow-ups
"You set MaxRAMPercentage=60 and the pod still gets OOMKilled at peak. What next?"

Then the 40 percent I left is not enough for non-heap, and I need to find out what is using it. I run the pod with -XX:NativeMemoryTracking=summary and, at peak, jcmd <pid> VM.native_memory summary to compare the JVM's committed total against the cgroup's memory.current.

If NMT accounts for the whole RSS, the biggest category tells me which cap to tighten — usually Thread, meaning too many threads or too large an -Xss, or Class.

If NMT is well under RSS, the gap is glibc malloc arenas or a native library; MALLOC_ARENA_MAX=2 typically recovers hundreds of megabytes.

One more check: the kernel counts page cache from file writes against the cgroup, so a service writing logs or files heavily can be charged for cache it does not control.

"How does the JVM know the container's limit, and when does that detection fail?"

Since JDK 10, and backported to 8u191, the JVM reads the cgroup files directly: memory.limit_in_bytes on cgroup v1 or memory.max on cgroup v2, and the CPU quota and period for availableProcessors(). -XX:+UseContainerSupport is on by default.

It fails in a few cases: a JDK older than those versions sees the host's memory and picks a heap of a quarter of the whole node; a container with no memory limit set gets the host's numbers; and a mismatch between the JVM's cgroup version support and the node's, which was a real problem for cgroup v2 before JDK 15.

I verify with java -XX:+PrintFlagsFinal -version | grep MaxHeapSize run inside the actual pod, not on a laptop.

"Why not just set -Xmx directly instead of a percentage?"

Both work; the percentage makes the heap follow the pod's memory limit when someone resizes the pod in the deployment manifest, so the two numbers cannot drift apart.

With a fixed -Xmx4g and a pod limit later lowered to 4Gi, the heap alone matches the limit and the first busy period gets OOMKilled.

The downside of a percentage is that it also follows the limit down when someone shrinks the pod without thinking, so I pair it with an explicit -XX:MaxRAM floor or at least a startup log line printing the computed heap.

For a service with a well-understood footprint I prefer explicit -Xms and -Xmx set equal, with the pod limit computed as heap plus a documented non-heap budget, and a CI check that the two agree.

"What does the kernel's OOM killer actually choose, and can the JVM get any warning?"

Within a cgroup that exceeds its limit, the kernel picks the process with the highest oom_score, which is roughly the one using the most memory, and in a single-process container that is the JVM.

It sends SIGKILL, which cannot be caught, so shutdown hooks never run and no dump is written.

Warning is possible but not from the JVM: cgroup v2 exposes memory.events with a high counter that increments when usage crosses memory.high, and a sidecar or the application can watch memory.current approaching memory.max and trigger a heap dump or a graceful drain while there is still time.

In practice I make the JVM's own budget the first line of defense so the kernel limit is never the one that fires.

Drill · Leak patterns & the diagnosis toolkit

This group tests the leak taxonomy every senior should recite and whether you have personally walked from a GC log to a MAT dominator tree and back to a one-line fix.

Q132. "Java has garbage collection — so how do memory leaks still happen? Start with the static-collection pattern."

Reveal answer

Strong answer The collector frees what is unreachable, not what is unused — and a Java leak is exactly that gap: objects still reachable from a GC root that the program will never touch again. The most common shape is a static collection.

Why a static collection is immortal:

  1. Ownership: a static field belongs to the class.
  2. Lifetime: the class lives as long as its classloader.
  3. Result: a static Map used as a registry, a deduplication set, or an "audit trail" is effectively immortal, and if entries are only ever added, it grows for the life of the process.

The growth can be slow enough to hide for weeks. A modern variant is metrics with unbounded label values: tag a counter with user IDs and the metrics registry becomes a static map growing with your user base.

Detection is cheap: take jcmd <pid> GC.class_histogram a few hours apart and diff. The growing collection and its entry type float to the top.

The fix is a bound: eviction, expiry, or scoping the data to the request instead of the class.

Picture it a static map that only grows, who keeps it alive, and the histogram that gives it away.

The setup: an audit trail kept in a static map that nothing ever trims.

AuditTrail.javaruns offline
public class AuditTrail {
    // ❌ TRAP: static + add-only + no bound = reachable from a GC root forever
    private static final Map<String, Event> TRAIL = new ConcurrentHashMap<>();

    public static void record(String requestId, Event e) {
        TRAIL.put(requestId, e);   // nothing ever removes an entry
    }
}

Make the invisible visible: the class is a GC root, so everything the map points to stays reachable.

memory picture
GC roots                          heap
class AuditTrail ───────────────► TRAIL (ConcurrentHashMap)
 (lives as long as its                ├─► "req-1"       ─► Event #1        ✗ never read again
  classloader)                        ├─► "req-2"       ─► Event #2        ✗ never read again
                                      ├─► ...
request thread stack ─► Event #n      └─► "req-2000000" ─► Event #2000000  ✗ still reachable

The trace: the same process at three moments; the post-GC floor only goes up.

growth trace
# illustrative output
hour  0   TRAIL entries         0   old gen after GC  0.3 GB   ✓
hour  6   TRAIL entries 1,200,000   old gen after GC  0.9 GB   ✗ floor rising
hour 12   TRAIL entries 2,400,000   old gen after GC  1.5 GB   ✗ floor rising

What you see: two class histograms taken hours apart, diffed by instance count.

jcmd GC.class_histogram, diffed
# illustrative output
class                  count @09:00   count @15:00   change
byte[]                      812,044        790,310   -21,734   (fluctuates)
com.acme.Event            1,204,331      1,990,877  +786,546   ← grows linearly

Why: the collector frees only what is unreachable, and the static field keeps every entry reachable.

The fix: bound the collection and expire entries.

AuditTrail.java (fixed)runs offline
// ✅ FIX: bounded, expiring, observable
private static final Cache<String, Event> TRAIL = Caffeine.newBuilder()
        .maximumSize(10_000)
        .expireAfterWrite(Duration.ofMinutes(10))
        .recordStats()
        .build();

What you see now: the same diff after a day: the entry count is flat.

jcmd GC.class_histogram, diffed
# illustrative output
class                  count @09:00   count @15:00   change
com.acme.Event               10,000         10,000         0   ✓ capped by maximumSize

Land it Any collection that only ever gains entries is a leak on a delay timer — the only open question is the rate.

Likely follow-ups
"The histogram shows byte[] and String at the top, which is true of every Java heap. How do you get past that?"

By not reading the histogram in isolation. Arrays and strings are always at the top because they are the leaves of every object graph; the leak's owner is a container object further up. Two moves.

First, diff two histograms a few hours apart and sort by the change in instance count rather than by absolute size — the leaking class's count grows linearly while byte[] fluctuates.

Second, in a heap dump, use the dominator tree instead of the histogram: it attributes the strings and arrays to the object that retains them, so the top entry is the map or list holding two million entries, not the two million strings.

MAT's "Immediate Dominators" query on java.lang.String answers directly "which objects retain most of the strings".

What you see: sorted by absolute size, the leaves win; sorted by change, the owner shows up.

histogram, two sort orders
# illustrative output
by size:    1. byte[]  2. java.lang.String  3. Event      ✗ same on every heap
by growth:  1. Event  +786,546   2. String +786,540   3. byte[] -21,734   ✓ Event is the suspect
"How do metrics with unbounded labels leak, concretely, and how do you prevent it?"

A metrics registry keys each time series by its full set of label values, and each series holds a counter or a histogram object with its own buckets.

Tag a request counter with user_id and every distinct user creates a new series that lives forever in the registry, which is a static singleton — a million users is a million histogram objects, each hundreds of bytes plus its label strings.

The scrape payload grows with it, so Prometheus suffers too. Prevention is a rule that label values come from a small fixed set: status codes, endpoint templates like /orders/{id} rather than raw paths, tenant tiers.

Micrometer has MeterFilter.maximumAllowableTags to cap cardinality per metric, and I set it as a safety net so a mistake degrades to a capped tag instead of an outage.

"Is a static collection ever legitimate?"

Yes, when its size is bounded by something that is not user input.

A static map from class to a cached reflection result is bounded by the number of classes; a static registry of handlers filled at startup and never changed is bounded by the code; an enum-keyed map is bounded by the enum.

The test I apply in review is: what determines the maximum number of entries, and is that number fixed at build time?

If the answer involves requests, users, sessions, or time, it needs a bound and an eviction policy, which usually means it should be a Caffeine cache rather than a HashMap.

I also want static mutable collections to be thread-safe by construction, because a static HashMap mutated from request threads is a corruption bug as well as a leak.

"How slow can a leak be and still be worth chasing?"

Any leak that will reach the heap limit within the deploy cadence is worth chasing, and the rest are worth knowing about.

A service deployed daily can tolerate a leak that would take a month to matter, but that tolerance is fragile: a deploy freeze over a holiday, or a switch to fewer, larger instances, turns a harmless slope into an outage.

So I quantify every observed slope in megabytes per hour from the post-GC floor and divide the free headroom by it to get a time-to-failure, and I record it.

Anything under a week gets fixed now; anything under a quarter gets a ticket; and a restart-based mitigation is only acceptable with the slope documented, because "we restart nightly" is how a known leak becomes a surprise later.

Q133. "How do listener and callback registrations leak memory, and what is the discipline that prevents it?"

Reveal answer

Strong answer A listener leak happens when a short-lived component registers itself with a long-lived one and never deregisters.

The long-lived side (an event bus, scheduler, connection, or observable) holds a strong reference to the listener in its internal list.

When the component's logical life ends (the session closes, the view is discarded), it stays physically alive because the subject still points at it.

It also drags its entire object graph along: services it references, buffers, often a whole subtree.

The histogram symptom is unmistakable: tens of thousands of instances of a class that should number in the dozens.

The discipline: every addListener is written together with its removeListener on the same lifecycle. Three ways to do that:

  • try/finally around the period the listener is needed.
  • @PreDestroy (or the framework's equivalent) on the owning component.
  • A subscription handle: subscribing returns an AutoCloseable you must own, as Reactor's Disposable does.

Weak-reference listener lists exist as a fallback, but they trade a leak for listeners that silently vanish, so I prefer explicit deregistration with an owner.

Picture it a short-lived view registered on a long-lived bus, drawn before and after the session closes.

The setup: a bus that keeps strong references, and a per-session view that registers itself and never leaves.

OrderView.javaruns offline
class EventBus {                                    // long-lived singleton
    private final List<Listener> listeners = new CopyOnWriteArrayList<>();
    void addListener(Listener l)    { listeners.add(l); }
    void removeListener(Listener l) { listeners.remove(l); }
}
class OrderView implements Listener {               // one per user session
    OrderView(EventBus bus) {
        bus.addListener(this);                      // ❌ TRAP: no matching removeListener, ever
    }
}

Make the invisible visible: the bus is the GC root; each closed session is logically dead but physically attached.

memory picture
GC root: EventBus (static singleton)
  └─ listeners: [ OrderView#1 ][ OrderView#2 ] ... [ OrderView#48211 ]
                     │              └─► Session ─► buffers ─► subtree
   session 1 closed: logically dead ✓   physically alive ✗ (the bus points at it)

The trace: the list only ever grows, however many sessions close.

call trace
t0  new OrderView(bus)    listeners = [V1]
t1  session 1 closes      listeners = [V1]          ✗ V1 still reachable
t2  new OrderView(bus)    listeners = [V1, V2]
t3  session 2 closes      listeners = [V1, V2]      ✗ V1, V2 still reachable

What you see: the instance count against the application's own count of live sessions.

histogram vs metric
# illustrative output
com.acme.OrderView   instances: 48,211
app metric active_sessions:        37     ✗ 48,174 stale views

Why: the subject holds a strong reference, so nothing short of an explicit remove can free the listener.

The fix: subscribe returns a handle, and the owner closes it on the same lifecycle.

OrderView.java (fixed)runs offline
class EventBus {
    Runnable subscribe(Listener l) { listeners.add(l); return () -> listeners.remove(l); }
}
class OrderView implements Listener, AutoCloseable {
    private final Runnable unsubscribe;
    OrderView(EventBus bus) { this.unsubscribe = bus.subscribe(this); }
    @Override public void close() { unsubscribe.run(); }   // ✅ FIX: owned deregistration
}
// try (OrderView v = new OrderView(bus)) { ... }

What you see now: the instance count follows the live sessions.

histogram vs metric
# illustrative output
com.acme.OrderView   instances: 37
app metric active_sessions:     37     ✓ match

Land it Pair every subscribe with an owned unsubscribe handle — a registration nobody owns is a leak that has not been measured yet.

Likely follow-ups
"The framework registers the listener for you and offers no unsubscribe. What then?"

Then I make the listener not retain anything worth leaking.

The listener becomes a small adapter that holds a weak reference to the real component and does nothing when the referent is gone; the leak shrinks from a whole subtree to a few dozen bytes per stale listener, which is acceptable at any realistic rate.

Where even that is too much, I keep one long-lived listener per subject that dispatches to a map of live components keyed by identity, and the component removes itself from that map on its own lifecycle end — I have moved the deregistration to an object I control.

And I open a ticket against the framework, because a subscribe with no unsubscribe is a bug in its API; most mature libraries have added a returned handle after enough of these reports.

"How does this look in a heap dump, and how would you confirm the listener list is the retainer?"

The histogram shows an implausible instance count for the component class — tens of thousands of OrderView objects where a few dozen are live.

In the dominator tree, they are not top-level, because they are retained by one thing: expanding the event bus or scheduler object shows its listener collection, an ArrayList or CopyOnWriteArrayList, retaining all of them.

Selecting one stale component and running "Path to GC Roots" with weak references excluded ends at the bus's static instance or at a thread holding it.

To confirm they are stale rather than live, I check a field that indicates lifecycle — a closed flag, a disposed session ID — or simply compare the count against the application's own metric for active components.

What you see: the retention chain in the dump, read from the root down.

path to GC roots
# illustrative output
com.acme.EventBus  (static INSTANCE, GC root)
  └─ listeners  java.util.concurrent.CopyOnWriteArrayList
       └─ array[0..48210]  com.acme.OrderView   ← 48,211 instances retained
"Why do you prefer explicit deregistration over weak listener lists?"

Because a weak listener list changes the semantics from "leak" to "silent disappearance".

A listener held only weakly can be collected the moment nothing else references it, which is often sooner than the developer expects — a lambda registered inline has no other referent and can be collected on the very next young GC, so the callback stops firing and nothing reports why.

That bug is far harder to diagnose than a leak, because it produces missing behavior rather than growing memory.

Explicit deregistration with an owned handle makes the lifetime visible in code: whoever holds the Disposable owns the subscription, and disposing it is a line a reviewer can see. I use weak lists only as the defensive layer beneath explicit deregistration.

"How do you test for this kind of leak automatically?"

With a lifecycle test that asserts collectability. Create the component, register it, end its lifecycle the way production does, drop the strong reference, hold a WeakReference to it, then call System.gc() in a short loop and assert that the weak reference clears within a few iterations.

Frameworks like JUnit plus a small helper make this a five-line test, and it fails deterministically when a listener retains the object.

The same pattern scales to a soak test: run the request loop for an hour in CI against a small heap and assert that ManagementFactory.getMemoryPoolMXBeans() reports a flat old-generation floor after collections.

It is slow, so it runs nightly rather than per commit, but it catches the listener that someone added without its unsubscribe.

Q134 · Scenario. "You store per-request context in a ThreadLocal. Running on Tomcat, memory climbs for days and occasionally one user sees another's context. Walk me through the exact retention chain."

Reveal answer

The real test The Thread-to-map-to-value chain, stated precisely — plus spotting that this is a security bug, not just a leak.

Strong answer The mechanics: every Thread object owns a ThreadLocalMap. Each entry's key is a weak reference to the ThreadLocal object itself, but the entry's value — your context object — is held by a strong reference.

So the retention chain is: the live thread, which is a GC root, holds its map; the map holds the entry; the entry strongly holds your value.

On Tomcat the workers are pooled threads that live as long as the process, so a value set during a request and never removed survives the request indefinitely.

The weak key does not save you, for two reasons:

  • The key never goes stale: your ThreadLocal is almost always a static final, so it never becomes unreachable.
  • Even a stale entry lingers: its value stays until the map happens to purge it on a later access.

The arithmetic: 200 worker threads times a few megabytes of context each is a slow, steady climb.

Worse, the next request served by that thread reads the previous request's leftover context. That is the cross-user data bleed, which makes this a security incident.

The fix: set and remove in the same filter or interceptor, with remove() in a finally block, exactly as frameworks like Spring's RequestContextHolder do.

In a heap dump the retained path betrays it instantly: java.lang.Thread, then threadLocals, then your value class.

Picture it the Thread-to-map-to-value chain, and two requests on one pooled thread where the second reads the first one's user.

The setup: a static ThreadLocal set in a filter and never removed.

UserContext.javaruns offline
public final class UserContext {
    private static final ThreadLocal<User> CURRENT = new ThreadLocal<>();
    static void set(User u) { CURRENT.set(u); }
    static User get()       { return CURRENT.get(); }
}
// filter:
UserContext.set(authenticate(req));   // ❌ TRAP: no remove() on the way out
chain.doFilter(req, res);

Make the invisible visible: who holds what, from the GC root down.

memory picture
Thread http-nio-8080-exec-3   (GC root; pooled, lives as long as the process)
  └─ threadLocals : ThreadLocalMap
       └─ Entry
            key   ──weak───► UserContext.CURRENT   (static final: always reachable)
            value ──STRONG─► User{alice} ─► her whole object graph

The trace: two requests that happen to land on the same worker thread, one row per step.

Interleaving on one pooled thread (exec-3)
StepRequest 1 (alice)Request 2 (public page, auth skipped)
1CURRENT.set(alice) ✓
2handler reads get() = alice ✓
3response sent, no remove() ✗
4lands on exec-3; the entry is still there
5get() returns alice ✗ (bleed)

What you see: the log of both requests.

console
# illustrative output
[exec-3] GET /orders       user=alice
[exec-3] GET /public/stats user=alice    ✗ should be anonymous

Why: the pooled thread outlives the request, so the entry outlives it too.

The fix: clear in a finally block on the same path that set it.

UserContext filter (fixed)runs offline
UserContext.set(authenticate(req));
try {
    chain.doFilter(req, res);
} finally {
    UserContext.clear();              // ✅ FIX: CURRENT.remove()
}

What you see now: the same two requests.

console
# illustrative output
[exec-3] GET /orders       user=alice
[exec-3] GET /public/stats user=anonymous   ✓

Land it ThreadLocal plus a thread pool inverts the lifetime assumption — the thread outlives the request, so cleanup must be explicit or it never happens.

Likely follow-ups
"You added remove() in a finally block, but the bleed still happens occasionally. What did you miss?"

The value is escaping the thread before the request finishes. Two common paths.

First, the request does asynchronous work: a CompletableFuture callback or an executor task runs on a different pool thread, reads the ThreadLocal there, and finds whatever that other thread last stored — the context was never propagated, so it reads a stale one from a previous request.

Second, the filter that removes it runs at the wrong layer: a servlet filter's finally runs after the response is committed, but an async servlet or reactive handler can complete on another thread after the filter returned, so the remove happens before the last read.

The fix is to pass the context explicitly as a parameter or through a task-wrapping executor that copies it in and clears it out, and to never read a request-scoped ThreadLocal from a pooled thread you did not populate.

What you see: an async callback runs on another pool thread and reads that thread's leftover value.

Context lost across threads
StepRequest thread (exec-3)Pool thread (worker-1)
1CURRENT.set(bob)
2supplyAsync(() -> CURRENT.get())task starts here
3get() returns whatever worker-1 last stored, or null ✗
"When exactly does the ThreadLocalMap purge stale entries, and why isn't that enough?"

Only opportunistically. On get() and set(), when the map probes for a slot and encounters an entry whose weak key has been cleared, it expunges that entry and a few of its neighbors; on resize it scans the whole table.

There is no background cleaning, so a stale entry survives until some later access happens to land near it. It is not enough for two reasons.

The key is usually a static final ThreadLocal, so it is never cleared and the entry is never stale — the value is just old.

And even with a stale key, a thread that stops touching ThreadLocals, like an idle worker, never triggers a purge, so the value sits there indefinitely. The design intent was to reduce leaks from discarded ThreadLocal instances, not to manage value lifetimes.

"What is ScopedValue and how does it change this?"

ScopedValue, final in JDK 25 under JEP 506, is the structured replacement: a value bound for the dynamic extent of a call, ScopedValue.where(CONTEXT, ctx).run(() -> handle(request)), readable by anything called inside that lambda, and automatically unbound when it returns.

There is no set(), so a stale value cannot exist, and there is no remove() to forget. It is immutable within its scope, which also removes the "someone overwrote the context halfway through the request" class of bugs.

With virtual threads and structured concurrency, child tasks forked inside the scope inherit the binding, which solves the propagation problem that ThreadLocal has with pools.

For a request context, as of Aug 2026, I would reach for ScopedValue first and ThreadLocal only where a library demands it.

"How do you audit a codebase for ThreadLocal misuse quickly?"

Grep for new ThreadLocal and ThreadLocal.withInitial, then for each one find every set( and check that a remove( exists on the same lifecycle path in a finally. That is usually a short list.

For the ones that are legitimately per-thread caches — a SimpleDateFormat or a buffer — the lack of remove is fine because the value is not request data, though it still pins memory per thread.

For the ones holding request or user data, no remove is a bug.

At runtime, a heap dump makes the audit concrete: MAT's "Thread Overview" shows each thread's ThreadLocals with their values, and Tomcat's own clearReferencesThreadLocals logs a warning at undeploy naming the leaked keys, which is a free audit if anyone reads the log.

Q135. "When does a cache stop being a cache and become a leak? What must every production cache have?"

Reveal answer

Strong answer A cache without eviction is a leak with better naming. The moment the key space is derived from input — user IDs, query strings, tenant plus date — an unbounded map grows with the input space, which is unbounded by definition.

Every production cache needs four things:

  1. A size or weight bound, so worst-case memory is a number you can state.
  2. An eviction policy, least-recently-used or better, like the TinyLFU policy Caffeine implements, so the bound is enforced by dropping the least valuable entries.
  3. A time-to-live where staleness matters.
  4. Metrics (hit rate, size, eviction count), because a cache you cannot observe cannot be judged or sized.

The anti-patterns I flag in review: a HashMap with "cache" in its name; keys whose equals is identity, so the cache never hits and always grows; and caching whole object graphs where an ID would do.

And I use Caffeine rather than hand-rolling, because eviction under concurrency is genuinely hard to get right.

Picture it a cache whose key has identity equals: every lookup misses and every miss adds an entry.

The setup: a "cache" in a plain HashMap with a key class that has no equals or hashCode.

QueryCache.javaruns offline
static final class Key { final String q; Key(String q) { this.q = q; } }   // ❌ TRAP: identity equals

static final Map<Key, Result> CACHE = new HashMap<>();                    // ❌ TRAP: no bound

static Result find(String q) {
    return CACHE.computeIfAbsent(new Key(q), k -> load(q));
}

Make the invisible visible: the same query lands in a different bucket slot every time.

data-structure picture
find("shoes") x3   →   CACHE.size() == 3
bucket 3:  Key@1a2b("shoes") ─► Result
bucket 9:  Key@77c1("shoes") ─► Result      ✗ same query, new entry
bucket 12: Key@9d04("shoes") ─► Result      ✗ same query, new entry

What you see: the statistics a cache must report.

cache stats
# illustrative output
hitRate=0.00  size=1,000,000  evictions=0     ✗ never hits, never evicts

Why: an unbounded map grows with the input space, and identity keys guarantee a miss.

The fix: a value-equals key and a bounded, expiring cache.

QueryCache.java (fixed)runs offline
record Key(String q) { }                                   // ✅ FIX: value equals/hashCode

static final Cache<Key, Result> CACHE = Caffeine.newBuilder()
        .maximumSize(10_000)                               // ✅ FIX: bound
        .expireAfterWrite(Duration.ofMinutes(10))
        .recordStats()
        .build();
static Result find(String q) { return CACHE.get(new Key(q), k -> load(q)); }

What you see now: the same three statistics.

cache stats
# illustrative output
hitRate=0.93  size=10,000  evictions=412,300    ✓ hits, and capped

Land it If you cannot state a cache's maximum size and its eviction policy in one sentence, what you have is a leak you have not met yet.

Likely follow-ups
"What does TinyLFU actually do differently from LRU, and why does it matter for memory?"

LRU evicts the entry that was used longest ago, so a burst of one-time keys — a crawler scanning every product page — flushes the whole cache of genuinely popular entries, each of which then costs a miss to reload.

TinyLFU adds an admission filter: it keeps an approximate frequency count of recent keys in a compact sketch, and when the cache is full, a new entry is admitted only if its frequency beats the frequency of the entry it would evict.

One-time keys never get in, so the cache retains the working set through scans. Caffeine's Window TinyLFU keeps a small LRU window for new entries so short bursts of popularity still get a chance.

For memory, this means a smaller cache achieves the hit rate a larger LRU would need, so the budget can be lower for the same effect.

"Weight-based versus size-based bounds — when does maximumSize lie to you?"

maximumSize counts entries, so it only bounds memory when entries are roughly uniform.

A cache of user profiles where one user has ten thousand addresses and most have one has a memory footprint that maximumSize cannot predict, and a few heavy entries can consume the budget of thousands of light ones.

maximumWeight with a Weigher that estimates bytes — a string's length, a list's size times an element estimate — bounds the actual resource. The estimate does not have to be exact; it has to correlate with retained size.

I verify it once by comparing the cache's reported total weight against the cache's retained size in a heap dump, and if they are off by more than a factor of two the weigher needs work.

"How do you keep a cache from being a stampede generator when entries expire?"

Three mechanisms together. A loading cache with single-flight semantics, which Caffeine's LoadingCache.get provides: concurrent misses on one key block on one load rather than each calling the backend.

refreshAfterWrite instead of, or in addition to, expireAfterWrite: after the refresh interval, the next read triggers an asynchronous reload and keeps serving the old value in the meantime, so the backend sees one call and users see no latency spike.

And jitter on expiry so entries loaded together do not expire together — Caffeine's expireAfter with a custom Expiry lets me add a random 10 percent to each entry's lifetime.

With those three, a cold-start after a deploy is the only stampede left, and a warmup routine handles that.

"When is caching the wrong answer entirely?"

When the hit rate would be low or the staleness unacceptable.

A cache keyed by something nearly unique per request — a full query string with a timestamp, a per-user computation that no two requests share — has a hit rate near zero and is pure overhead plus memory.

Data that must be current, like an account balance before a withdrawal, cannot be cached without a correctness argument about invalidation.

And caching to paper over a slow query is often worse than fixing the query, because the cache makes the p99 bimodal: fast on hits, catastrophically slow on misses.

My check is to prototype with metrics on: if the hit rate after a day is under 50 percent or the miss path is what the SLO measures, I remove the cache and look at the source.

Q136 · Scenario. "Heap climbs across days and each full GC reclaims less than the last. Walk me through the complete diagnosis, from first suspicion to the fix and the regression guard."

Reveal answer

The real test The full workflow, in order, with real commands — this is the question that separates operators from readers.

Strong answer I run it as an escalation ladder, cheapest evidence first:

  1. Confirm the trend. Enable GC logs — -Xlog:gc*:file=gc.log:time,uptime, or jcmd <pid> VM.log to switch logging on without a restart — and chart occupancy after each full GC over days. A floor that ratchets upward independent of traffic confirms a leak rather than load growth.
  2. Cheap census. Take jcmd <pid> GC.class_histogram two or three hours apart and diff: the classes whose instance counts and bytes only go up name the suspects without pausing anything meaningfully.
  3. Heap dump. jcmd <pid> GC.heap_dump /dumps/app.hprof — by default it dumps only live objects, which is what I want, and it forces a full collection first. I do this off-peak and on one instance behind the load balancer, because the dump is a stop-the-world pause of seconds to minutes on a big heap, and the file is roughly heap-sized, so I check disk space first.
  4. Open it in Eclipse MAT — the Memory Analyzer Tool — and go straight to the dominator tree: for each object, everything that would become collectible if that object died, sorted by retained size. The leak's owner is almost always in the top handful of rows.
  5. Find the pin. On the suspect, run "Path to GC Roots", excluding weak and soft references — it prints the exact chain of strong references keeping it alive:
mat-dominator-tree.txt
Class Name                                      Retained Heap
org.app.session.SessionRegistry                 2.31 GB
  '- sessions  java.util.ConcurrentHashMap      2.31 GB
       1,974,203 entries of org.app.session.UserSession

Path to GC Roots (excl. weak/soft):
  class org.app.session.SessionRegistry  (system classloader, GC root)
    .INSTANCE  ->  sessions  ->  UserSession
  1. Fix the code. Here the registry adds a session on connect and never removes on disconnect — the fix is removal on the disconnect path plus time-based expiry as a backstop.
  2. Guard the regression. Alert on the post-full-GC occupancy slope, add a soak test that runs for hours and asserts the heap floor stays flat, and keep -XX:+HeapDumpOnOutOfMemoryError on permanently.

Picture it the ratcheting post-GC floor, the escalation ladder with the cost of each rung, and the leak that the dominator tree names.

The setup: a registry that adds on connect and forgets to remove on disconnect.

SessionRegistry.javaruns offline
public final class SessionRegistry {
    static final SessionRegistry INSTANCE = new SessionRegistry();
    private final Map<String, UserSession> sessions = new ConcurrentHashMap<>();

    void onConnect(UserSession s)    { sessions.put(s.id(), s); }
    void onDisconnect(UserSession s) { /* ❌ TRAP: forgot sessions.remove(s.id()) */ }
}

Make the invisible visible: the occupancy right after each full GC, day by day.

post-full-GC occupancy
# illustrative output
day 1  ██░░░░░░░░  1.2 GB
day 3  ████░░░░░░  2.6 GB
day 5  ███████░░░  4.9 GB     ✗ the floor ratchets up independent of traffic

The trace: the ladder, cheapest evidence first.

escalation ladder
1 GC log trend        free                  ✓ leak, not load growth
2 class_histogram     ms to seconds pause   ✓ names UserSession
3 heap dump           seconds to minutes    ✓ evidence (off-peak, one instance)
4 MAT dominator tree  offline               ✓ owner = SessionRegistry (2.31 GB)
5 path to GC roots    offline               ✓ class SessionRegistry -> INSTANCE -> sessions
6 fix, 7 regression guard

What you see: the GC log lines for three full collections, and the dominator tree in the block above.

gc.log
# illustrative output
GC(41)  Pause Full (G1 Compaction Pause) 7890M->1310M(8192M) 2410.5ms
GC(97)  Pause Full (G1 Compaction Pause) 7901M->3388M(8192M) 3100.2ms   ✗ floor up
GC(163) Pause Full (G1 Compaction Pause) 7899M->5840M(8192M) 4120.8ms   ✗ floor up

Why: every disconnected session stays reachable from a static singleton.

The fix: remove on disconnect, with expiry as a backstop.

SessionRegistry.java (fixed)runs offline
void onDisconnect(UserSession s) { sessions.remove(s.id()); }          // ✅ FIX
// backstop for missed disconnects
scheduler.scheduleAtFixedRate(
        () -> sessions.values().removeIf(UserSession::isExpired), 1, 1, TimeUnit.MINUTES);

What you see now: the same log: the floor stays where it started.

gc.log
# illustrative output
GC(41)  Pause Full (G1 Compaction Pause) 7890M->1310M(8192M) 2410.5ms
GC(97)  Pause Full (G1 Compaction Pause) 7901M->1322M(8192M) 2398.0ms   ✓ flat
GC(163) Pause Full (G1 Compaction Pause) 7899M->1318M(8192M) 2405.3ms   ✓ flat

Land it The workflow is trend, histogram, dump, dominator tree, path to root, fix — and adding the regression guard at the end is what marks the answer as senior.

Likely follow-ups
"The dump is 30GB and MAT runs out of memory opening it. What do you do?"

Give MAT more heap or parse headlessly.

MAT needs roughly as much heap as the dump's live object count implies, so I edit MemoryAnalyzer.ini to set -Xmx40g on a large analysis box, or I run the parser from the command line with ParseHeapDump.sh app.hprof org.eclipse.mat.api:suspects, which produces the leak-suspects report as a zip of HTML without the GUI and can run on a server overnight.

If that is still too much, I reduce the dump: jcmd GC.heap_dump after a full GC on an instance that has just been restarted and run for an hour, when the leak is at a few hundred megabytes, is usually enough to see the same retention chain at a fraction of the size.

The leak's structure does not change with size; only the count does.

"You cannot take a dump in production — the pause is unacceptable. What is the alternative?"

Several. First, take the dump from a single instance that I have drained from the load balancer, so the pause affects nobody; that is almost always possible and is my default.

If even that is not allowed, JFR's jdk.OldObjectSample event is the built-in alternative: with -XX:StartFlightRecording=settings=profile,path-to-gc-roots=true it samples allocated objects and, at recording end, reports the ones that survived longest with their allocation stack trace and their path to a GC root — a leak profile with no dump and low overhead.

Second, the class histogram, which pauses for milliseconds, diffed over hours narrows it to a class. Third, a heap dump from a core file: gcore the process, then jhsdb jmap --binaryheap --pid on the core, which pauses only for the core write.

What you see: the JFR route: start a recording that tracks old objects, then ask for the sampled leak candidates.

console
$ java -XX:StartFlightRecording=settings=profile,path-to-gc-roots=true,filename=leak.jfr -jar app.jar
$ jfr print --events jdk.OldObjectSample leak.jfr     # lists survivors with allocation stack and root path
"The dominator tree shows the leak but the path to GC roots is a framework internal you cannot change. What now?"

Then I walk up the path to the first frame that is mine and ask what I handed to the framework.

The chain typically runs from a framework registry down to my object, and somewhere in it is a registration call I made, a callback I passed, or a context I stored — the framework is retaining what I gave it, and the fix is on my side: deregister, use a scoped registration, or store an identifier instead of the object.

If the retention is genuinely a framework bug, I check the framework's issue tracker with the exact class names from the chain, because leaks in popular frameworks are usually reported, and I mitigate with a version upgrade or a documented workaround.

The one thing I do not do is accept it, because a leak in a dependency is still my outage.

"How would you write the soak test that guards this regression?"

A nightly job that runs the service with a deliberately small heap, say -Xmx512m, under a steady synthetic load for two hours, with GC logging on.

At the end, a script parses the log for full or mixed collections, extracts the occupancy after each, and fits a line; the test fails if the slope exceeds a threshold like 5MB per hour, or if any full GC's post-occupancy is above 70 percent of the heap.

A small heap makes the leak visible in hours instead of days because the headroom is tiny.

I also add a targeted unit test for the specific fix — the registry drops sessions on disconnect — using the weak-reference collectability pattern, so the exact bug cannot return even if the soak test is skipped.

Q137. "Here's a line from a GC log. Read it to me and tell me what you'd actually extract from a file full of them."

Reveal answer
gc.log — one line, decoded
[2026-08-23T02:14:07.123+0000][gc] GC(184) Pause Young (Normal) (G1 Evacuation Pause) 6144M->1290M(8192M) 23.481ms

Strong answer Reading the line above left to right:

  • Timestamp: when the pause happened.
  • GC(184): the 184th collection since startup, so the numbering lets me measure spacing between events.
  • Pause Young: a stop-the-world young collection. (Normal) marks an ordinary one; (Concurrent Start) would mean this pause also kicked off concurrent marking.
  • Cause: G1 Evacuation Pause, meaning eden filled and live objects were evacuated.
  • The three numbers that matter: heap went from 6144M to 1290M with 8192M total, and the pause took 23.481ms.

From a file of these I extract three trends:

  1. Allocation rate: how much heap refills between consecutive collections, divided by the time between them.
  2. Post-collection floor: its upward drift is the leak signal.
  3. Pause distribution: measured against the latency SLO.

-Xlog:gc* adds per-phase detail, and :filecount options give rotation so logs survive long enough to be useful.

Picture it the log line cut into its fields, and the arithmetic that turns two consecutive lines into an allocation rate.

Make the invisible visible: each field of the line in the block above, with an arrow to what it means.

decoded line
GC(184) Pause Young (Normal) (G1 Evacuation Pause) 6144M->1290M(8192M) 23.481ms
  │        │         │              │                  │      │     │       └ pause length
  │        │         │              │                  │      │     └ heap total
  │        │         │              │                  │      └ occupancy AFTER (live set + promoted)
  │        │         │              │                  └ occupancy BEFORE
  │        │         │              └ cause: eden filled
  │        │         └ ordinary young pause
  │        └ stop-the-world young collection
  └ 184th collection since start

The trace: two consecutive young pauses give the allocation rate.

allocation-rate arithmetic
# illustrative output
02:14:07.123  GC(184)  6144M->1290M(8192M)  23.481ms   after = 1290M
02:14:11.9    GC(185)  6150M->...           before = 6150M
allocated = 6150M - 1290M = 4860M  in  4.8 s     ✓ about 1 GB/s (high)

What you see: the three series worth charting from a whole file.

what to extract
allocation rate     (before_next - after_this) / seconds between   → predicts pause frequency
post-GC floor       the "after" number over time                    → upward drift = leak
pause distribution  the ms value, p50 / p99                         → compare with the SLO

Land it Three numbers per line — before, after, pause — charted over time answer most memory questions before anyone takes a heap dump.

Likely follow-ups
"What is the exact -Xlog configuration you ship with, and why each part?"

-Xlog:gc*,gc+age=trace,safepoint:file=/var/log/app/gc.log:time,uptime,level,tags:filecount=10,filesize=50m.

The gc* selector gives every GC tag at info level, which includes the phase breakdown and heap regions; gc+age=trace adds the tenuring distribution, which is cheap and essential for promotion problems; safepoint captures time-to-safepoint so I can tell GC pauses from stop-the-world stalls caused by something else.

The decorators time,uptime give both wall-clock and seconds-since-start, so I can align with application logs and with deploy times. Rotation at 10 files of 50MB keeps two or three days on a busy service without filling the disk.

On JDK 17 and later I add async so a slow disk cannot stall a GC thread writing the log.

"How do you compute allocation rate from the log, exactly?"

From consecutive young collections.

Each line gives heap before and after; the heap after collection N is the starting occupancy, and the heap before collection N plus one is what was allocated in between, so allocation is before-of-next minus after-of-this, divided by the time between the two lines.

Using the line in the answer: if the next young pause at 02:14:11.9 shows 6150M before, then 6150 minus 1290 is 4860MB in 4.8 seconds, about 1GB per second — which is high, and it is the number that predicts pause frequency.

Tools do this for me: GCeasy or gcviewer produce the rate, the promotion rate, and the pause percentiles from a log file. I still know the arithmetic because in an incident the tool is not always at hand.

"What does a 'Pause Young (Mixed)' line tell you, and what is 'Pause Remark'?"

A mixed pause is a young collection that also evacuated some old regions chosen after concurrent marking, so seeing them means marking completed and G1 is now paying down the old generation; a healthy service shows a burst of a few mixed pauses after each marking cycle and then normal young pauses.

If I never see mixed pauses but old-generation occupancy keeps climbing, marking is not finishing or the candidate regions are too live to bother with.

"Pause Remark" and "Pause Cleanup" are the two short stop-the-world steps inside the concurrent cycle: remark finishes marking by processing what changed during the concurrent phase, and cleanup frees completely empty regions.

A remark pause of hundreds of milliseconds usually means a large number of reference objects or a huge number of classes to process.

"What single chart would you build from this log for the on-call dashboard?"

Post-collection occupancy over time, as a scatter of one point per collection, colored by collection type.

The young collections form a band whose bottom edge drifts up as the old generation fills; each mixed sequence or full GC drops it back down, and the height it drops to is the live set.

On one chart I can see the sawtooth period, which is promotion rate; the floor, which is the leak signal; the ceiling against the heap max, which is headroom; and the full GCs, which are the incidents.

Pause duration goes on a second axis as bars, so a long pause is visually tied to the occupancy that caused it. That one chart answers "is memory healthy" faster than any set of gauges, which is why it is the top of my JVM dashboard.

Q138. "You get a terminal on a memory-suspect JVM — no dashboards. What do you run in the first five minutes with jstat and jcmd?"

Reveal answer

Strong answer Four commands, in this order:

  1. jcmd <pid> VM.flags to see what is actually configured (collector, -Xmx, dump-on-OOM), because assumptions about flags are wrong surprisingly often.
  2. jcmd <pid> GC.heap_info for a one-shot picture of occupancy per space.
  3. jstat -gcutil <pid> 1000, which prints one line per second: percentage full for each space plus collection counts and accumulated GC time. I watch the old-generation column across a few minutes of load (sawtoothing healthily or ratcheting) and the full-GC count and time, which tell me how hard the collector is working.
  4. jcmd <pid> GC.class_histogram, if the old generation is climbing, to name the growing classes. It is far cheaper than a dump, though it does briefly pause the JVM.

Those four commands establish whether there is a problem, what kind, and whether a heap dump is justified.

Picture it what the old-generation column looks like when healthy and when it ratchets, in the same jstat layout.

Make the invisible visible: the two shapes of old-generation occupancy over a few minutes.

old generation, two shapes
healthy (sawtooth)         leaking (ratchet)
O%  70 ▁▃▅▇ ▁▃▅▇ ▁▃▅▇      O%  70 ▃▅▇ ▅▇ ▆▇ ▇▇▇▇
    each GC drops to ~70       each GC drops to a higher floor ✗

The trace: the four commands, with what each one answers.

first five minutes
1 jcmd VM.flags            what is configured?        ✓ collector, -Xmx, dump-on-OOM
2 jcmd GC.heap_info        how full, per space?       ✓ instant
3 jstat -gcutil 1000       trend over time?           ✓ ratchet or sawtooth
4 jcmd GC.class_histogram  which class grows?         ✓ names it (brief pause)

What you see: one jstat sample with the leaking shape, then a healthy one for comparison.

jstat -gcutil
# illustrative output
  S0     S1     E      O      M     CCS    YGC     YGCT    FGC    FGCT      GCT
  0.00  45.12  67.30  97.85  94.10  90.02  12034   88.201   217  402.115  490.316   ✗ O at 97%, full GCs dominate
  0.00  12.40  30.20  41.10  93.00  89.50   5120   41.020     3    4.800   45.820   ✓ healthy: O stays low

Why: if O stays near the top after a full GC, the memory is live, so it is a leak or an undersized heap.

Land it jstat tells you whether there is a problem, the histogram tells you what is growing, and the dump tells you why — escalate in that order because each step costs more than the last.

Likely follow-ups
"Read me a jstat -gcutil line and tell me what is wrong with it."

The columns are S0, S1, E, O, M, CCS as percentages, then YGC and YGCT for young collection count and total time, FGC and FGCT for full, and GCT total.

A line like 0.00 45.12 67.30 97.85 94.10 90.02 12034 88.201 217 402.115 490.316 says: survivor one is half full, eden two-thirds, but the old generation is at 97.85 percent — and 217 full GCs have consumed 402 seconds, versus 88 seconds for twelve thousand young collections.

Full GCs are dominating GC time and the old generation is not draining after them, which is the leak or undersized signature.

The next line a second later will tell me whether O is dropping: if it is still at 97 after another full GC increment, the memory is live. Metaspace at 94 percent is a second thing to check, because it may be near its cap.

"What does jcmd GC.class_histogram cost, and when would you not run it?"

It walks the whole heap at a safepoint, so it pauses the application for the duration of the walk — roughly a second per few gigabytes of used heap.

On a 4GB heap that is a one-to-two-second stop-the-world, comparable to a full GC. By default it also counts only live objects, which means it first performs a full collection unless -all is passed.

I would not run it on the only instance of a latency-sensitive service at peak, or on a heap over 30GB or so, where the pause is long enough to trip health checks.

The alternatives are cheaper in different ways: GC.heap_info is instant but only per-space; JFR's allocation sampling is continuous and low overhead but shows allocation, not retention. On one drained instance, the histogram is the best cost-to-insight ratio there is.

"You have five minutes and the process is at 99 percent old-generation with full GCs every 10 seconds. What do you do first?"

Preserve evidence, then restore service, in that order but quickly. First, jcmd <pid> GC.heap_dump /dumps/incident.hprof if disk allows — the process is already pausing constantly, so the dump's pause costs nothing extra, and without it the root cause is lost forever.

If the dump is impossible, jcmd <pid> GC.class_histogram > hist.txt takes seconds and names the top classes. Second, capture jcmd <pid> VM.flags and Thread.print to a file.

Third, pull the instance from the load balancer and restart it, since a process in this state serves nothing anyway.

Then, on the replacement, I watch the old-generation slope with jstat to estimate how long until it recurs, which tells me whether I have hours or days to analyze the dump.

"What else can jcmd tell you about memory that people forget?"

Several things beyond the heap. VM.native_memory summary, if NMT is on, breaks down every non-heap category. VM.metaspace shows class-space usage and fragmentation. VM.classloader_stats lists every classloader with its class count and size, which finds classloader leaks without a dump. Compiler.codecache shows code-cache occupancy.

GC.finalizer_info reports how many objects are waiting for finalization, which catches a stuck finalizer thread. VM.info dumps the same summary as a crash log, including the heap layout and the container limits the JVM detected.

And JFR.start begins a flight recording on the spot for a live allocation profile. All of these are cheap and none require a restart, which is why jcmd is the tool I reach for before anything else.

Q139 · Scenario. "Heap is rock-stable at 2GB, but the container's RSS climbs 50MB a day toward its 4GB limit, and heap dumps show nothing. Where is the memory going and how do you find it?"

Reveal answer

The real test Knowing heap dumps cannot see native memory, and that NMT is the instrument for the gap.

Strong answer The leak is in native memory, which a heap dump is blind to by design. The usual suspects:

  • Direct buffers.
  • Metaspace creep.
  • Thread stacks multiplying.
  • The JIT code cache.
  • Native allocations made by libraries, the sneakiest: for example an unclosed GZIPInputStream whose Inflater holds zlib memory until finalization.

My steps:

  1. Restart with Native Memory Tracking: -XX:NativeMemoryTracking=summary, accepting its 5–10% overhead temporarily. Then jcmd <pid> VM.native_memory baseline, wait a day, and jcmd <pid> VM.native_memory summary.diff — it attributes growth to JVM categories: Class, Thread, Code, Internal, and so on, which usually names the culprit directly.
  2. If every NMT category is flat but RSS still climbs, the leak is outside the JVM's own accounting — a native library leaking through JNI, or glibc's allocator holding fragmented arenas. Then I diff pmap -x <pid> snapshots, try MALLOC_ARENA_MAX=2, or run under jemalloc with profiling to get native allocation stacks.
  3. Check the boring causes in parallel: thread count trend, metaspace trend, and any code path creating Inflaters, Deflaters, or direct buffers without closing them.

The fix follows the attribution; the prevention is exporting RSS and NMT summary numbers as metrics so heap-versus-RSS divergence pages you early, not at the cgroup limit.

Picture it the container budget with a flat heap and one native slice that grows, then the NMT and pmap evidence that separates the two branches of the diagnosis.

The setup: a code path that opens a native-backed stream and never closes it.

Unzip.javaruns offline
byte[] unzip(Path p) throws IOException {
    InputStream in = new GZIPInputStream(Files.newInputStream(p));   // ❌ TRAP: never closed
    return in.readAllBytes();   // the Inflater's native zlib buffers stay allocated
}

Make the invisible visible: the container limit split into slices; the heap dump sees only one of them.

memory picture
# illustrative output
container limit  4096 MB
  heap (-Xmx)           2048 MB   flat       ← the only slice a heap dump sees
  metaspace              120 MB   flat
  thread stacks           60 MB   flat
  code cache              50 MB   flat
  direct buffers          40 MB   flat
  native malloc / arenas 800 MB   ✗ +50 MB per day

The trace: which tool answers which question.

diagnosis branches
NMT diff shows a JVM category growing  → fix that category (Thread, Class, Code ...)   ✓
NMT diff flat, RSS still climbs        → outside JVM accounting: pmap diff, MALLOC_ARENA_MAX, jemalloc

What you see: a flat NMT diff next to growing anonymous mappings.

console
# illustrative output
$ jcmd 4242 VM.native_memory summary.diff
Total: reserved=5367MB +0MB, committed=2655MB +0MB      ✗ nothing to blame
$ pmap -x 4242 | grep anon     # 64 MB blocks = glibc malloc arenas
00007f3a54000000   65536   65412   65412 rw---   [ anon ]
00007f3a58000000   65536   64980   64980 rw---   [ anon ]

Why: native memory freed inside a glibc arena is not returned to the OS, and the heap dump cannot see it anyway.

The fix: close the stream, and cap the arenas.

Unzip.java (fixed)runs offline
byte[] unzip(Path p) throws IOException {
    try (InputStream in = new GZIPInputStream(Files.newInputStream(p))) {   // ✅ FIX
        return in.readAllBytes();
    }
}
// ✅ FIX (arenas): MALLOC_ARENA_MAX=2 in the container environment

What you see now: the RSS-minus-heap gap stops growing.

RSS minus heap, per day
# illustrative output
before:  day 1  0.90 GB   day 2  0.95 GB   day 3  1.00 GB   ✗ +50 MB/day
after:   day 1  0.90 GB   day 2  0.90 GB   day 3  0.91 GB   ✓ flat

Land it Heap dumps only see the heap — when RSS and heap disagree, Native Memory Tracking is the tool that assigns blame.

Likely follow-ups
"NMT says everything is flat, pmap shows growth in anonymous mappings of 64MB each. What is that?"

Those are glibc malloc arenas. Each arena reserves 64MB of address space on 64-bit Linux, and glibc creates up to eight arenas per core to reduce lock contention between threads calling malloc.

Memory freed inside an arena is returned to that arena, not to the operating system, and fragmentation means the arena's high-water mark keeps growing even when the live native data does not.

Sources of native malloc in a JVM include the JIT, zlib inflaters, JNI libraries, and some parts of the JDK itself.

The fix is MALLOC_ARENA_MAX=2 in the container environment, which caps arenas and typically recovers hundreds of megabytes, or switching the allocator with LD_PRELOAD to jemalloc, which fragments less and can also produce allocation profiles that name the native call sites.

"How do you catch the unclosed GZIPInputStream class of bug before production?"

With a resource-leak check in the build and a runtime tripwire. Static analysis, such as Error Prone's or SpotBugs' unclosed-resource checks, flags an InputStream created outside try-with-resources.

At runtime, the JDK's own finalizer statistics tell the story: if jcmd <pid> GC.finalizer_info or the JFR jdk.FinalizerStatistics event shows java.util.zip.Inflater instances being finalized, code is relying on GC to close them.

Under load test, I watch NMT's Internal and Other categories for growth while the heap stays flat, which is exactly the symptom.

The Inflater holds around 32KB of zlib memory each, so ten thousand unclosed ones between GCs is 300MB of native memory that a heap dump would show as ten thousand tiny wrapper objects.

"What overhead does NMT add, and would you leave it on permanently?"

Summary mode adds a header to every native allocation the JVM makes and a counter update per category, which measures at around 5 percent of native allocation throughput and a small constant memory overhead; for most services the end-to-end CPU cost is under 1 percent.

Detail mode also records a stack trace per allocation and is markedly more expensive, so I use it only in a targeted diagnosis.

I do leave summary mode on in production for services that have had native memory problems, and I export the category totals as metrics via a small script that runs jcmd VM.native_memory summary on a schedule, so heap-versus-RSS divergence alerts early.

It must be set at startup; there is no way to turn it on for a running process.

"The growth is 50MB a day and the pod restarts weekly for deploys anyway. Do you still fix it?"

I quantify it and then decide, but I lean yes.

At 50MB per day with 2GB of headroom, time-to-failure is 40 days, so the weekly deploy masks it; but a deploy freeze, a reduction in pod memory, or a change to a longer-lived instance turns it into an outage with no warning.

The fix cost is usually small once the attribution is known — a missing close(), an arena environment variable.

What I refuse to do is leave it unquantified: I record the slope, the time-to-failure, and the mitigation in the runbook, and I add the RSS-minus-heap alert so the assumption "deploys restart it" is monitored rather than trusted.

A known, measured, alerted leak is a debt; an unmeasured one is a trap.

Q140. "Why do people set -Xms equal to -Xmx in containers?"

Reveal answer

Strong answer Because in a container the memory is already bought.

When -Xms is lower than -Xmx, the JVM starts small and grows the heap in steps. Each resize costs something:

  • Extra collections triggered by the shrinking free band.
  • Heuristic churn while the collector re-learns its sizing.
  • Page faults as freshly committed memory is touched for the first time.

All of it lands during warmup, exactly when the service is also compiling hot code.

That elasticity only pays when memory saved can be used elsewhere; inside a container with a fixed limit reserved for this pod, there is no elsewhere — the limit is paid for whether the JVM commits it or not.

Setting them equal makes the footprint predictable, which is what container budgeting needs, and removes a whole class of warmup wobble. Latency-critical services add -XX:+AlwaysPreTouch to fault every page in at startup — slower boot, no first-touch stalls later.

The honest nuance: on shared or oversubscribed hosts where returning memory matters, an elastic heap and G1's ability to uncommit are the neighborly choice — but for one JVM in one sized container, fixed is right.

Picture it the committed heap during warmup with and without -Xms equal to -Xmx, read from the GC log.

The setup: the same service started with two flag sets.

flags
A:  java -Xms256m -Xmx2g  -jar app.jar        # elastic: starts small, grows in steps
B:  java -Xms2g   -Xmx2g  -XX:+AlwaysPreTouch -jar app.jar   # fixed: committed up front

Make the invisible visible: the budget of a container with a 4 GB limit.

pod budget
# illustrative output
pod limit 4096 MB (paid for whether the JVM commits it or not)
  heap 2048 (Xms = Xmx)  + metaspace 120 + code cache 50 + stacks 60 + direct 40 ≈ 2.3 GB   ✓ under the limit

What you see: the number in parentheses is the committed heap; watch it during warmup.

gc.log, flags A
# illustrative output
GC(3)  Pause Young (Normal) (G1 Evacuation Pause)  230M->41M(256M)    12.1ms
GC(9)  Pause Young (Normal) (G1 Evacuation Pause)  480M->88M(512M)    14.0ms   ✗ resized
GC(17) Pause Young (Normal) (G1 Evacuation Pause)  950M->120M(1024M)  15.3ms   ✗ resized

What you see now: flags B: the total never moves.

gc.log, flags B
# illustrative output
GC(3)  Pause Young (Normal) (G1 Evacuation Pause)  1500M->41M(2048M)  10.2ms   ✓
GC(9)  Pause Young (Normal) (G1 Evacuation Pause)  1500M->88M(2048M)  10.9ms   ✓

Land it Inside a container the memory is yours either way — commit it up front and make the JVM's footprint boring and predictable.

Likely follow-ups
"What does AlwaysPreTouch actually do, and what does it cost at startup?"

It makes the JVM write to every page of the committed heap during initialization, so the operating system allocates physical memory for all of it up front rather than on first use.

Without it, the first time each 4KB page is touched — usually during the first young collections and allocations — the kernel takes a page fault, zeroes the page, and maps it, which can add tens of milliseconds of scattered stalls to the first minutes of traffic.

With it, an 8GB heap takes a few seconds longer to start, because zeroing 8GB is bounded by memory bandwidth, and the process's RSS is the full heap from the first second.

That matters in a container because the memory is committed immediately, so an over-generous heap gets OOMKilled at startup rather than a week later. JDK 17 and later pre-touch in parallel across GC threads.

"Does this advice still hold with ZGC, which is designed to uncommit memory?"

Partly. ZGC and G1 both uncommit unused heap back to the operating system by default — G1 after a periodic or full collection and since JDK 12 on a timer with -XX:G1PeriodicGCInterval, ZGC with -XX:ZUncommitDelay, 300 seconds by default — which is useful on shared hosts.

In a dedicated container it is mostly churn: memory is uncommitted at night and recommitted with page faults in the morning.

Setting -Xms equal to -Xmx disables uncommit for both collectors, since the JVM will not shrink below the initial size, and that is what I want for one JVM in one sized pod.

For ZGC specifically I also set -XX:SoftMaxHeapSize below -Xmx, so the collector aims for a smaller footprint while keeping the emergency room.

"What goes wrong if you set -Xms equal to -Xmx on a shared VM with several JVMs?"

Each JVM commits its whole heap regardless of use, so the host's physical memory is fully claimed by heaps that are mostly empty, and the operating system has nothing to give to the page cache, to a JVM that genuinely needs its full heap, or to a new process.

If the host is overcommitted, one JVM touching its heap forces another's pages to swap, and a swapped JVM heap turns every GC into a disk-bound crawl.

On a shared host the elastic default is the neighborly choice: a modest -Xms, a realistic -Xmx, and G1's uncommit so idle JVMs give memory back.

The fixed heap is right when the memory is dedicated, which is the container case — the advice follows the deployment model, not a universal rule.

"Do the same arguments apply to metaspace and the code cache?"

Less so, and the flags work differently.

Metaspace grows on demand and cannot be pre-committed in the same way; -XX:MetaspaceSize sets the threshold that triggers the first metaspace-driven GC, not an initial commit, so raising it to the expected steady-state size avoids a few pointless collections during startup while classes load.

The code cache is reserved at -XX:ReservedCodeCacheSize and committed as compiled code is produced, with -XX:InitialCodeCacheSize setting the initial commit; it is small enough, 240MB reserved, that pre-committing it would not matter.

The common thread is that all of these count against the container's limit when committed, so the budget I write for a pod lists heap, metaspace cap, code cache, thread stacks, and direct memory as separate lines that add up to less than the limit.

06 · Threads & monitorsThreads, synchronized & the Monitor — Q141–Q180

This is the section interviewers use to separate people who have memorized "synchronized makes it thread-safe" from people who actually understand what the JVM (Java Virtual Machine — the program that runs your compiled Java code) is doing with locks and memory. Every question here lives at the language level: what a monitor really is, what synchronized and volatile actually promise, and how the classic coordination bugs — races, deadlocks, lost wakeups — happen and get fixed. Answer these well and the whole concurrency round tilts in your favor.

Drill · Thread lifecycle & basics

These questions test whether you can read what a thread is doing from its state alone — the skill that turns a wall of stack traces into a diagnosis.

Q141. "Walk me through the six thread states in Java, and tell me what each one means when you see it in a thread dump."

Reveal answer

The real test Not the list — whether you know that BLOCKED and WAITING mean two completely different problems.

Strong answer A thread dump — a snapshot of every thread's state and stack trace — labels each thread with one of six states, and each one tells a different story:

  • NEW — the Thread object exists but start() has not been called; it has no operating system thread yet.
  • RUNNABLE — the thread is running or is ready to run and waiting for a CPU. Threads stuck in native I/O, like a socket read, also show as RUNNABLE, which surprises people.
  • BLOCKED — the thread is trying to enter a synchronized region and another thread holds that lock. BLOCKED always means lock contention.
  • WAITING — the thread deliberately parked itself, inside wait(), join(), or LockSupport.park(), and will not move until another thread signals it.
  • TIMED_WAITING — the same, but with a deadline: sleep(ms), wait(ms), join(ms).
  • TERMINATED — run() has finished.

So in a dump, many BLOCKED threads pointing at one lock means contention on that lock; many WAITING threads means they are parked waiting for a signal or for work that is not arriving.

Picture it the six states as a diagram with the BLOCKED and WAITING transitions marked, and how each looks in a dump.

The setup: a thread that needs a lock the main thread holds, printed at three moments.

ThreadStates.javaruns offline
Object lock = new Object();
Thread t = new Thread(() -> { synchronized (lock) { } });
System.out.println(t.getState());            // NEW
synchronized (lock) {
    t.start();
    Thread.sleep(100);
    System.out.println(t.getState());        // BLOCKED: wants the lock main holds
}
t.join();
System.out.println(t.getState());            // TERMINATED

Make the invisible visible: the states and the transitions between them.

thread states
 NEW ──start()──► RUNNABLE ──run() returns──► TERMINATED
                   │  ▲
  enter synchronized│  │lock acquired          ◄── BLOCKED: "I want a lock someone else holds"
  (lock is taken) ─►BLOCKED
                   │  ▲
  wait() / join() / │  │notify / unpark         ◄── WAITING: "I chose to sleep until woken"
  LockSupport.park()─►WAITING
                   │  ▲
  sleep(ms) / wait(ms)│ │timeout or wake
                   └─►TIMED_WAITING

What you see: the program output, then the same states as a dump labels them.

console
NEW
BLOCKED
TERMINATED
jstack excerpt
# illustrative output
"worker-1" #21 ... waiting for monitor entry
   java.lang.Thread.State: BLOCKED (on object monitor)
        - waiting to lock <0x000000076ab62208> (a com.acme.Cache)      ← contention
"worker-2" #22 ... waiting on condition
   java.lang.Thread.State: WAITING (parking)
        - parking to wait for <0x000000076ab70010> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
"worker-3" #23 ... runnable
   java.lang.Thread.State: RUNNABLE
        at sun.nio.ch.SocketDispatcher.read0(Native Method)            ← blocked in the kernel, still RUNNABLE

Why: BLOCKED means a monitor entry set (contention), WAITING means a deliberate park: the fixes are different.

Land it BLOCKED is "I want a lock someone else holds"; WAITING is "I chose to sleep until someone wakes me" — the fix for each is completely different.

Likely follow-ups
"Why does a thread stuck in a socket read show as RUNNABLE, and how do you tell it apart from a thread actually computing?"

Because the state reflects what the JVM knows, not what the kernel is doing.

Inside a native call like SocketInputStream.socketRead0 or NioSocketImpl.read, the thread has left Java code, the JVM has not parked it, and from the JVM's point of view it is running — the blocking happens in the kernel.

To distinguish it, I read the top frames: a native frame in a socket, file, or database driver method means blocked I/O, while frames in application or library computation with no native frame means real CPU use.

For confirmation I pair the dump with CPU numbers: top -H -p <pid> lists per-thread CPU, and the native thread ID in the dump's nid=0x1a2b field, converted from hex, matches the top row. A RUNNABLE thread with zero CPU is waiting on something outside the JVM.

"Which state does a thread waiting on a ReentrantLock or a BlockingQueue show, and why not BLOCKED?"

WAITING, or TIMED_WAITING with a timeout, because those classes are built on LockSupport.park, not on monitors. BLOCKED is reserved for the monitor entry set — threads waiting to enter a synchronized region.

The dump shows the difference in the frames: a BLOCKED thread says "waiting to lock <0x...>" with the monitor's address, while a thread parked on a ReentrantLock says "parking to wait for <0x...> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)".

So when I count "how many threads are stuck on locks", I have to count both kinds, and to find the owner of a ReentrantLock I look for the "Locked ownable synchronizers" section under each thread, which is only printed when the dump is taken with jstack -l or jcmd Thread.print -l.

"How do you read a dump of 800 threads without going line by line?"

I aggregate. First I group by state with a one-liner like grep -c 'java.lang.Thread.State: BLOCKED' for each state to get the shape: mostly RUNNABLE is a CPU or I/O problem, mostly BLOCKED is contention, mostly WAITING is starvation or a stuck dependency.

Then I group by top frame: grep -A2 'java.lang.Thread.State' dump.txt | grep 'at ' | sort | uniq -c | sort -rn shows the most common place threads are sitting, which is usually the diagnosis in one line.

Then I look for the single lock everyone is waiting on by counting "waiting to lock" addresses. Tools like fastthread.io or IntelliJ's thread dump analyzer do this grouping visually.

And I always take two or three dumps ten seconds apart, because a thread that is in the same frame in all three is stuck, not passing through.

What you see: the aggregation one-liners and the shape they print.

console
# illustrative output
$ grep -A2 'java.lang.Thread.State' dump.txt | grep 'at ' | sort | uniq -c | sort -rn | head -3
    412   at java.lang.Object.wait(Native Method)
    198   at sun.nio.ch.EPoll.wait(Native Method)
     87   at com.acme.Cache.get(Cache.java:42)       ← 87 threads piled on one frame
"What does a virtual thread look like in a thread dump?"

It does not appear in a classic jstack dump at all — only the carrier threads show, named ForkJoinPool-1-worker-N, with a frame indicating they are running a virtual thread.

To see the virtual threads I use jcmd <pid> Thread.dump_to_file -format=json /tmp/threads.json, added in JDK 21, which lists every thread including virtual ones grouped by their thread container — the executor or structured task scope that owns them.

Each virtual thread shows its stack whether mounted or parked, so a million parked virtual threads waiting on the same downstream call are visible as a million entries with the same top frame.

That dump is also the way to find pinned virtual threads: a virtual thread whose carrier shows it in a native frame is one that could not unmount.

Q142. "Should I implement Runnable or extend Thread? Does it actually matter?"

Reveal answer

Strong answer It matters, and the reason is separation of concerns, not style. A Runnable is a description of work; a Thread is the worker that executes work.

Extending Thread welds the two together: the task can now only ever run on its own dedicated thread, it cannot be handed to a thread pool, and because Java allows only one superclass, you have spent your single inheritance slot on plumbing.

Implementing Runnable (or Callable when you need a return value) keeps the task portable — the same object can run on a new thread today and on a shared pool tomorrow.

There is also a subtle correctness angle: a Thread subclass tempts people to add mutable fields to the thread itself, mixing task state with worker state.

Picture it work welded to its worker versus work as a portable object, and what each one allows.

The setup: the same task written both ways.

Tasks.javaruns offline
class LoadTask extends Thread { public void run() { load(); } }      // worker + work welded together
class LoadJob implements Runnable { public void run() { load(); } }  // work only

Make the invisible visible: which objects exist in each design.

object picture
extends Thread:   [LoadTask = Thread + work]        1 object, 1 thread, one use
implements Runnable:
   [LoadJob = work] ──► new Thread(job)      today
   [LoadJob = work] ──► pool worker thread   tomorrow

What you see: the same actions against both designs.

Task as Thread subclass versus Runnable
Actionextends Threadimplements Runnable
Start it once on its own threadWorks: task.start()Works: new Thread(job).start()
pool.submit(task)Silently wrong: it compiles because Thread is a Runnable, but run() executes on the pool thread and the Thread object itself is never startedWorks
Start it a second timeFails: IllegalThreadStateExceptionWorks: new Thread each time
Also extend another classCompile error: only one superclassWorks

Why: a Thread is a worker with an OS-thread lifecycle; a Runnable is only a description of work.

Land it I write tasks as Runnable and let something else own the threads — in nine years I have extended Thread approximately never.

Likely follow-ups
"How do you create threads in modern Java, if not new Thread?"

Through a builder or an executor. Since JDK 21, Thread.ofPlatform().name("worker-", 0).daemon(false).factory() produces a ThreadFactory with named threads that I hand to a ThreadPoolExecutor, and Thread.ofVirtual().name("req-", 0).start(task) starts a virtual thread directly. For pools, Executors.newThreadPerTaskExecutor(factory) or newVirtualThreadPerTaskExecutor() for virtual threads, and an explicit ThreadPoolExecutor for platform threads.

The point is that the code that describes work — the Runnable or Callable — never mentions threads, and the code that chooses the threading strategy is in one place with a name.

Raw new Thread(runnable).start() survives only in tiny scripts and in a single supervised background loop that owns its own lifecycle.

"Runnable versus Callable — what is the practical difference beyond the return value?"

Two things: checked exceptions and result handling. Callable.call() is declared throws Exception, so a task that does I/O can let checked exceptions propagate, and they come back to the submitter wrapped in an ExecutionException from Future.get().

A Runnable.run() cannot throw checked exceptions, so the body must catch and wrap them, and if an unchecked exception escapes, an executor swallows it into the future or, for execute(), hands it to the thread's UncaughtExceptionHandler where it is easy to lose.

That asymmetry is why I submit Callable even for tasks with no result — Callable<Void> returning null — when I want the exception to reach whoever cares. With CompletableFuture, the equivalent is Supplier, which has the same no-checked-exception limitation as Runnable.

What you see: where the exception ends up in each case.

exception pathsruns offline
Future<?> f = pool.submit(() -> { throw new IllegalStateException("boom"); });
f.get();                       // Result: ExecutionException, cause = IllegalStateException ✓
pool.execute(() -> { throw new IllegalStateException("boom"); });
                               // Result: only the thread's UncaughtExceptionHandler sees it ✗ easy to lose
"Is there ever a good reason to subclass Thread?"

One narrow case: when the subclass is the worker abstraction itself, not the task — for example, a framework's event-loop thread that needs per-thread state like a selector or a fast-path local cache, and Netty's FastThreadLocalThread does exactly this to give FastThreadLocal an indexed array instead of a hash map.

In that design the thread has a lifecycle and identity, and tasks are still Runnables handed to it. Outside of building such infrastructure, subclassing is a code smell in review: it usually signals that someone wanted a place to put fields and picked the thread.

The other historical reason, overriding run for a one-off background loop, is better served by a named factory and a Runnable, so the loop can be tested without a thread.

Q143 · Scenario. "A junior wrote a 'parallel' file loader: it creates ten Thread objects in a loop and calls run() on each. It produces correct results but takes exactly as long as the serial version. What happened?"

Reveal answer

The real test Whether you know the difference between calling a method and starting a thread — a classic trap that still catches people.

Strong answer Nothing ran in parallel, because run() is just an ordinary method. Here is how I would confirm and fix it:

  1. The symptom already tells the story: correct results, serial timing. If I took a thread dump during the load, I would see only the main thread doing the work and ten threads still in the NEW state.
  2. The cause: run() is a plain method call, so the calling thread executes the task body itself, one after another. start() is the special method — it asks the JVM to create a real operating system thread and have that thread invoke run(). Skipping start() means no new thread is ever born.
  3. The fix: call start() on each thread, then join() — wait for a thread to finish — on all of them before using the results.
  4. Prevention: modern IDEs and static analyzers flag a direct Thread.run() call as a bug pattern, and using a thread pool instead of raw threads removes the opportunity entirely.

Picture it one thread running three tasks in a row versus three threads overlapping, with the thread name as the evidence.

The setup: three tasks, called with run().

Loader.javaruns offline
for (int i = 0; i < 3; i++) {
    Thread t = new Thread(() ->
        System.out.println("loading on " + Thread.currentThread().getName()), "loader-" + i);
    t.run();                   // ❌ TRAP: a plain method call, no new thread
}

Make the invisible visible: which thread executes each task.

thread picture
run():    main ──[load A]──[load B]──[load C]──            3.0 s, one thread
start():  main     ──start A,B,C──join──
          loader-0 ──[load A]──
          loader-1 ──[load B]──                            ~1.0 s, overlapped
          loader-2 ──[load C]──

What you see: every line names the main thread, and the other threads are still NEW.

console
loading on main
loading on main
loading on main            ✗ no loader-N thread ever existed

Why: start() asks the JVM to create an OS thread that calls run(); run() alone runs on the caller.

The fix: start every thread, then join them all.

Loader.java (fixed)runs offline
List<Thread> ts = new ArrayList<>();
for (int i = 0; i < 3; i++) {
    Thread t = new Thread(() ->
        System.out.println("loading on " + Thread.currentThread().getName()), "loader-" + i);
    t.start();                 // ✅ FIX: start(), not run()
    ts.add(t);
}
for (Thread t : ts) t.join();  // ✅ FIX: wait before using results

What you see now: three different thread names (order may vary).

console
# illustrative output
loading on loader-1
loading on loader-0
loading on loader-2        ✓

Land it start() creates a thread; run() is just a method your current thread executes — the compiler cannot tell them apart for you.

Likely follow-ups
"They fixed it with start(), and now it's faster but results are occasionally wrong. What next?"

Now the threads really run concurrently, and the code that was accidentally safe when serial is racing. The likely shape is that each loader writes into a shared, unsynchronized collection — an ArrayList or HashMap — so concurrent adds lose entries or corrupt the structure.

I confirm by looking for shared mutable state touched from run(), and the fix is to have each thread produce its own result and combine them after join(): a Callable per file returning a list, submitted to an executor, and the results collected from the futures in the main thread.

That design has no shared mutation at all. The lesson to state is that calling start() did not introduce a bug; it exposed one that the serial execution was hiding, which is why "correct results" from the first version proved nothing.

What you see: two loaders appending to one ArrayList; the second write lands on the same slot.

Lost update inside ArrayList.add
StepLoader A: list.add("a")Loader B: list.add("b")size
1reads size = 00
2reads size = 00
3elementData[0] = "a"0
4elementData[0] = "b" ✗ overwrites a0
5size = 11
6size = 1 ✗ one entry lost1
console
# illustrative output
expected 2000 entries, got 1873       ✗ with a shared ArrayList
expected 2000 entries, got 2000       ✓ each thread returns its own list, combined after join()
"What does join() guarantee about visibility of what the thread wrote?"

It is a happens-before edge: everything the joined thread did before it terminated is visible to the thread that returns from join().

That is the Java Memory Model's thread-termination rule, and it is what makes the pattern "start threads, join them, read their results" correct without any volatile or lock on the result fields.

The corresponding edge on the way in is start(): everything the parent did before calling start() is visible inside the child. If the fix uses an executor instead, the same guarantee comes from Future.get(), which happens-after the task's completion.

What has no such guarantee is polling a field to see if the thread is "done" — that read is a data race unless the field is volatile.

"Ten files, ten threads — is that the right degree of parallelism?"

Probably not, and the honest answer is to measure what the loader is bound by.

If the files are on one spinning disk, ten concurrent readers cause seeks and are slower than two; on a fast SSD or a network filesystem, parallelism up to a few times the core count helps because each thread spends most of its time waiting.

If parsing dominates, the useful parallelism is the core count.

So I would use a fixed pool sized from a quick experiment — 2, 4, 8, 16 threads with timing — rather than one thread per file, which also does not scale when tomorrow there are a thousand files.

A parallel stream over the file list is an acceptable quick version for a CPU-bound parse, but not for I/O, because it uses the common pool.

"How would a unit test have caught the original bug?"

By asserting on parallelism rather than on results. A test that records the thread name inside each loader's run() and asserts that more than one distinct name appears would fail immediately, since the original code runs everything on the test thread.

A timing assertion — ten loaders that each sleep 100ms should complete in well under a second — is a rougher version.

Neither is a great permanent test because they test mechanism, not behavior; the durable fix is structural: once the loader is a Callable submitted to an injected ExecutorService, the test can inject a direct executor for determinism and a real pool for a concurrency test, and the run()-versus-start() mistake has no place left to happen.

Q144 · Scenario. "Your service buffers audit events in memory and a background thread flushes them to disk every second. After every deploy, the last few seconds of audit events are missing. Why, and how do you fix it?"

Reveal answer

The real test Whether you understand what marking a thread as daemon actually signs you up for.

Strong answer The flusher is almost certainly a daemon thread — a thread the JVM does not wait for. Here is the reasoning:

  1. The JVM exits as soon as the last non-daemon thread finishes. At that moment every daemon thread is killed abruptly: no finally blocks run, no cleanup happens, it simply stops mid-instruction.
  2. On deploy, the process is asked to shut down, the main threads finish, and the daemon flusher dies with up to a second of events still sitting in its buffer. That matches the symptom exactly — a small, consistent tail of data lost on every restart.
  3. The fix has two parts. First, register a shutdown hook — a thread the JVM runs when it receives a normal termination request — that tells the flusher to stop, performs one final flush, and join()s the flusher so shutdown waits for it. Second, consider making the flusher a normal user thread with an explicit stop signal, so its lifecycle is managed rather than assumed.
  4. Prevention: the rule of thumb is that a daemon thread must never hold data that matters. Daemon status is for genuinely disposable work — cache eviction, metrics ticking — not for anything buffering writes.

Picture it the moment the JVM exits while the daemon flusher is asleep with events in its buffer, row by row.

The setup: a flusher marked as daemon.

AuditFlusher.javaruns offline
Thread flusher = new Thread(() -> {
    while (true) { sleep(1000); flush(buffer); }
}, "audit-flusher");
flusher.setDaemon(true);       // ❌ TRAP: the JVM will kill it mid-flight at exit
flusher.start();

The trace: one row per step at deploy time.

Shutdown with a daemon flusher
Stepmain (user thread)audit-flusher (daemon)buffer
1handles request, buffer.add(e41)sleeping[e41]
2buffer.add(e42)sleeping[e41, e42]
3SIGTERM arrives, main returnsstill in sleep(1000)[e41, e42]
4last non-daemon thread ends, JVM exitskilled, no finally runs ✗lost ✗

What you see: the file is missing the tail.

audit.log
# illustrative output
last line in audit.log: event 40
expected:               events 1..42     ✗ two missing

Why: daemon means the JVM may stop the thread at any instant, and it does not wait for it.

The fix: a shutdown hook that stops the loop, waits for the flusher, and flushes once more.

AuditFlusher.java (fixed)runs offline
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    running = false;                       // ✅ FIX: tell the loop to stop (volatile flag)
    flusher.interrupt();
    try { flusher.join(5_000); } catch (InterruptedException ignored) { }
    flush(buffer);                         // ✅ FIX: one final, bounded flush
}, "audit-shutdown"));

What you see now: the same check after a deploy.

audit.log
# illustrative output
last line in audit.log: event 42
expected:               events 1..42     ✓

Land it "Daemon" means "the JVM may kill this thread mid-write without warning" — so a daemon thread that buffers valuable data is a data-loss bug waiting for a deploy.

Likely follow-ups
"You added the shutdown hook and events are still lost on some deploys. What next?"

Then the hook is not getting the time it needs, or it is not running at all. On Kubernetes, the pod receives SIGTERM, which does run shutdown hooks, but only terminationGracePeriodSeconds — 30 seconds by default — before SIGKILL, and SIGKILL runs nothing.

If the final flush waits for a slow disk or a network sink, it can exceed that. I check the timing by logging the hook's start and end with timestamps and comparing against the pod's termination events.

Then I raise the grace period, make the flush bounded with a timeout so a partial flush beats none, and drain traffic first using a preStop hook so no new events arrive during the flush.

If the hook is not running at all, someone is calling Runtime.halt() or the process is being killed with SIGKILL directly, which I confirm from the exit code: 137 means SIGKILL, 143 means SIGTERM.

What you see: the exit code tells SIGTERM from SIGKILL.

console
# illustrative output
Last State: Terminated   Exit Code: 143   ← SIGTERM, hooks ran
Last State: Terminated   Exit Code: 137   ← SIGKILL, no hook can run ✗
"Are the executor threads from Executors daemon or not, and why does it matter here?"

Threads from the default factory are non-daemon, so an executor that is never shut down keeps the JVM alive after main returns, which is the opposite problem — a hang rather than data loss.

If the team "fixed" that hang by making the factory produce daemon threads, they created this bug: the flusher pool is now killed at exit.

The correct middle is non-daemon threads with an explicit shutdown: shutdown(), then awaitTermination, in the shutdown hook or the container's lifecycle callback, so exit waits for the pool to drain and then proceeds.

The rule is that daemon status is not a lifecycle management tool; it is a statement that a thread's work can be abandoned at any instant, and that is rarely true of anything that holds data.

"What guarantees does a shutdown hook give, and what does it not?"

It runs on normal exit — the last non-daemon thread ending, System.exit, SIGTERM, SIGINT — and all registered hooks start concurrently in unspecified order. It does not run on SIGKILL, on a JVM crash, on Runtime.halt, or on a kernel OOM kill.

Inside a hook, the rest of the JVM is still running — other threads are not stopped — so the hook must coordinate with them explicitly, and it should be fast: there is no built-in timeout, but the thing that sent SIGTERM usually has one.

Logging frameworks often register their own hooks that stop the appenders, so a hook that logs may find its output silently dropped; the fix is to order the shutdown explicitly through the application's lifecycle rather than through independent hooks racing each other.

"Would you keep an in-memory buffer for audit events at all?"

For audit data specifically, I would push back on the design. An in-memory buffer trades durability for throughput, and audit events are the one category where losing a second of data has compliance consequences.

The options are a write-ahead approach — append each event to a local file with a buffered writer that is flushed and synced on a short interval, so the file survives a crash — or a durable queue like Kafka with acknowledgement before the request completes, so the buffer lives outside the process.

If the in-memory buffer must stay for latency reasons, the shutdown hook handles deploys but not crashes, so I would document the maximum loss window and get the audit owners to accept it in writing.

Data-loss tolerance is a product decision, not something a flusher thread decides.

Q145. "Can you use thread priorities to make sure your important work runs first?"

Reveal answer

Strong answer No — and the honest answer is that priorities are hints, not guarantees. setPriority() takes a value from 1 to 10, and the JVM maps it onto whatever the operating system scheduler offers.

On Linux, under the default scheduling policy, that mapping is weak to nonexistent for ordinary processes, so two threads with different Java priorities usually get near-identical CPU time. The specification never promises preference; it only allows the JVM to pass the hint along.

That means any program whose correctness depends on priority — "the consumer has higher priority so it will always drain the queue first" — is broken by design and will fail differently on different machines.

If work genuinely must happen first, you express that with explicit coordination: ordering, queues, or dedicated threads for latency-sensitive work.

Picture it two threads with opposite priorities doing identical work, and the mapping from Java priority to the OS.

The setup: a high and a low priority thread each counting for five seconds.

Priorities.javaruns offline
Thread hi = new Thread(new Counter("high"));  hi.setPriority(Thread.MAX_PRIORITY);   // 10
Thread lo = new Thread(new Counter("low"));   lo.setPriority(Thread.MIN_PRIORITY);   // 1
// ❌ TRAP: expecting hi to finish its work "first" or get far more CPU
hi.start(); lo.start();

Make the invisible visible: what happens to the number on the way to the scheduler.

Java priority on the way to the scheduler
Platform / flagsEffect of setPriority
Linux, default flagsIgnored: all threads run at the same nice value
Linux, -XX:+UseThreadPriorities -XX:ThreadPriorityPolicy=1Mapped to nice values, but raising needs root or CAP_SYS_NICE
WindowsMapped to OS priorities; visible effect
Virtual threadFixed at NORM_PRIORITY; setPriority is a no-op

What you see: the counters after five seconds on a default Linux JVM.

console
# illustrative output
high (priority 10): 1,018,442,310 iterations
low  (priority  1): 1,017,903,877 iterations     ✗ no preference

Why: priorities are hints the JVM may pass along; the specification promises no preference.

The fix: isolate capacity instead of ranking threads.

Pools.javaruns offline
ExecutorService requests   = Executors.newFixedThreadPool(3);   // latency-sensitive work
ExecutorService background = Executors.newFixedThreadPool(1);   // ✅ FIX: can never take more than 1 slot

What you see now: a hard cap, whatever the scheduler decides.

capacity picture
# illustrative output
cores=4   request pool = 3 threads   background pool = 1 thread
background CPU share <= 1 core (25%)     ✓ by construction, not by hint

Land it Priorities may shift scheduling at the margins on some platforms, but I never let correctness or ordering depend on them — that belongs to explicit coordination.

Likely follow-ups
"Then how do you make latency-sensitive work run ahead of background work in one JVM?"

By giving them separate resources rather than separate priorities.

I put request handling on its own pool and background work on a smaller pool, so background work can never occupy more than its share of threads, and I keep the total thread count near the core count so the operating system scheduler is not the arbiter.

If the background work is CPU-heavy, I bound it further with a semaphore or a rate limiter so it yields regularly.

For strict cases, the operating system can do it: run the background work in a separate process at a lower nice value, or in its own pod with a CPU limit.

Inside one process, the only reliable "priority" is capacity isolation — a thread that cannot get a slot in the background pool cannot compete with the request thread that has one.

"Does the JVM map Java priorities to OS priorities at all on Linux?"

Only if you ask. By default on Linux, HotSpot ignores Java priorities entirely for the scheduling policy — all threads run at the same nice value.

The flag -XX:ThreadPriorityPolicy=1 together with -XX:+UseThreadPriorities maps Java priorities onto nice values, but lowering nice below zero requires root or the CAP_SYS_NICE capability, so in a container it silently fails to raise anything and can only lower the priority of low-priority threads.

On Windows the mapping is real and priorities have visible effects, which is where the folklore came from.

So a program that behaved differently on a developer's Windows machine and a Linux server, because of priorities, is a real thing I have seen, and it is the strongest argument for never depending on them.

"What about virtual threads — do they have priorities?"

No. A virtual thread's priority is fixed at Thread.NORM_PRIORITY, and setPriority on it is a no-op by specification. Virtual threads are scheduled by a ForkJoinPool in first-in-first-out order onto carrier threads, and there is no way to express "this virtual thread first".

That is deliberate: the design assumes that scheduling fairness among a million lightweight threads is not something the application should tune per thread.

If ordering matters, the same answer applies as for platform threads — separate executors, bounded concurrency with semaphores, or an explicit queue with an ordering discipline.

Virtual threads also do not yield for a higher-priority thread; they unmount only when they block, so a CPU-bound virtual thread holds its carrier until it finishes or parks.

Q146 · Scenario. "Your batch job finishes, main() returns, the logs say 'done' — but the Java process never exits and the pipeline hangs. What is going on?"

Reveal answer

Strong answer The JVM does not exit when main() returns — it exits when the last non-daemon thread finishes. main is just one user thread among possibly many. The diagnosis:

  1. Take a thread dump of the hung process and look for threads that are alive and not marked daemon. Every such thread is a vote to keep the process running.
  2. The usual culprits: a thread pool that was created but never shut down (pool workers are non-daemon by default), a scheduled timer still ticking, or a homegrown worker thread looping on a flag nobody set.
  3. Fix the specific leak: shut the pool down explicitly when the job completes, or stop the worker with a proper signal. As a design choice, threads that exist purely to serve others — and hold nothing precious — can be created as daemon threads so they never block exit.
  4. The blunt instrument is System.exit(), which terminates regardless of live threads — acceptable in a batch main, but it papers over the leak rather than fixing it, and it will skip any in-flight work those threads were doing.

Picture it the thread inventory after main returns: main is gone, one non-daemon pool thread remains, and it keeps the JVM alive.

The setup: a batch job whose pool is never shut down.

Batch.javaruns offline
public static void main(String[] args) {
    ExecutorService pool = Executors.newFixedThreadPool(4);
    pool.submit(job);
    System.out.println("done");        // main returns here
    // ❌ TRAP: pool.shutdown() never called; pool threads are non-daemon
}

Make the invisible visible: who is still alive after main returns.

thread inventory
main                (exited)
pool-1-thread-1     user thread, parked in LinkedBlockingQueue.take   ✗ keeps the JVM alive
Reference Handler   daemon
Finalizer           daemon
Signal Dispatcher   daemon

What you see: the process after the log says done, and the thread lines that give it away.

console
# illustrative output
$ java -jar batch.jar
done
                                  ← prompt never returns
$ jstack 4242 | grep '^"' | grep -v daemon
"pool-1-thread-1" #21 [4262] prio=5 os_prio=0 ...

Why: the JVM exits when the last non-daemon thread ends, and main is only one of them.

The fix: give the pool an owner that closes it.

Batch.java (fixed)runs offline
public static void main(String[] args) {
    try (ExecutorService pool = Executors.newFixedThreadPool(4)) {   // ✅ FIX: close() = shutdown + await (JDK 19+)
        pool.submit(job);
    }
    System.out.println("done");
}

What you see now: the process ends and the exit code reaches the pipeline.

console
$ java -jar batch.jar
done
$ echo $?
0                                  ✓

Land it User threads keep the JVM alive and daemon threads do not — a hanging process at exit is always an inventory question: which non-daemon thread did we forget to stop?

Likely follow-ups
"How do you identify the specific thread that is holding the JVM open from the dump?"

Every thread line in a jstack dump includes daemon if the thread is a daemon, so I filter for lines that do not: grep '^"' dump.txt | grep -v daemon.

The JVM's own threads — Reference Handler, Finalizer, Signal Dispatcher, compiler threads — are daemons, and main has already exited, so what remains is short.

Typical survivors are pool-N-thread-1 parked in LinkedBlockingQueue.take, which is an executor that was never shut down; a Timer-0 thread, which is a java.util.Timer created without the daemon flag; a database pool's housekeeping thread; or a client library's event loop, like an HTTP client or a message consumer that was never closed.

The name and the top frame together usually identify the owner without further work.

What you see: the filtered dump keeps only the user threads.

console
# illustrative output
$ grep '^"' dump.txt | grep -v daemon
"pool-1-thread-1" #21 [4262] prio=5 ...       ← executor never shut down
"Timer-0" #22 [4263] prio=5 ...               ← java.util.Timer without the daemon flag
"Is System.exit() acceptable at the end of a batch main?"

It is acceptable as a final safety net, but I do it after a proper shutdown, not instead of one.

The sequence I write is: run the job, close every resource and executor explicitly, and then System.exit(exitCode) with a code that reflects success or failure, because the pipeline reads the exit code. The exit call runs shutdown hooks, so logging and metrics still flush.

What I avoid is exiting from deep inside the code, where an exception path might skip it, or calling it before the pool has drained, which discards in-flight work.

In a service, System.exit is a different matter: it kills the container's other threads mid-request, and a library calling it is a bug I would flag in review.

"What about an executor that must live for the process lifetime — should its threads be daemon?"

It depends on whether it can hold work that matters. A pool that runs metrics publishing or cache refresh can be daemon; if the process exits, abandoning that work is fine.

A pool that runs the batch's actual tasks must not be daemon, because a daemon worker killed mid-task loses the task silently.

For the process-lifetime pool, the clean design is non-daemon threads plus a shutdown hook that calls shutdown() and awaitTermination(), so the JVM's exit is delayed exactly as long as the work in flight, and nothing is abandoned.

Marking threads daemon to avoid writing the shutdown code is the shortcut that produces the audit-loss bug from a few questions ago; the two questions are the same problem from opposite sides.

"How would you make this class of hang impossible in a new codebase?"

By making every executor's lifetime owned by something with a close method.

In Spring, executors are beans with destroyMethod set so the context shutdown stops them; in plain Java, since JDK 19 ExecutorService implements AutoCloseable, and close() does shutdown-and-await, so a try-with-resources around the pool in main guarantees the drain.

I add a build-time rule — an ArchUnit test or Error Prone check — that forbids Executors.new* and new Thread outside a designated package, so every pool goes through a factory that registers it for shutdown and names its threads.

Then a hang at exit becomes a bug in one factory rather than a hunt across the codebase.

Drill · The monitor & what synchronized really locks

Every question here reduces to one discipline: name the exact object whose lock is taken — because every synchronized bug in this group is a thread locking a different object than the one you thought.

Q147. "What actually is a monitor in Java? Draw me the mental picture."

Reveal answer

The real test Whether "synchronized" is a magic word to you or a mechanism you can describe part by part.

Strong answer A monitor is the built-in lock that every Java object carries — every single object, from a domain entity to new Object(). The mental picture is a room with one key and three places a thread can be:

  • The owner — the one thread currently holding the lock, executing inside a synchronized region on that object. There can be at most one.
  • The entry set — the crowd at the door: threads that hit a synchronized block on this object while someone else owns it. These show as BLOCKED in a thread dump.
  • The wait set — a side lounge: threads that were inside, called wait(), gave the key back, and are now parked until someone calls notify() or notifyAll(). These show as WAITING.

When the owner leaves, one thread from the entry set gets the key. When the owner calls notify(), a thread moves from the lounge back to the crowd at the door — it still has to reacquire the key before it runs.

Picture it one lock drawn as owner, entry set and wait set at five successive moments.

The setup: three threads and one lock object, with T1 using wait().

MonitorDemo.javaruns offline
final Object lock = new Object();
// T1: synchronized (lock) { while (!ready) lock.wait(); work(); }
// T2: synchronized (lock) { ready = true; lock.notify(); }
// T3: synchronized (lock) { work(); }

Make the invisible visible: the state of the monitor after each event.

Monitor state over time
MomentEventOwnerEntry set (BLOCKED)Wait set (WAITING)
t0nobody inside-[][]
t1T1 enters synchronizedT1[][]
t2T2 and T3 arrive while T1 holds itT1[T2, T3][]
t3T1 calls lock.wait(): key released, T2 gets itT2[T3][T1]
t4T2 calls lock.notify(): T1 moves to the entry set, T2 still ownsT2[T3, T1][]
t5T2 leaves the block, someone from the entry set gets the keyT3 (or T1)[T1][]

What you see: the same moment t3 as a thread dump, all three threads naming one address.

jstack excerpt
# illustrative output
"T3" ... java.lang.Thread.State: BLOCKED (on object monitor)
        - waiting to lock <0x000000071b2c0d10> (a java.lang.Object)
"T1" ... java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x000000071b2c0d10> (a java.lang.Object)
"T2" ... java.lang.Thread.State: RUNNABLE
        - locked <0x000000071b2c0d10> (a java.lang.Object)

Why: notify() only moves a thread from the wait set to the entry set; it still has to win the key.

Land it One owner, a queue at the door, a lounge of waiters — every synchronized and wait/notify rule in Java falls out of that one picture.

Likely follow-ups
"When the owner leaves, which thread in the entry set gets the lock? Is it fair?"

It is not fair, deliberately.

HotSpot's monitor implementation hands the lock to a waiting thread in roughly last-in-first-out order for recently blocked threads, and it also allows barging: a thread that arrives just as the lock is released can take it with a single compare-and-swap before any parked thread is woken.

That is faster because the barging thread is already running on a CPU, while waking a parked thread costs a scheduler round-trip.

The consequence is that under sustained contention a particular thread can be passed over repeatedly — starvation is possible in principle, though rare in practice because critical sections are short. If fairness matters, synchronized cannot provide it; a ReentrantLock(true) can, at a large throughput cost.

"After notify(), does the notified thread run immediately?"

No. notify() moves one thread from the wait set to the entry set, and nothing else; the notifying thread still holds the monitor and continues executing until it leaves the synchronized block.

Only then does the notified thread compete for the lock, along with everyone else in the entry set and any barging newcomer.

So there can be an arbitrary delay between the notify and the notified thread actually running, and by then the condition that was signaled may have been consumed by another thread — that is exactly why the condition is re-checked in a while loop.

It also means that calling notify() early inside the block, rather than at the end, costs nothing; the woken thread cannot proceed until the block exits anyway.

"Can a thread be in the wait set of one object and hold the monitor of another?"

Yes, and it is a classic deadlock source. wait() releases only the monitor of the object it is called on.

If a thread holds lock A, then synchronizes on B and calls B.wait(), it releases B and parks, but it still holds A. Any thread that needs A to make progress — including the one that would eventually call B.notify() — is now blocked forever.

In a dump this appears as one thread WAITING on B while listing A under "locked", and other threads BLOCKED on A. The rule that prevents it is to never wait while holding any lock other than the one being waited on, which in practice means keeping wait() calls at the outermost level of locking or, better, using library components that hide the waiting entirely.

The setup: wait() on B while still holding A.

NestedWait.javaruns offline
synchronized (a) {
    synchronized (b) {
        b.wait();       // ❌ TRAP: releases b only; a stays locked, so the notifier needing a is BLOCKED forever
    }
}
"Where do the entry set and wait set physically live, and is this expensive?"

In the inflated ObjectMonitor structure, which is native memory owned by the JVM, not part of the object itself. The object's header holds a pointer to it once inflated.

The entry set is a linked list of parked thread structures, the wait set is another, and each parked thread is blocked on an operating-system primitive — a futex on Linux — so it consumes no CPU. The expense is in the transitions: parking and unparking a thread are system calls costing a few microseconds each, and the cache-line traffic on the monitor under contention can dominate.

Uncontended, none of this exists; the lock is bits in the header. HotSpot deflates idle monitors back to thin locks over time, so a monitor that was contended once does not stay fat forever.

Q148. "Where does the lock physically live, and what is lock inflation?"

Reveal answer

Strong answer Every object starts with a header, and the first machine word of it — the mark word — is a multipurpose field holding the identity hash, the garbage collector's age bits, and the lock state.

When one thread synchronizes on an uncontended object, the JVM takes a thin lock: it uses CAS (compare-and-swap — a single atomic CPU instruction that updates a value only if it still holds the expected old value) to stamp lock information into the mark word.

That is extremely cheap — no operating system involvement at all.

Only when a second thread arrives while the first still holds the lock does the JVM inflate it into a fat monitor: a real data structure with the owner field, entry set, and wait set, backed by operating system parking for the blocked threads.

So the cost of synchronized is tiered: nearly free uncontended, expensive under contention.

One modern note: biased locking — an old optimization that pre-assigned a lock to its first thread — was disabled and then removed in recent JVMs because its bookkeeping cost more than it saved.

Picture it the three lock states of one object, and a timeline showing when each one appears.

The setup: one lock object used by one thread, then by two, then with wait().

LockStates.javaruns offline
Object o = new Object();
synchronized (o) { }                        // one thread, no contention: thin lock
synchronized (o) { synchronized (o) { } }   // reentrant: still thin
// a second thread blocking on o, or o.wait(): the monitor is inflated

Make the invisible visible: what the mark word holds in each state.

lock states
state             mark word holds                          elsewhere
unlocked          hash? | age | lock bits 01
thin (1 thread)   lock bits 00 ("locked")                  owner's lock stack lists o   ✓ one CAS
inflated          pointer to ObjectMonitor (bits 10)       ObjectMonitor { owner, entry set, wait set }

The trace: which action moves the object to which state.

Lock state over time
StepActionLock state
1T1 enters synchronized(o)thin, o on T1's lock stack
2T1 re-enters the same othin, o listed twice
3T2 tries to enter while T1 holds itinflated: ObjectMonitor with entry set [T2]
4someone calls o.wait() or hashes a thin-locked oinflated (also happens here)
5quiet for a whileidle monitors are deflated again

What you see: JFR can record each inflation with its cause.

jfr print
# illustrative output
jdk.JavaMonitorInflate {
  monitorClass = com.acme.Cache
  cause = "Monitor Enter"          ← contention
}

Why: uncontended locking is one CAS on the header; only a collision needs a real, OS-backed structure.

Going deeper Two things have changed here that a JDK 21 or 25 interviewer will expect.

First, the thin-lock implementation: the older scheme, now called legacy stack locking, stored a displaced copy of the mark word in the locking thread's stack frame and wrote a pointer to it into the header.

JDK 21 introduced lightweight locking, which became the default in JDK 23 through -XX:LockingMode=2.

The thread no longer writes its stack address into the header, only a two-bit "locked" state.

It keeps a small per-thread lock stack listing the objects it holds, which is what makes reentrancy work.

As of Aug 2026 the legacy mode has been removed in recent JDKs, so this is the only fast path.

Second, compact object headers, JEP 519 in JDK 25, enabled with -XX:+UseCompactObjectHeaders.

They shrink the header from 12 bytes to 8 by folding the compressed class pointer into the mark word, which is only possible because lightweight locking freed those bits.

A typical heap gets 10 to 20 percent smaller.

Biased locking was disabled in JDK 15 under JEP 374 and removed in JDK 18. Inflation to a full ObjectMonitor still happens on contention, on wait(), and when a thread's lock stack is full.

Land it Uncontended synchronized is a single CAS on the object header — the real cost only appears when threads actually collide, which is why "synchronized is slow" is mostly folklore about contention.

Likely follow-ups
"What happens to the identity hash code when an object is locked? Both live in the mark word."

They conflict, and the JVM resolves it by inflating. The identity hash is computed lazily the first time System.identityHashCode or a default hashCode() is called, and stored in the mark word.

If the object is thin-locked at that moment, or gets hashed and then thin-locked, there is no room for both, so the lock is inflated to a full monitor, and the monitor structure holds the displaced mark word with the hash inside.

That inflation is silent, and it means an object that is both used as a lock and used as a HashMap key with identity hashing always pays the fat-monitor cost — a small argument for using a dedicated lock object with no other role.

With compact headers in JDK 25 the hash bits were also repositioned, but the conflict and the resolution are the same.

"How do you see lock inflation and contention on a running service?"

JFR is the tool. The jdk.JavaMonitorEnter event records every monitor acquisition that blocked longer than a threshold, 20ms by default in the profile settings, with the lock class, the stack trace, and the previous owner, and jdk.JavaMonitorInflate records inflations with the cause.

In JDK Mission Control's lock instances view, the monitors sorted by total blocked time name the hottest lock and the code paths contending for it. For a cheaper live view, a few thread dumps counting BLOCKED threads by lock address is enough to confirm contention.

The number I care about is blocked time per request; if it is a meaningful fraction of the latency budget, I either shorten the critical section or split the lock.

"Does virtual thread pinning relate to this?"

It did, and it was fixed.

Before JDK 24, a virtual thread that blocked while inside a synchronized block — waiting on I/O or on Object.wait — could not unmount from its carrier, because the monitor implementation recorded the owner as the carrier's native thread; the virtual thread was "pinned", the carrier was wasted, and with enough pinned threads the scheduler starved.

JEP 491 in JDK 24 reworked the monitor code so the owner is the virtual thread itself, and a virtual thread can now block inside synchronized and release its carrier like any other blocking operation.

As of Aug 2026 the remaining pinning cases are native frames on the stack and class initializers. The diagnostic is -Djdk.tracePinnedThreads=full on older JDKs or the jdk.VirtualThreadPinned JFR event.

"What is the cost of an uncontended synchronized block in nanoseconds?"

On modern hardware, roughly 10 to 25 nanoseconds for the enter-and-exit pair: a compare-and-swap on the header on the way in, which is an atomic instruction costing 5 to 20 cycles when the cache line is local, and a store on the way out.

That is the same order as a volatile write, and it is why "avoid synchronized, it is slow" is wrong for uncontended locks.

The cost becomes real in three cases: contention, where parking is microseconds; false sharing, where the locked object shares a cache line with hot data; and the loss of JIT optimizations, since the compiler cannot move memory operations across the lock boundary and cannot scalar-replace an object that is synchronized on.

I would measure with JMH before removing a lock for speed, and usually the measurement says leave it.

Q149. "A synchronized method versus a synchronized block — what exactly does each one lock?"

Reveal answer

Strong answer The rule is mechanical, and knowing it resolves half the bugs in this area. A synchronized instance method locks this — the specific object the method was called on.

A synchronized static method locks the Class object, the single runtime object representing the class itself.

A synchronized (expr) block locks whatever object the expression evaluates to — in the bytecode this is an explicit monitorenter and monitorexit on that reference, and the method forms are just shorthand for the same thing.

I prefer the block form with a dedicated lock object for two reasons: it lets me hold the lock for the few lines that need it instead of the whole method, and it keeps my lock private, so no code outside my class can synchronize on the same object and interfere.

Picture it the bytecode of both forms, and which pairs of calls exclude each other.

The setup: a method form, a block form, and a static form on one class.

Counter.javaruns offline
class Counter {
    private final Object lock = new Object();
    private int count;
    synchronized void incA()        { count++; }                         // locks this
    void incB()                     { synchronized (lock) { count++; } } // locks lock
    static synchronized void sInc() { }                                  // locks Counter.class
}

Make the invisible visible: the method form has a flag; the block form has explicit monitor instructions.

javap -c
# illustrative output (constant-pool numbers vary)
void incA();   flags: ACC_SYNCHRONIZED        ← no monitorenter at all; the JVM locks "this"
void incB();
   6: monitorenter                            ← on the reference from the "lock" field
  18: monitorexit
  19: goto 27
  22: astore_2
  24: monitorexit                             ← second exit, in the generated exception handler
  26: athrow

What you see: which pair of concurrent calls can overlap (a and b are two Counter objects).

Does the second call wait for the first?
Call 1Call 2Outcome
a.incA()a.incA() from another threadBlocks: same this
a.incA()b.incA()Runs in parallel: different this
a.incA()a.incB()Runs in parallel: this versus lock
a.incA()Counter.sInc()Runs in parallel: this versus the Class object
Counter.sInc()synchronized (Counter.class) anywhereBlocks: same Class object

Why: the lock is whichever object the keyword names; name the object out loud and the outcome follows.

Land it Always name the object being locked out loud — this, the Class object, or an explicit lock — because every synchronized bug I have debugged came down to two threads locking different objects.

Likely follow-ups
"Why is locking on 'this' considered bad if it works?"

Because this is a public lock: any code holding a reference to the object can write synchronized (obj) and take the same monitor, either by mistake or as a misguided attempt at coordination.

Then a caller who holds the lock across a slow operation blocks every method of my object, and I cannot see it in my code.

It also couples my locking to my inheritance: a subclass that adds synchronized methods shares the lock with the parent's, which may be intended or may create a deadlock through a callback.

A private final lock object keeps the lock's scope inside the class, so the set of places that can acquire it is exactly the lines I wrote. The cost is one extra field.

The one time this is fine is when the class is designed for clients to lock on it, like Collections.synchronizedList, and the documentation says so.

"What does the bytecode for a synchronized method look like versus a block?"

A synchronized method has no monitorenter in its bytecode at all; it has the ACC_SYNCHRONIZED flag in its method descriptor, and the JVM acquires the monitor of this or the class before invoking and releases it on any exit, including an exception.

A synchronized block compiles to an explicit monitorenter on the reference, the body, a monitorexit, plus an exception handler that covers the body and does a second monitorexit before rethrowing — the compiler generates that handler so the lock is released on exceptions too.

Both are equivalent at runtime. The block form's advantage is that the reference is anything I choose and the region is any span I choose; the method form's advantage is that it is impossible to forget the release path, because there is none to write.

"How small should the synchronized region be, and can it be too small?"

It should cover exactly the operations that must be atomic together, and no more — so the rule is not "small" but "complete". Too large is the common mistake: a lock held across a network call or a log statement serializes threads for milliseconds.

Too small is the subtler one: locking each of two operations separately when the invariant spans both, which is the check-then-act race.

My review question is "what invariant does this lock protect?", and then "is every read and write of that invariant's state inside a region holding this same lock?" If the answer is yes, the region is right, regardless of length.

A second consideration is that many tiny lock acquisitions in a loop cost more than one acquisition around the loop, and the JIT will sometimes coarsen them for me, which is itself a sign the region was drawn too fine.

What you see: the check-then-act race when each step is locked separately.

Two separate regions, one invariant
StepThread 1Thread 2stock
1synchronized { ok = stock > 0; } sees true1
2synchronized { ok = stock > 0; } sees true1
3synchronized { stock--; }0
4synchronized { stock--; } ✗-1
"What is lock coarsening and lock elision?"

Two JIT optimizations that change where locks actually happen.

Lock elision is escape analysis applied to locks: if the JIT proves the locked object never escapes the method, no other thread can ever contend for it, so the lock is removed entirely — a StringBuffer used as a local is the textbook case.

Lock coarsening merges adjacent or repeated lock regions on the same object into one: a loop that locks and unlocks the same object each iteration becomes one lock around the whole loop, reducing atomic operations at the cost of holding the lock longer.

Both are correct because the Java Memory Model only promises visibility at lock boundaries, and moving those boundaries outward never removes a guarantee. They are also why microbenchmarks of synchronized on a local object show zero cost — the lock was never there.

Q150 · Scenario. "You made deposit() and withdraw() both synchronized, the unit tests pass, but production still corrupts balances. Looking closer, the service constructs a new Account object per request for the same account row. What's the bug?"

Reveal answer

The real test Whether you understand that the lock belongs to the instance, not to the method or the class.

Strong answer The lock is per-object, and there is no shared object. The reasoning, step by step:

  1. A synchronized instance method locks this. Two requests for account 42 each build their own Account object, so each thread locks its own private monitor. Two monitors, zero mutual exclusion — both threads read the same database row, compute, and write back, and one update silently overwrites the other.
  2. The tests passed because they reused a single Account instance, which is exactly the sharing production does not have. This is why concurrency bugs survive test suites.
  3. The fix is to make the lock follow the logical entity, not the transient object: either a registry that guarantees one canonical object per account id and locks that, or a map of dedicated lock objects keyed by account id.
  4. The senior follow-up: with multiple service instances, no JVM lock can protect a database row at all — correctness must move to the database, with row locking (SELECT … FOR UPDATE) or optimistic versioning. The in-memory lock was only ever guarding one process.

Picture it two Account objects with two monitors guarding one database row, and the lost update row by row.

The setup: a synchronized entity that the service constructs per request.

Account.javaruns offline
class Account {
    private final long id;
    Account(long id) { this.id = id; }
    synchronized void deposit(long amt)  { long b = repo.load(id); repo.save(id, b + amt); }
    synchronized void withdraw(long amt) { long b = repo.load(id); repo.save(id, b - amt); }
}
// service, per request:  new Account(42).deposit(50)   // ❌ TRAP: a new monitor per request

Make the invisible visible: two threads, two objects, two monitors, one row.

memory picture
T1 ─► Account@a1 [monitor M1, owner T1] ─┐
                                          ├─► DB row id=42, balance=100
T2 ─► Account@a2 [monitor M2, owner T2] ─┘        no shared lock ✗

The trace: a deposit of 50 and a withdrawal of 30 racing; the correct result is 120.

Lost update across two monitors
StepThread 1: a1.deposit(50)Thread 2: a2.withdraw(30)DB balance
1takes M1, loads 100100
2takes M2 (free, a different object), loads 100100
3saves 150150
4saves 70 ✗ deposit lost70

What you see: the balance after both calls.

console
# illustrative output
expected balance 120, actual 70      ✗

Why: synchronized protects an object, and two objects for one logical account never exclude each other.

The fix: lock a shared object chosen by account id, with bounded striping.

AccountService.java (fixed)runs offline
private final Object[] stripes = new Object[1024];
{ for (int i = 0; i < stripes.length; i++) stripes[i] = new Object(); }

private Object lockFor(long id) { return stripes[Long.hashCode(id) & 1023]; }   // ✅ FIX: shared per id

void deposit(long id, long amt) {
    synchronized (lockFor(id)) { long b = repo.load(id); repo.save(id, b + amt); }
}
// with several service instances, move this into the database instead (SELECT ... FOR UPDATE)

What you see now: the second call waits for the first.

console
# illustrative output
expected balance 120, actual 120     ✓

Land it synchronized protects an object, not a concept — if two threads hold two different objects for the same logical entity, they were never excluding each other.

Likely follow-ups
"You built a map of lock objects keyed by account ID. What is wrong with that as it grows?"

It is the static-collection leak: every account ever touched gets a lock object that lives forever, and with millions of accounts that is millions of objects plus the map's nodes.

The bounded version is lock striping — Striped.lock(1024) from Guava, or a hand-rolled array of 1024 locks indexed by id.hashCode() & 1023 — which caps memory at a fixed number of locks and accepts that two unrelated accounts occasionally share one, which is harmless for correctness and rarely matters for throughput.

If per-key exclusivity truly matters, a ConcurrentHashMap with compute on the key gives me a per-key critical section with no lock objects to manage, because the map locks the bin during the compute. Either way, the lock-per-entity map is a leak unless it evicts.

"The fix worked in one JVM. Now you scale to three instances and balances corrupt again. What do you do?"

Move the correctness to the database, because no JVM lock can span processes. Two standard shapes. Pessimistic: SELECT ... FOR UPDATE on the account row inside a transaction, so the database serializes concurrent updates of the same row across all instances, at the cost of holding a row lock for the transaction's length.

Optimistic: a version column, with UPDATE accounts SET balance = ?, version = version + 1 WHERE id = ? AND version = ?, and if zero rows are updated, someone else won and I retry — cheaper under low contention, and JPA's @Version does it for me.

For a balance, I actually prefer neither: UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ? is atomic in the database and needs no lock in Java at all.

What you see: the atomic statement that needs no Java lock.

console
UPDATE accounts SET balance = balance - 30 WHERE id = 42 AND balance >= 30;
-- rows updated: 1  → applied     rows updated: 0  → refused, nothing lost
"Why did the tests pass, and how do you write a test that would have failed?"

The tests used one Account object, so they tested the lock in exactly the condition production never had.

A test that would fail builds the scenario honestly: obtain the account through the same service path production uses, twice, from two threads, and run a hundred concurrent deposits and withdrawals against a starting balance, then assert the final balance equals the arithmetic.

With a per-request new Account, that test loses updates within a few hundred iterations and fails reliably. Tools like jcstress exist for the hard cases, but here a plain JUnit test with an executor and a CountDownLatch to start all threads at once is enough.

The general rule is that a concurrency test must create sharing the same way production does, or it tests nothing.

"If you had to keep the per-request object design, is there a way to make synchronized work?"

Only by moving the lock to something that is shared, which means the object is no longer the lock.

An interned key is the tempting shortcut — synchronized (accountId.intern()) — and it is wrong for the reasons in the next question: the string is a global object anyone can lock, and interning has its own cost.

The honest version is a small LockRegistry that maps an ID to a lock object with bounded striping, injected into the service, and the per-request Account objects become plain value holders with no synchronized methods at all.

That is a better design anyway: the entity carries data, the registry carries coordination, and the coordination is in one place where its scope and lifetime can be reasoned about.

Q151 · Scenario. "A teammate wrote synchronized(userId) where userId is a String, to serialize work per user. In staging it worked; in production it occasionally freezes, and the thread dump shows your code blocked on a lock owned by a third-party library. How is that even possible?"

Reveal answer

The real test Whether you know which objects are secretly shared across the whole JVM — and why your lock must be private.

Strong answer Locking on a String means you may be locking on an object you do not own. The chain:

  1. String literals are interned — the JVM keeps one shared copy of each distinct literal, JVM-wide. If any other code in the process, including a library you have never read, synchronizes on an equal literal, you are both taking the same monitor. That is how a foreign library ends up owning "your" lock, and how the two of you can deadlock without sharing a line of code. Small boxed Integer values have the same trap: values from −128 to 127 come from a shared cache, so synchronized(count) on a small integer is a shared lock too.
  2. The bug is double-edged: strings built at runtime are usually not interned, so two requests for the same user may hold two different String objects — and then you get no mutual exclusion at all. The idiom is broken in both directions.
  3. The fix is the private final lock object idiom: private final Object lock = new Object(); — an object nobody else can reach, so nobody else can lock it. For per-user serialization, keep a map from user id to such a lock object and synchronize on the mapped lock.
  4. Prevention: never synchronize on Strings, boxed primitives, or anything a caller handed you; static analysis rules catch this pattern.

Picture it the string pool object shared by unrelated code, and its opposite: runtime strings that share nothing.

The setup: three strings with the same text.

Strings.javaruns offline
String a = "user-42";                // literal: interned, JVM-wide
String b = "user-42";                // the same literal, e.g. inside a library
String c = new String("user-42");    // runtime copy: a different object
System.out.println(a == b);          // true  -> same monitor
System.out.println(a == c);          // false -> different monitor

Make the invisible visible: which monitor each piece of code takes.

memory picture
your code:   synchronized (a)  ─┐
library:     synchronized (b)  ─┴─► [String "user-42" in the pool]   ONE monitor ✗ shared with strangers
request 1:   synchronized (c1) ───► [String@a1]   monitor M1
request 2:   synchronized (c2) ───► [String@a2]   monitor M2          ✗ no exclusion between the requests

The trace: how the freeze happens when the library holds the pooled string.

Foreign owner of your lock
StepLibrary threadYour thread
1synchronized ("user-42"), slow call inside
2still insidesynchronized (userId) where userId is the pooled "user-42" ✗ BLOCKED
3returns, releasescontinues

What you see: your thread blocked on a String owned by a library thread.

jstack excerpt
# illustrative output
"http-exec-7" ... java.lang.Thread.State: BLOCKED (on object monitor)
        - waiting to lock <0x00000007c0a12345> (a java.lang.String)
"lib-poller-1" ... java.lang.Thread.State: RUNNABLE
        - locked <0x00000007c0a12345> (a java.lang.String)      ← the library owns it

Why: you do not control every place that can lock a shared object.

The fix: private locks you own, striped by user.

UserLocks.javaruns offline
private final Object[] locks = new Object[256];
{ for (int i = 0; i < locks.length; i++) locks[i] = new Object(); }   // ✅ FIX: private, final, boring

void serialized(String userId, Runnable work) {
    synchronized (locks[userId.hashCode() & 255]) { work.run(); }
}

What you see now: no thread waits on a String lock.

jstack excerpt
# illustrative output
"http-exec-7" ... RUNNABLE
        - locked <0x00000007d1c0ffee> (a java.lang.Object)      ✓ a private lock

Land it A lock only gives you guarantees if you control every place it can be acquired — which is exactly why the lock object should be private, final, and boring.

Likely follow-ups
"How would you serialize work per user correctly, with bounded memory?"

With lock striping or a per-key compute. Striping: an array of, say, 256 lock objects, and the lock for a user is locks[userId.hashCode() & 255] — bounded memory, private locks, and two users occasionally sharing a stripe is harmless.

Per-key: ConcurrentHashMap.compute(userId, (k, v) -> doWork()) serializes all callers for the same key inside the map's bin lock, with no lock objects at all; the constraint is that the work must be short and must not touch the same map, or it deadlocks.

For longer work per user I use a ConcurrentHashMap<String, ReentrantLock> with reference counting so entries are removed when the last user leaves, or Guava's Striped.lazyWeakLock. What all of these share is that the lock is an object I own.

"Why is locking on a boxed Integer or a Boolean also broken?"

Same two failure modes.

Integer.valueOf caches values from −128 to 127, so synchronized (Integer.valueOf(5)) takes the same monitor as any other code locking on the number five anywhere in the JVM, while values outside the cache produce a fresh object each time and give no exclusion at all.

Boolean is worse: there are exactly two instances, Boolean.TRUE and Boolean.FALSE, so locking on a boolean field is locking on a global.

Java 16 made this explicit by deprecating the wrapper constructors and by emitting a warning for synchronized on a value-based class — -Xlint:synchronization — because Valhalla value classes will have no monitor at all.

So this is not only a correctness problem today; it is code that will not compile in a future Java.

"The dump showed a library owning your lock. How did you actually find which library?"

From the monitor address. The BLOCKED thread's dump line says waiting to lock <0x00000007c0a12345> (a java.lang.String), and somewhere in the same dump another thread's frames show locked <0x00000007c0a12345> — that thread's stack names the library class holding the monitor.

If the owner is in a native frame or the dump was not taken with -l, I take the dump again with jcmd <pid> Thread.print -l. JFR makes it easier: the jdk.JavaMonitorEnter event records the previous owner's thread for every long block.

Once I know the library, a search of its source for synchronized on a String usually finds an interned constant, and the fix on my side is simply to stop sharing the string as a lock.

"What analysis rule catches this at build time?"

Several tools have it. Error Prone has no dedicated check but -Xlint:synchronization from javac warns on value-based classes, which covers boxed types. SpotBugs has DL_SYNCHRONIZATION_ON_SHARED_CONSTANT, DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE, and DL_SYNCHRONIZATION_ON_BOOLEAN, which flag exactly these. SonarQube's rule S1860 is "synchronization should not be based on Strings or boxed primitives".

I enable these in the build as errors, not warnings, and I add a lightweight ArchUnit or custom check that any synchronized (x) where x is a method parameter gets a review comment, since a caller-supplied lock is the general form of the problem.

The rule in words is that a lock must be a private final field of a type nobody else holds.

Q152. "What does static synchronized actually lock, and what does that imply?"

Reveal answer

Strong answer A static synchronized method locks the Class object — the single runtime object that represents the class itself, the same one you get from MyClass.class. Three consequences follow.

First, there is exactly one such lock per class per class loader, shared by every instance and every caller, so two threads cannot be inside any static synchronized method of that class at the same time — even different methods.

Second, this lock is completely separate from any instance's monitor: holding the class lock says nothing about this.

Third, because the Class object is globally reachable, any code anywhere can write synchronized (MyClass.class) and contend with you — the same "public lock" weakness as locking on this, one level up.

When static state needs guarding, I prefer a private static final Object lock so the lock stays under my control.

Picture it the one Class-object monitor against the per-instance monitors, and what a thread dump shows for it.

The setup: static and instance synchronized methods in one class.

Registry.javaruns offline
class Registry {
    static synchronized void put(String k) { }   // locks Registry.class
    static synchronized void get(String k) { }   // the same lock, even though it is another method
    synchronized void inst() { }                 // locks this
}

Make the invisible visible: one class-wide key, many separate instance keys.

lock picture
Registry.class monitor   ← put(), get(), and synchronized (Registry.class) anywhere
r1 monitor               ← r1.inst()
r2 monitor               ← r2.inst()         three unrelated locks

What you see: which pairs of calls wait.

Which calls overlap?
Call 1Call 2Outcome
Registry.put()Registry.get()Blocks: both lock the Class object
Registry.put()r1.inst()Runs in parallel: different monitors
r1.inst()r2.inst()Runs in parallel: different instances
Registry.put()synchronized (Registry.class) elsewhereBlocks: same object
jstack excerpt
# illustrative output
"t2" ... java.lang.Thread.State: BLOCKED (on object monitor)
        - waiting to lock <0x000000076b001a40> (a java.lang.Class for com.acme.Registry)

Why: the Class object is the monitor for static synchronized, and it is a public, global object.

The fix: a private lock for static state, or no lock at all.

Registry.java (fixed)runs offline
private static final Object LOCK = new Object();    // ✅ FIX: private, under my control
private static final LongAdder hits = new LongAdder(); // ✅ FIX: counters need no lock

Land it static synchronized means "one lock for the whole class" — powerful for guarding static state, and a completely different monitor from any instance lock.

Likely follow-ups
"You said one lock per class per classloader. When does that distinction bite?"

In any environment with multiple classloaders loading the same class: application servers with one loader per deployed application, OSGi, plugin systems, and test frameworks that isolate tests.

Each loader creates a distinct Class object for com.acme.Registry, so two applications on one Tomcat each have their own Registry.class lock and their own static fields — static synchronized gives no exclusion between them, which is usually what you want, but it surprises teams who expected a JVM-wide singleton.

The reverse bite is a shared library in the container's common loader: its class lock is truly JVM-wide, so a static synchronized method in a logging or JDBC library serializes every application on the server.

That is one reason library authors avoid class-level locks on hot paths.

"What happens when a static synchronized method and a static initializer interact?"

Class initialization uses its own lock, the initialization lock, which is distinct from the Class object's monitor, but the two can still interact in a deadlock.

Thread A starts initializing class X, whose static initializer calls into class Y; thread B starts initializing Y, whose initializer references X. Each waits for the other's initialization to complete — a class-initialization deadlock, which shows in a dump as two threads RUNNABLE or WAITING inside <clinit> frames with no monitor in sight.

The rule is to keep static initializers free of cross-class calls that could initialize each other, and never to start threads or take application locks inside <clinit>. JDK 17 and later improve the diagnostic: -Xlog:class+init=info logs initialization order.

The setup: two classes whose initializers need each other.

InitCycle.javaruns offline
class X { static { Y.touch(); } static void touch() { } }
class Y { static { X.touch(); } static void touch() { } }
// thread A: first use of X, thread B: first use of Y  → each waits for the other's <clinit> ✗
"How would you protect static state without a class-level lock at all?"

By not having mutable static state, which is the design most teams eventually arrive at.

A registry that must be shared becomes an instance owned by the dependency-injection container, scoped as a singleton, with its own private lock or, better, built on a ConcurrentHashMap or an AtomicReference to an immutable snapshot so no lock is needed.

Static final fields initialized once are fine — class initialization guarantees they are safely published.

If a static mutable field is unavoidable, a private static final Object LOCK = new Object() or a private static final ReentrantLock keeps the lock private, and an AtomicLong or LongAdder handles the counter case without any lock.

The class object's monitor is the one choice I would never make on purpose.

Q153 · Scenario. "A class has an instance method synchronized void record() and a static synchronized void reset(), and both touch the same static counter. Under load the counter goes negative, which should be impossible. Why?"

Reveal answer

Strong answer The two methods are synchronizing on two different monitors, so they never exclude each other:

  1. record() is an instance method, so it locks this — the particular object it was called on. reset() is static, so it locks the Class object. Those are two unrelated locks; a thread inside record() and a thread inside reset() run fully concurrently against the same static counter.
  2. The interleaving that makes it negative: record() reads the counter, reset() zeroes it, record() writes back its stale computed value, and later arithmetic drives it below zero. Classic lost update.
  3. The rule being violated: every access to a piece of shared state must go through the same lock. Which lock is a free choice — but it must be one lock, chosen once.
  4. The fix: the data is static, so the lock must be class-level — either make both operations static synchronized, or better, introduce one private static final Object lock and have both methods synchronize on it. Instance monitors are simply the wrong scope for static data, because every instance brings its own.

Picture it two methods taking two different monitors, and the interleaving that drives the counter below zero.

The setup: static data guarded by an instance lock in one method and the class lock in another.

Quota.javaruns offline
class Quota {
    static int count = 5;
    synchronized void record()       { if (count > 0) { count--; } }   // locks this   ❌ TRAP
    static synchronized void reset() { count = 0; }                    // locks Quota.class
}

Make the invisible visible: two padlocks on two different doors.

lock picture
record()  ─► monitor of "this"            ┐
                                           ├─ both touch static count; nothing excludes them ✗
reset()   ─► monitor of Quota.class       ┘

The trace: one row per step; the check and the decrement are separated by a reset.

record() versus reset()
StepThread 1: q.record() (holds this)Thread 2: Quota.reset() (holds Class)count
1if (count > 0) reads 5, true5
2enters, the Class lock is free5
3count = 00
4count-- reads 0, writes -1 ✗-1

What you see: the counter after a stress run.

console
# illustrative output
count after 100000 record()/reset() pairs: -3     ✗ should never be negative

Why: mutual exclusion exists only between sections that take the same monitor.

The fix: one private lock for both.

Quota.java (fixed)runs offline
class Quota {
    private static final Object LOCK = new Object();   // ✅ FIX: one lock, chosen once
    private static int count = 5;
    void record()       { synchronized (LOCK) { if (count > 0) { count--; } } }
    static void reset() { synchronized (LOCK) { count = 0; } }
}

What you see now: the same stress run.

console
# illustrative output
count after 100000 record()/reset() pairs: 0      ✓ never below zero

Land it Mutual exclusion is a property of one shared monitor, not of the keyword — mixing instance and static synchronized on the same data is two padlocks on two different doors.

Likely follow-ups
"Would making the counter volatile have fixed the negative values?"

No. Volatile fixes visibility, so each thread would see the latest write, but record() still performs read-then-write and reset() still writes in between; the lost update is a race between two operations, not a stale read.

The counter can still go negative because a record() that read 5 before the reset writes 4 after it.

The fix needs atomicity across the read and write, which means one lock for both methods, or replacing the counter with an AtomicInteger whose decrementAndGet and set are individually atomic.

Even with an atomic, "never negative" needs a compare-and-swap loop that refuses to decrement below zero — updateAndGet(v -> Math.max(0, v - 1)) — because a plain decrement after a reset would still cross zero.

"How would you find this bug in a large codebase without reading every method?"

With a static analyzer that understands lock consistency. SpotBugs' IS2_INCONSISTENT_SYNC detector reports fields accessed sometimes with a lock and sometimes without, and reports which lock, so a static field guarded by this in one place and by the class in another is flagged.

Error Prone's GuardedBy check goes further if I annotate the field with @GuardedBy("LOCK"): every access outside a region holding that lock becomes a compile error, which is the strongest guarantee available.

At runtime, jcstress or a targeted stress test that calls record() and reset() concurrently and asserts non-negativity reproduces it in seconds. The annotation approach is the one I roll out, because it turns the reviewer's question "which lock guards this?" into something the compiler answers.

"Is this a case for making the counter an AtomicInteger instead of any lock?"

Probably, if the counter is the only shared state. An AtomicInteger makes each operation lock-free and removes the question of which lock entirely, and for a hot counter LongAdder is faster still.

It stops being enough the moment a second variable must stay consistent with the counter — a total and a count that must be updated together, for instance — because two atomics updated separately can be observed mid-update.

Then I go back to one lock, or to an AtomicReference holding an immutable pair that is replaced with a compare-and-swap. The general rule: one variable, one atomic; an invariant across variables, one lock or one immutable snapshot.

This bug was one variable, so the atomic is the right and simpler fix.

Q154. "A synchronized method calls another synchronized method on the same object. Why doesn't that deadlock against itself?"

Reveal answer

Strong answer Because Java's intrinsic locks are reentrant — a thread that already owns a monitor can enter it again. The monitor tracks two things: which thread owns it, and a hold count.

When the owner hits another synchronized region on the same object, the JVM sees the owner asking again, increments the count from one to two, and lets it through; each exit decrements the count, and the lock is only truly released when the count reaches zero.

Without reentrancy, ordinary object-oriented code would be unwritable: any public synchronized method calling a synchronized helper, or a subclass method calling super's synchronized version, would freeze forever waiting for a lock it itself holds.

The design cost is small — one extra counter — and the payoff is that locking composes with normal method calls.

The thing reentrancy does not give you is protection across different objects: reentering your own lock is fine, but taking a second object's lock while holding the first is where deadlocks live.

Land it The monitor remembers its owner and counts the entries — so a thread can nest synchronized calls on one object freely, and the danger only starts when a second lock enters the picture.

Likely follow-ups
"Give me a case where reentrancy itself causes a bug."

The classic is a callback invoked while holding the lock.

A synchronized method iterates over its listeners and calls each one; a listener, running on the same thread, calls back into another synchronized method of the same object, which reentrancy allows — and that method mutates the collection being iterated, throwing ConcurrentModificationException, or observes the object in a half-updated state that the outer method had not finished establishing.

Without reentrancy this would deadlock loudly; with it, the invariant violation is silent. The related bug is a subclass overriding a synchronized method and calling super after taking an additional lock, creating an ordering that another path takes in reverse.

The rule is to never call foreign code — listeners, callbacks, virtual methods — while holding a lock; copy what you need, release, then call.

"How does ReentrantLock implement the same thing, and what does getHoldCount tell you?"

ReentrantLock keeps an owner thread reference and an integer state in its AbstractQueuedSynchronizer: a lock attempt by the owner increments state, an unlock decrements it, and the lock is free when state reaches zero.

getHoldCount() returns that count for the current thread, and it is useful mostly as an assertion in tests or a debug log — a hold count greater than one at a point where the code expects to be the outermost acquirer means an unexpected reentrant path.

isHeldByCurrentThread() is the boolean version and is the check I use in a guard clause like "this method must be called with the lock held". Note that unlocking more times than locking throws IllegalMonitorStateException, and unlocking from a thread that is not the owner does too.

"Does reentrancy work across a wait() call? What is the hold count after wait returns?"

Yes, and it is preserved.

When a thread that holds a monitor with a hold count of three calls wait(), the JVM saves that count, releases the monitor completely — a partial release would leave the lock held and the notifier unable to acquire it — parks the thread, and on wakeup reacquires the monitor and restores the count to three before wait() returns.

So from the code's point of view, the nesting is intact. The same holds for Condition.await() on a ReentrantLock: it saves the state, fully releases, and restores it.

The subtle consequence is that if the outer frames assumed nothing changed while they held the lock, they are wrong: the whole world could have changed during the wait, which is why code after wait() re-checks everything.

Q155. "People say synchronized gives you mutual exclusion. What's the second guarantee everyone forgets?"

Reveal answer

The real test Whether you know synchronized is also a memory-visibility tool, not just a turnstile.

Strong answer Visibility. synchronized makes two promises, and the second is just as load-bearing as the first. The first is mutual exclusion: only one thread inside at a time.

The second is a memory guarantee: releasing a monitor happens-before the next acquisition of that same monitor — meaning every write the releasing thread made, inside or before the block, is guaranteed visible to the thread that locks it next.

Without this rule, thread B could take the lock after thread A and still read A's writes from a stale CPU cache, and mutual exclusion alone would not save you.

The lock boundaries also act as fences against reordering: the compiler and CPU cannot move your reads and writes out of the locked region.

This is why "I'll synchronize the writes but skip the lock on reads for speed" is not an optimization but a correctness bug — the reader gave up the very edge that made the writes visible.

Land it Synchronized is exclusion plus visibility in one keyword — and the visibility half only works when both the writer and the reader go through the same lock.

Likely follow-ups
"Does synchronized flush the CPU cache? Is that how visibility works?"

No, and the cache-flush model is wrong in a way that leads to bad decisions. Modern CPUs keep caches coherent in hardware; a write in one core's cache becomes visible to other cores through the coherence protocol without any flush.

What a lock boundary really does is constrain reordering — by the JIT compiler, which otherwise hoists loads out of loops and keeps values in registers, and by the CPU's store buffer, which delays writes becoming globally visible.

On x86 the unlock compiles to a plain store with compiler-level ordering; on ARM it compiles to a store-release instruction, which is a fence.

So the accurate statement is that acquire and release are ordering points that force the compiler and the CPU to make earlier writes globally visible before later ones, and that is a few nanoseconds, not a cache flush.

"Can you get the visibility guarantee without the mutual exclusion?"

Yes; that is what volatile is.

A volatile write has the same release semantics as an unlock and a volatile read the same acquire semantics as a lock, so a writer that stores several plain fields and then a volatile flag, and a reader that reads the flag and then the fields, get full visibility of the fields — without any thread ever blocking.

VarHandle exposes the finer-grained versions: setRelease and getAcquire give exactly the ordering without the full sequential-consistency cost of volatile, and setOpaque gives only visibility without ordering. The thing volatile cannot do is exclusion: two writers still race.

So the split is that locks give ordering plus exclusion, volatile gives ordering alone, and atomics give ordering plus single-variable atomicity.

"Two threads use two different locks, A and B. Does releasing A give visibility to a thread acquiring B?"

No. The monitor rule is specifically about the same monitor: unlock of M happens-before a later lock of M. Unlock of A and lock of B are unrelated, so no edge exists and the reader may see stale values.

In practice on x86 the reader will often see the writes anyway, because the hardware is strongly ordered and the write reached memory, but that is luck, not a guarantee, and the JIT is still free to keep the reader's value in a register.

This is the exact mistake in "I lock writes with the object's lock and reads with a separate read lock object" designs. A readers-writer lock works because both sides are part of one lock whose release and acquire are paired internally; two unrelated locks are not.

"How would you demonstrate the visibility problem to a skeptic?"

With a small program and the right hardware.

A boolean field, a thread that spins while (!stop) {}, and a main thread that sleeps a second and sets stop = true: on any HotSpot JVM with C2 enabled, the spinning thread never exits, because C2 hoists the read of the non-volatile field out of the loop.

Add volatile and it exits instantly. That is a deterministic demonstration of the compiler half.

For the hardware half, jcstress — the JDK's concurrency stress harness — has test cases for store reordering that show unexpected outcomes on ARM within seconds and essentially never on x86, which is a useful lesson in itself: the bug is real, it depends on the machine, and a test that passes on a laptop proves nothing about the server fleet.

Q156. "A field is only ever written inside a synchronized block. Is it safe to read it without the lock, since reads don't modify anything?"

Reveal answer

Strong answer No — that unsynchronized read is a data race: two threads touching the same variable, at least one writing, with no ordering between them.

The visibility guarantee of a monitor is a pairing: the writer's unlock creates a happens-before edge only with a later lock of the same monitor.

A bare read participates in no such edge, so the Java Memory Model — the specification of what one thread is guaranteed to see of another's writes — makes essentially no promise about what it returns.

The reader may see the old value indefinitely, because the JIT (just-in-time) compiler is free to hoist the read out of a loop and never look at memory again; it may see updates out of order relative to other fields; on a long or double it may even see half of one write and half of another.

Reads are cheap under a lock precisely because uncontended locking is a single atomic instruction — so the honest options are: lock the reads too, or make the field volatile if a single-variable guarantee is enough.

Land it Happens-before is a handshake — if the writer locks and the reader doesn't, no handshake happened, and the read is a race no matter how innocent it looks.

Likely follow-ups
"Can a long or double really tear on a 64-bit JVM?"

The specification permits it, and the practical answer is that HotSpot on 64-bit platforms does not tear aligned long and double fields, because it uses a single 64-bit store.

The permission exists for 32-bit JVMs, where a 64-bit value needs two stores, and it remains in the specification so those implementations are conforming.

I still write the code as if it could tear, because relying on an implementation detail of one JVM on one architecture is exactly the kind of assumption that breaks on a new platform, and because volatile on the field is the documented way to guarantee atomic 64-bit access.

As of Aug 2026 there is a JEP in progress to require atomicity for all primitives, but until it lands, volatile is the guarantee.

"Is a read of a reference field at least guaranteed to see a valid reference, or can it be garbage?"

It is always a valid reference — either the old value or a new value that was written by some thread — and never a torn or invented pointer.

References are atomic in the memory model, and the JVM guarantees memory safety even for racy programs, so a racy read cannot crash the JVM or point into the middle of an object.

What it can do is see a reference to an object whose fields are not yet visible: the reference is valid but the object appears partly constructed, which is the unsafe publication problem.

The exception is final fields, which are guaranteed visible once the reference is seen, provided the constructor did not leak this. So racy reference reads are safe in the memory sense and unsafe in the correctness sense.

"The reads outnumber the writes a thousand to one. Isn't locking the reads wasteful?"

Uncontended locking costs about 20 nanoseconds, so a thousand reads cost 20 microseconds — usually invisible.

But if the reads are contended with each other because they all take the same lock, throughput suffers, and then the right tools are ones that make reads free: volatile on the field if it is a single value; an AtomicReference to an immutable snapshot for multi-field state, so readers pay one volatile read; a ReentrantReadWriteLock if the read involves several steps; or StampedLock's optimistic read for tiny critical sections.

Each of these keeps the happens-before edge while removing exclusion between readers. The one option that is never right is dropping the edge entirely, because that trades a measurable cost for an unmeasurable correctness risk.

"What does the JIT concretely do to a racy read in a loop?"

It treats the field like a local variable, because with no synchronization the compiler is allowed to assume no other thread modifies it.

So in while (!done) { work(); }, C2 loads done once before the loop into a register and tests the register on every iteration; the loop becomes if (!done) while (true) { work(); }.

If work() is inlined and has no synchronization, that transformation is legal and permanent. A volatile read cannot be hoisted, so the load happens every iteration.

This is not theoretical: it is the single most reproducible concurrency bug in Java, and it is the reason the "it will see it eventually" argument fails — eventually may be never.

Q157 · Scenario. "Your cache code does: if the map doesn't contain the key, compute the value and put it. The map is a thread-safe implementation. Under load you see the same expensive value computed five times in the same second. Why, and what's the fix?"

Reveal answer

The real test Whether you can spot a check-then-act race even when every individual call is "thread-safe".

Strong answer This is the classic check-then-act race — a decision made on information that can go stale between the check and the act:

  1. Thread-safety of the map means each single call — one containsKey, one put — is internally consistent. It says nothing about the gap between two calls. Under load, five threads all call containsKey in the same few microseconds, all see "absent", and all five launch the expensive computation. Last writer wins; four computations were wasted, and if the computation has side effects, you have five of them.
  2. Diagnosis confirms it: duplicate "cache miss, computing…" log lines with identical keys and near-identical timestamps, and a load spike proportional to concurrency, not to distinct keys.
  3. The fix is to make check-and-insert one atomic step. On a ConcurrentMap, that is exactly what computeIfAbsent(key, loader) exists for — the map performs the check and the insert under its own internal coordination, and concurrent callers for the same key wait for the one computation. The hand-rolled equivalent is synchronizing the whole check-then-act sequence on one lock, at the cost of serializing all keys.
  4. Prevention: whenever I see "if (condition) then modify" on shared state, I ask what happens if the condition changes between the two lines — that one question finds this whole bug family.
check-then-act on a concurrent mapruns offline
// BROKEN — ConcurrentHashMap is thread-safe, this code is not.
// Each operation is atomic; the SEQUENCE is not.
if (!cache.containsKey(key)) {          // thread A and B both see false
    Value v = expensiveCompute(key);    // BOTH compute it
    cache.put(key, v);                  // one silently overwrites the other
}
// Symptoms: duplicated expensive work, and if the value has identity
// (a connection, a lock, a counter) two callers hold DIFFERENT instances
// while believing they share one.

// FIX — one atomic operation.
Value v = cache.computeIfAbsent(key, this::expensiveCompute);
// The mapping function runs AT MOST ONCE per key, under the bin's lock.

// THE SHARP EDGE (Q212): the bin is locked while the function runs, so the
// function must NOT touch the same map, or you get a deadlock or a corrupt map:
cache.computeIfAbsent(k, key -> {
    cache.put(other, v);          // ILLEGAL: recursive update
    return compute(key);
});
// And it must not block for a long time, because every other key hashing to
// the same bin is blocked behind it. For an expensive load, cache a
// CompletableFuture instead so the map lock is released immediately:
CompletableFuture<Value> f = cache.computeIfAbsent(key,
        k -> CompletableFuture.supplyAsync(() -> expensiveCompute(k), pool));
return f.join();

// The other atomic compound operations worth knowing:
map.putIfAbsent(k, v);
map.merge(k, 1, Integer::sum);        // the idiomatic concurrent counter
map.compute(k, (key, old) -> old == null ? 1 : old + 1);

The CompletableFuture pattern is the production answer. It keeps the map lock held only long enough to insert a placeholder, so a slow load no longer blocks every other key that happens to hash to the same bin.

Land it Thread-safe calls do not compose into thread-safe sequences — atomicity has to cover the entire decision, not each half of it.

Likely follow-ups
"What are the rules for the function you pass to computeIfAbsent, and what happens if you break them?"

The function must be short, must not modify the same map, and should not block on anything that could wait for another computeIfAbsent on this map.

ConcurrentHashMap runs the function while holding the lock on the key's bin, so a slow function blocks every other key that hashes to the same bin, and a function that recursively calls computeIfAbsent on the map either throws IllegalStateException: Recursive update in JDK 9 and later or deadlocks in JDK 8.

A function that loads from a database with a 500ms latency stalls unrelated keys for 500ms.

For expensive loads, the right pattern is to store a CompletableFuture in the map — the compute creates the future instantly, and the caller waits on it outside the lock — which is what Caffeine's AsyncLoadingCache does.

"How would you confirm the duplicate computation in production before changing code?"

From the logs and a metric. If the loader logs a miss with the key, a count of log lines per key per second shows the duplicates, and a query like "keys with more than one miss in the same second" quantifies the waste.

Without logs, I add a counter for loader invocations and a gauge of distinct keys, and compare: invocations well above distinct keys is the signature. For the downstream cost, the backing service's request rate spikes in proportion to concurrency on hot keys.

A JFR recording during a load test is the strongest evidence: the sampled stacks show many threads simultaneously inside the loader for the same key. I do the confirmation because the fix changes the locking behavior of the map, and I want the before-and-after numbers.

"What if the cache is not a ConcurrentMap but a remote store like Redis?"

Then the race is distributed, and the same principle applies with different tools.

The check-then-act becomes a single atomic command where possible: SET key value NX sets only if absent, and returns whether it won, so the one client that wins does the computation and the others wait or fall back.

For expensive computations I use a short-lived lock key — SET lock:key token NX PX 5000 — so one instance computes while others either wait briefly and re-read or serve stale data.

This is the cache stampede problem, and libraries implement it as "single flight" per key. Locally, a per-instance computeIfAbsent still helps, because it collapses the duplicates within one JVM before they reach the network.

"Give me a check-then-act race outside of caching."

The file that exists check: if (!Files.exists(path)) Files.createFile(path) races with another process, and the fix is to just call createFile and handle FileAlreadyExistsException.

The unique-username check: a query that finds no user with that name, followed by an insert, lets two registrations through, and the fix is a unique constraint with the insert catching the violation.

The lazy initialization check: if (instance == null) instance = new X() is the double-checked locking problem. The balance check: read balance, compare with amount, then subtract — the fix is a conditional update in the database.

The pattern is always the same: the decision must be made by the same atomic operation that acts on it, and usually the storage layer already offers that operation.

Q158. "Give me other examples where a thread-safe collection still isn't enough."

Reveal answer

Strong answer Any compound action — an operation made of two or more calls whose combination must be atomic — races even on a perfectly thread-safe collection.

The recurring shapes: read-then-write, like get, modify the value, put it back — another thread's update between the two calls is silently lost; size-then-access, like checking isEmpty() before taking an element — the collection can empty out in between; and iterate-then-modify, where a "safe" iterator gives you either an exception or a weakly consistent view that may not reflect concurrent changes, so decisions made from the iteration are decisions made on old data.

In each case the collection kept its own internal invariants intact — that is all it ever promised — while your invariant, which spans multiple calls, was violated in the gap.

The remedies are always the same three: use an atomic compound operation the collection itself provides, widen the lock to cover the whole sequence, or redesign so the invariant lives inside one call.

Land it A thread-safe collection guarantees its invariants, not yours — the moment your correctness spans two calls, the atomicity has to come from you.

Likely follow-ups
"What atomic compound operations do ConcurrentHashMap and the queues provide, so you don't need your own lock?"

On ConcurrentHashMap: putIfAbsent, computeIfAbsent, computeIfPresent, compute, merge, replace(key, oldValue, newValue), and remove(key, value) — each does a read-decide-write as one step under the bin lock. merge(key, 1, Integer::sum) is the atomic counter-in-a-map idiom.

On the queues: BlockingQueue.poll(timeout) replaces the isEmpty-then-take pair; drainTo moves a batch atomically; offer returns false rather than needing a size check. On ConcurrentLinkedDeque, pollFirst returns null rather than throwing, which is the safe form. On atomics, compareAndSet, getAndUpdate, and accumulateAndGet.

The habit I try to build is to look for the method whose name contains the whole operation before writing an if statement around two calls.

"How does iteration over a ConcurrentHashMap behave, and when is that a problem?"

Its iterators are weakly consistent: they never throw ConcurrentModificationException, they reflect the map's state at some point at or after the iterator was created, and they may or may not show entries added or removed during the iteration.

That is fine for reporting, for metrics, for a best-effort sweep.

It is a problem when the code makes a decision from the iteration that must hold at the end — "no entries are expired, so skip the cleanup" — or when it counts entries and expects the count to equal size().

size() itself is an estimate under concurrent updates. If I need a consistent view, I take a snapshot under a lock the writers also use, or I design the data as an immutable map replaced atomically with an AtomicReference, so readers iterate a frozen version.

"Collections.synchronizedMap — is that safer than ConcurrentHashMap for compound actions?"

It is the same problem with a documented workaround. Every method of a synchronized wrapper locks the wrapper object, so single calls are safe and compound actions still race.

The workaround is that the wrapper's lock is the wrapper itself and the Javadoc tells you so: synchronized (map) { if (!map.containsKey(k)) map.put(k, v); } is correct, because the client takes the same lock the wrapper uses.

The same rule covers iteration: iterate inside synchronized (map) or get ConcurrentModificationException. ConcurrentHashMap deliberately does not expose its locks, so the client cannot extend them and must use the compound methods instead. Performance-wise, the wrapper serializes everything on one lock; the concurrent map locks per bin.

I use the wrapper only for a rarely-touched map where simplicity wins.

Drill · wait/notify, volatile & the Java Memory Model

This group tests whether you can reason about signaling and visibility from first principles — the rules that decide what one thread is allowed to see of another's work.

Q159. "Why must wait() and notify() be called while holding the object's monitor? What happens if you don't?"

Reveal answer

Strong answer If you call them without owning the monitor, the JVM throws IllegalMonitorStateException immediately — but the interesting part is why the rule exists.

wait()'s contract is to do two things as one indivisible step: release the lock and move the thread into the wait set. You cannot release a lock you do not hold, so ownership is a precondition by definition.

The deeper reason is the condition itself: you wait because some shared state — "the queue is empty" — is not what you need, and that state is guarded by the same lock.

Checking the condition and going to sleep must happen atomically under the lock; otherwise another thread could change the state and call notify() in the gap between your check and your wait(), the notification would find an empty wait set and vanish, and you would sleep forever waiting for a signal that already happened.

The lock requirement is what welds "check" and "sleep" into one step.

Land it The monitor requirement isn't ceremony — it is the only thing that makes "check the condition, then sleep" atomic, which is the only thing that makes the signal impossible to miss.

Likely follow-ups
"Does the same requirement apply to Condition.await and signal on a ReentrantLock?"

Yes, identically. await() must be called with the associated lock held, and it atomically releases the lock and parks; signal() and signalAll() must be called with the lock held too, or they throw IllegalMonitorStateException.

The reason is the same: the condition is a predicate over state guarded by the lock, and the check-then-park must be atomic with respect to the state change that would satisfy it.

One difference in the details: Condition is documented to wake spuriously exactly like wait(), and it adds awaitNanos which returns the remaining time so a loop can maintain a deadline correctly, and awaitUninterruptibly for the rare case where interruption must be deferred.

The discipline — lock, while-loop, await, signal under lock — transfers unchanged.

"Show me the exact interleaving that loses the signal if the lock were not required."

Consumer: reads queue.isEmpty(), sees true, decides to wait. Before it calls wait(), the scheduler switches. Producer: adds an item, calls notify(); the wait set is empty, so nothing happens and the signal is gone. Scheduler switches back.

Consumer: calls wait() and parks, waiting for a notification about an item that is already in the queue. If the producer never produces again, the consumer waits forever with a non-empty queue.

With the lock held across the check and the wait(), the producer cannot add and notify until the consumer has actually entered the wait set, because wait() releases the lock only as the thread is enqueued.

That atomic release-and-park is the entire mechanism, and the lock requirement is how it is enforced.

"Why is calling notify() outside the lock still a bug even though the JVM would throw?"

The exception makes the mistake visible, which is the good case.

The subtle version is calling notify() inside a synchronized block on the wrong object — the JVM cannot tell that the object is wrong, so it accepts the call, and the waiters on the right object never wake.

Or notifying on the right object but changing the state outside the lock: the state change and the notify are then not atomic, and a waiter can observe the old state, decide to wait, and miss the notify in the gap.

The rule I state is that the state change, the notify, and the waiter's check must all happen under the same lock, and the object whose monitor is held must be the one whose wait() and notify() are called — the exception only catches the first of these three errors.

Q160. "What's the difference between wait() and sleep() with respect to locks?"

Reveal answer

Strong answer wait() releases the monitor it is called on; sleep() releases nothing. The difference follows from what each is for.

wait() means "the state I need is not here yet, and another thread must change it" — and that other thread will need the very lock I am holding to make the change, so releasing it is not a courtesy, it is the mechanism.

The waiting thread gives the key back, parks in the wait set, and on wakeup must reacquire the lock before continuing.

sleep() is just a timer: "pause this thread for some milliseconds," with no relationship to any lock or any other thread — so it keeps every lock it holds for the whole nap.

That makes sleep() inside a synchronized block a small denial of service: every thread needing that lock queues up as BLOCKED for the duration. Also worth saying: wait() only releases the one monitor it was called on — any other locks the thread holds stay held.

Land it wait releases the lock because someone else needs it to change the condition; sleep holds everything because nobody was ever supposed to be involved — sleeping while holding a lock stalls the whole building.

Likely follow-ups
"What about Thread.yield() and Thread.onSpinWait() — where do they fit?"

yield() is a hint to the scheduler that this thread is willing to give up its time slice; it releases no locks, has no memory-model effect, and on Linux may do nothing at all. It has no place in correct coordination logic.

onSpinWait(), added in JDK 9, is a hint that the thread is in a busy-wait loop, and on x86 it emits the PAUSE instruction, which reduces power and lets a hyperthread sibling run; it is for very short spins on a volatile flag, on the order of nanoseconds to microseconds, before falling back to parking.

Neither is a substitute for wait() or LockSupport.park(): spinning burns CPU, and in a container with a CPU quota a spinning thread starves the threads doing useful work.

"You found sleep() inside a synchronized block in a retry loop. What is the fix?"

Move the sleep outside the lock, or replace the pattern. The code is usually "lock, try operation, if it failed sleep and retry" — the lock is held during the sleep, so every other thread that needs it waits out the retry delay for nothing.

The restructure is a loop whose body takes the lock only for the attempt, releases it, and sleeps unlocked before the next iteration.

If the retry is waiting for a condition that another thread will establish, the honest fix is wait() with a timeout or a Condition.await, which releases the lock and wakes on the signal rather than on a timer.

If the wait is for an external system, the lock should not be held at all, and a Semaphore or a rate limiter bounds concurrency without serializing the sleep.

"Does sleep() have any memory-model effect? Can I use it to 'let the other thread's write become visible'?"

None. Thread.sleep creates no happens-before edge, so a read after a sleep is exactly as racy as a read before it.

The folk belief comes from the fact that sleeping usually gives the operating system a chance to schedule the other thread and that x86 hardware makes stores visible quickly, so the read usually sees the new value — but the JIT can still have hoisted the read into a register before the sleep, and the value never changes.

The memory model is explicit that timing is not synchronization.

If code needs to see another thread's write, it needs a volatile, a lock, an atomic, or a join; a sleep that "fixes" a visibility bug in testing is a bug that will reappear at a different rate in production.

Q161. "Why must wait() always sit inside a while loop instead of an if?"

Reveal answer

The real test Whether you know both reasons — most candidates only know one.

Strong answer Because waking up does not mean the condition is true — for two separate reasons, and either alone mandates the loop:

  • Spurious wakeups. The Java specification explicitly permits a thread to wake from wait() with no notify() at all — an artifact of how thread parking works at the operating system level. Rare, but legal, so correct code must tolerate it.
  • The condition can be re-consumed before you run. This is the bigger one. notify() does not transfer control; it moves the waiter from the wait set back to the entry set, where it must compete for the lock. Between the notification and the waiter actually reacquiring the monitor, any other thread can slip in and consume the condition — take the item that was just added, say. An if-based waiter then proceeds on a false premise and, in a queue, pops from empty.

The while loop makes the code self-correcting: every wakeup, from any cause, re-checks the condition under the lock and re-waits if it is not actually satisfied.

why wait() must be in a while loopruns offline
// BROKEN — `if` instead of `while`.
synchronized (lock) {
    if (queue.isEmpty()) {
        lock.wait();              // resumes -> assumes the queue is non-empty
    }
    return queue.remove();        // NoSuchElementException
}

// THREE INDEPENDENT REASONS THE CONDITION MAY BE FALSE AFTER wait() RETURNS:
//
// 1. SPURIOUS WAKEUP. The specification explicitly permits wait() to return
//    without any notify at all. Rare, real, and permitted on purpose so the
//    JVM can be implemented efficiently on POSIX condition variables.
//
// 2. A DIFFERENT WAITER WON. notifyAll() wakes everyone; they then contend
//    for the monitor one at a time. By the time the third one acquires it,
//    the first two have already consumed the item.
//
// 3. NOTIFY FOR A DIFFERENT CONDITION. One monitor is often used for several
//    predicates ("not empty" and "not full"). A consumer can be woken by a
//    notify meant for a producer.

// CORRECT — re-check the predicate every time.
synchronized (lock) {
    while (queue.isEmpty()) {     // while, not if
        lock.wait();
    }
    return queue.remove();
}

// The rule generalises: wait() does not mean "the condition is now true".
// It means "something changed; look again." The same applies to
// Condition.await(), which is why it is also always used in a loop.

Reason 2 is the common one in practice. Spurious wakeups get the attention, but the everyday cause is simply that several threads were notified and an earlier one consumed the item — which is guaranteed to happen under load rather than being a rare hardware quirk.

Land it A wakeup is a hint, never a promise — the while loop converts "someone thinks something changed" into "I verified it changed, holding the lock."

Likely follow-ups
"Where do spurious wakeups actually come from?"

From the operating-system primitives underneath.

On Linux, wait() parks the thread with a futex or a pthread condition variable, and POSIX explicitly permits condition-variable waits to return without a signal — for example when a signal handler interrupts the wait, or as a consequence of how the kernel implements wake-ups efficiently, where waking one thread too many is cheaper than exact accounting.

The Java specification inherited that permission rather than trying to hide it at a cost. In practice on HotSpot they are rare, but they are real, and a program that would corrupt state on one is a program with a latent bug.

Since the same while loop also handles the far more common "condition was consumed by someone else" case, tolerating spurious wakeups costs nothing extra.

"What about a timed wait — how does the loop handle the deadline correctly?"

The loop must recompute the remaining time on every iteration, because a wakeup that is spurious or that finds the condition still false must not restart the full timeout.

The shape is: compute the deadline once as System.nanoTime() + timeoutNanos, then while (!condition) { long remaining = deadline - System.nanoTime(); if (remaining <= 0) return false; lock.wait(remaining / 1_000_000, (int)(remaining % 1_000_000)); }.

On return, the condition is either satisfied or the deadline passed, and the caller can tell which.

With Condition.awaitNanos the remaining time is returned directly, which is why it is the nicer API. The common bug is wait(timeout) inside a loop with a fixed timeout, which can wait many times the intended duration.

"Is there any situation where an if is acceptable?"

Only where the code does not depend on the condition after waking — for example a thread that waits merely to be poked and then re-reads all state from scratch anyway, which is effectively a while loop with the check moved after it.

Some argue that with a single waiter, a single notifier, and notify() called only when the condition is true, an if is safe; but spurious wakeups alone break that argument, and the code is fragile to a second waiter being added later.

Static analyzers flag wait() outside a loop as a bug pattern — SpotBugs' WA_NOT_IN_LOOP — and I keep that rule on.

The cost of the while loop is one extra comparison per wakeup; the cost of the if is an incident that happens once a month and is impossible to reproduce.

Q162 · Scenario. "Your bounded buffer uses one monitor for both producers and consumers, and signals with notify(). Under heavy load the whole system hangs — the dump shows every thread WAITING on the buffer, none BLOCKED, and the buffer isn't empty. Explain it."

Reveal answer

The real test Whether you can reconstruct the missed-signal failure that makes notify() dangerous with two waiter classes.

Strong answer This is the textbook missed signal: notify() woke the wrong kind of waiter, and the signal died there.

  1. Read the dump first: all threads WAITING on one object means everyone is parked in the wait set voluntarily. Nobody is BLOCKED, so this is not lock contention and not deadlock — it is a signaling failure.
  2. Reconstruct it: one monitor's wait set holds two classes of waiter — producers waiting for space and consumers waiting for items. notify() wakes one arbitrary thread from that mixed set. Suppose the buffer is full: a consumer takes an item and calls notify() to announce free space, but the JVM happens to pick another consumer. That consumer rechecks its loop condition, finds the buffer state unhelpful for it, and correctly re-waits. The signal has now been spent on a thread that could not use it, and no producer will ever hear it. A few repetitions of this under load and every thread is parked.
  3. The immediate fix: use notifyAll(). Everyone wakes, everyone rechecks under the lock, the threads that can proceed do, the rest re-wait. It costs a thundering herd of wakeups, but it is correct.
  4. The better design: give each waiter class its own wait set — which intrinsic monitors cannot do, since each object has exactly one. That is precisely the problem Condition objects on an explicit lock solve, with a "not full" condition for producers and a "not empty" condition for consumers.

Land it notify() is only safe when every waiter is interchangeable — the moment two kinds of threads share one wait set, it's notifyAll() or a redesign.

Likely follow-ups
"You switched to notifyAll() and the hang is gone, but CPU rose noticeably. What next?"

That is the thundering herd: every notifyAll() wakes every waiter, they all contend for the lock, all but one re-check and go back to sleep, and each of those cycles is two context switches.

With hundreds of producers and consumers, that is a lot of wasted wakeups per item. The next step is the redesign the answer mentioned: a ReentrantLock with two Conditions, notFull and notEmpty, so a consumer taking an item calls notFull.signal() and wakes exactly one producer.

Or the simplest fix of all: replace the hand-rolled buffer with ArrayBlockingQueue, which is implemented exactly that way and has been tested for twenty years. I would confirm the CPU improvement by comparing context-switch counts from pidstat -w before and after.

"Prove to me from the dump that this is not a deadlock."

A deadlock has threads in BLOCKED state, each with a "waiting to lock" line naming a monitor that another thread's "locked" line shows it holding, and the JVM prints "Found one Java-level deadlock" with the cycle at the bottom of the dump.

In this dump, every thread is WAITING (on object monitor) with a frame in Object.wait, nobody holds the buffer's monitor — because wait() released it — and there is no deadlock section.

That means the lock is free and any thread could take it; nobody does because they are all parked waiting for a signal that will not come.

The distinction matters because a deadlock is fixed by lock ordering and a lost signal is fixed by the signaling discipline; treating one as the other wastes the incident.

"Could a single-waiter-class design safely use notify()?"

Yes, with three conditions all holding: every waiter waits for the same predicate, every waiter that wakes can make progress or re-waits correctly in its loop, and every state change that could satisfy the predicate is followed by at least one notify.

A pool of identical worker threads waiting for "queue not empty", where each item is consumed by exactly one worker, meets those conditions, and notify() is then an optimization that wakes one worker per item.

The moment someone adds a second predicate on the same monitor — a shutdown flag, a "queue not full" for producers — the conditions fail silently.

Because that change tends to happen in a different pull request months later, my default is notifyAll() unless the wake-up cost is measured to matter, and a comment explaining why if so.

"How would you write a test that catches the missed-signal bug?"

With a stress test that forces the mixed-waiter situation.

Many producers and many consumers, a small capacity so both sides block often, a fixed total item count, and an assertion with a timeout that all items are consumed within a bound — a hang fails the test by timeout rather than freezing the suite.

Run it in a loop of a few hundred iterations, because the bug needs the "wrong thread woken" sequence, which is probabilistic.

jcstress is the rigorous tool, but a JUnit test with assertTimeoutPreemptively catches this one reliably within seconds when notify() is used, and passes with notifyAll() or with conditions.

I keep this test on the hand-rolled buffer permanently, because it is the class of code where a "small cleanup" reintroduces the bug.

Q163 · Scenario. "A starter thread finishes setup and calls notify(); a worker thread later reaches wait() and hangs forever, even though the notification definitely happened. What went wrong?"

Reveal answer

Strong answer This is a lost wakeup — the notify ran before the wait, and monitors do not remember signals:

  1. The key fact: notify() is stateless. It wakes a thread that is in the wait set right now; if the wait set is empty, it does nothing and the signal simply evaporates. It is not a message queue and not a flag — there is no memory of it ever happening.
  2. So the race is: starter completes, calls notify() into an empty wait set; worker arrives afterward, calls wait(), and parks waiting for a signal that already came and went. Forever.
  3. The fix is to never wait on a signal alone — wait on state, with the signal as a nudge to re-check. Keep a shared flag such as ready, and have the worker do while (!ready) { lock.wait(); } inside synchronized (lock), with the starter setting ready = true and calling notifyAll() under the same lock. Now ordering cannot hurt you: if the starter ran first, the worker sees the flag and never waits at all; if the worker got there first, it is in the wait set when the signal arrives. The lock makes check-and-sleep atomic, so there is no gap for the signal to fall into.

Land it Notifications are ephemeral and state is durable — correct waiting always pairs the two, so the signal is merely "go look at the state again."

Likely follow-ups
"Which java.util.concurrent class is the right replacement for this handshake?"

CountDownLatch with a count of one. The starter calls latch.countDown() when setup is done; the worker calls latch.await(), which returns immediately if the count is already zero and blocks otherwise.

Ordering cannot hurt, because the latch stores the state — it is the durable flag and the signal in one object, with the happens-before edge built in: everything the starter did before countDown() is visible after await() returns.

If the worker also needs a result, a CompletableFuture<Config> completed by the starter does the same with a value attached, and join() on it blocks or returns as appropriate. For a repeated handshake, Phaser or a CyclicBarrier; for one-shot readiness, the latch is the idiom.

"Does the flag need to be volatile if it is only read under the lock?"

No, as long as every read and write happens inside synchronized (lock) — the monitor gives both the exclusion and the visibility, and volatile would be redundant.

It becomes necessary the moment someone reads the flag outside the lock as a fast-path check, like if (ready) return; before entering the synchronized block, because that read has no happens-before edge to the write.

That double-checked pattern is a legitimate optimization only with volatile on the flag. My rule is to pick one discipline per field and write it down: either every access is under the lock, or the field is volatile and the lock only guards the wait.

Mixing them without volatile is the bug that passes every test and fails on the ARM fleet.

"What if the setup can fail? How does the worker learn that?"

The state must be able to express failure, not just readiness.

With the hand-rolled version, that means a second field — an exception or an error flag — set under the same lock before notifyAll(), and the worker's loop becomes while (!ready && error == null) wait(), then it checks which one happened.

A latch cannot carry that; it only counts down, so a worker released by a failed starter would proceed on nothing.

That is the argument for CompletableFuture: completeExceptionally(e) releases the waiters with the exception, join() rethrows it wrapped in CompletionException, and there is no way to be released without knowing the outcome.

It is the smallest primitive that models "wait for a result that might be an error".

Q164 · Scenario. "Write me a minimal correct producer–consumer with wait/notify, and tell me which rule each line is obeying."

Reveal answer

The real test This is the hand-rolled coordination exam: one missing rule and the code hangs or corrupts under load.

Strong answer Here is the minimal correct shape, with every rule visible:

BoundedBuffer.java
class BoundedBuffer {
    private final Deque<String> items = new ArrayDeque<>();
    private final int capacity = 100;
    private final Object lock = new Object();      // rule 1: private lock guards ALL state

    void put(String item) throws InterruptedException {
        synchronized (lock) {                      // rule 2: state only touched under the lock
            while (items.size() == capacity) {     // rule 3: condition re-checked in a while loop
                lock.wait();                       // rule 4: wait on the SAME object we locked
            }
            items.addLast(item);
            lock.notifyAll();                      // rule 5: notifyAll — two waiter classes share
        }                                          //          this wait set
    }

    String take() throws InterruptedException {
        synchronized (lock) {
            while (items.isEmpty()) {
                lock.wait();
            }
            String item = items.removeFirst();
            lock.notifyAll();
            return item;
        }
    }
}

Naming the rules aloud: one private final lock object that outside code cannot reach; every read and write of the buffer happens inside synchronized (lock), which also gives visibility between producer and consumer; the condition lives in a while loop so spurious wakeups and re-consumed conditions are harmless; wait() and notifyAll() are called on the exact object whose monitor we hold, or we would get IllegalMonitorStateException; notifyAll() rather than notify() because producers and consumers share one wait set and a single notify() can wake the wrong class and strand the system; and InterruptedException propagates out so the thread stays cancellable.

Land it In production I would reach for a BlockingQueue, which is this exact pattern implemented and tested once — but being able to write it by hand is how you prove you understand what the queue is doing for you.

Likely follow-ups
"Why is InterruptedException propagated rather than caught? What breaks if you catch it here?"

Because the caller of put or take is the one who knows what cancellation means for it, and a blocking method that swallows the interrupt makes its callers uncancellable.

Consider an executor shutting down: it interrupts the worker, the worker is in take(), and if take() caught the exception and looped back to wait(), the worker would never exit and shutdown would hang until force-killed.

By declaring throws InterruptedException, the buffer says "I block, and I can be asked to stop blocking", which is exactly what BlockingQueue declares too.

If for some reason the method could not throw, the fallback is to restore the flag with Thread.currentThread().interrupt() and return or throw an unchecked exception, but never to loop back into the wait.

"Why a Deque and a separate lock instead of synchronizing on the deque itself?"

Two reasons. The deque is an implementation detail I might replace with an array or a ring buffer, and the lock should not change identity when I do; a dedicated lock object decouples the coordination from the storage.

And synchronizing on the deque would make the lock reachable by anyone I hand the deque to — if a debugging method exposed it or a subclass grabbed it, they could lock it and interfere. The private final Object can be reached by nobody.

There is also a subtle point about wait(): the wait set belongs to the object waited on, so waiting on the deque would tie the wait set to the storage object, and if the storage were ever swapped out mid-operation the waiters would be stranded on an orphaned object.

"Capacity is 100 — what changes if it must be unbounded?"

The producer never waits, so the while (items.size() == capacity) loop disappears, put no longer throws InterruptedException, and only consumers wait — which means there is now one waiter class, and notify() becomes safe as an optimization.

But I would push back on the requirement: an unbounded buffer converts a slow consumer into an OutOfMemoryError with no warning, which is the same failure as the unbounded executor queue.

The senior version of "unbounded" is a large bound with a metric on depth and an alert, or a policy for what happens at the bound — block, drop oldest, reject.

If the requirement stands, LinkedBlockingQueue with no capacity is the library form, and the memory risk is documented next to it.

"What would you change to support multiple consumers taking in batches?"

Add a drainTo(Collection, max) that, under the lock, waits while the buffer is empty, then moves up to max items in one step and calls notifyAll() once — a single lock acquisition per batch instead of one per item, which is the main throughput lever for a hand-rolled queue.

The while-loop condition stays "empty", not "fewer than max", so a consumer takes whatever is available rather than waiting for a full batch and adding latency. With notifyAll() after a drain of fifty items, up to fifty waiting producers can proceed, which is the right semantics.

This is exactly BlockingQueue.drainTo, which is how a batching consumer over ArrayBlockingQueue is written in production code.

Q165. "Why did java.util.concurrent essentially retire hand-rolled wait/notify?"

Reveal answer

Strong answer Because hand-rolled wait/notify has a brutal property: it looks correct while missing any one of five rules, and the failure only appears under production load.

Forget the while loop, use notify() with mixed waiters, signal outside the lock, wait on the wrong object, swallow the interrupt — each is one line, each compiles, each passes light testing.

java.util.concurrent — Java's standard concurrency library — packages the correct patterns as tested components: a blocking queue is producer–consumer with all five rules baked in, a latch is the one-shot "wait until ready" handshake, and so on.

There is also a hard capability gap: an intrinsic monitor has exactly one wait set, so distinct waiter classes must share it and be woken with notifyAll() storms, while an explicit lock offers multiple Condition objects — one wait set per kind of waiter — plus timeouts and interruptible acquisition that synchronized simply cannot express.

Land it The library did not replace the monitor — it froze the correct usage patterns into components, so each team stopped re-deriving them and re-discovering the same five bugs.

Likely follow-ups
"Map me from a wait/notify pattern to the library class that replaces it."

Producer-consumer with a bounded buffer becomes ArrayBlockingQueue or LinkedBlockingQueue. "Wait until N things have happened" becomes CountDownLatch. "All parties wait for each other at a point, repeatedly" becomes CyclicBarrier or Phaser. "At most K threads in this section" becomes Semaphore.

"Wait for a result computed elsewhere" becomes CompletableFuture or FutureTask. "Hand off an item directly to a waiting thread" becomes SynchronousQueue or Exchanger. "Wait for a condition on shared state" — the general case — becomes ReentrantLock with a Condition.

Only that last one still needs the while-loop discipline; the rest hide it entirely. If I cannot name the library class for a piece of hand-rolled waiting, that is a review comment.

"Is there anything java.util.concurrent lost compared to the monitor?"

Two small things. Automatic release: a synchronized block cannot leak its lock, while ReentrantLock can be left locked by a missing finally, so the library traded one bug class for another.

And integration with the JVM's diagnostics: synchronized monitors appear in thread dumps with "locked" and "waiting to lock" lines and in the JVM's built-in deadlock detector, whereas ReentrantLock owners appear only with jstack -l under "Locked ownable synchronizers", and the deadlock detector handles them but some tools do not.

There is also a performance point: uncontended synchronized is slightly cheaper than ReentrantLock, and the JIT can elide or coarsen monitors but not explicit locks. So the monitor stays my default and the library is for when I need its features.

"How is Condition implemented underneath — is it just a wrapper around wait/notify?"

No, it is built on LockSupport.park and unpark and a queue, not on monitors at all. AbstractQueuedSynchronizer maintains a linked queue of waiting threads for the lock and a separate queue per Condition.

await() adds the thread to the condition's queue, fully releases the lock, and parks; signal() moves the first node from the condition queue to the lock queue, so it will be unparked when the lock becomes available.

park is the primitive that makes this work: it is a permit-based block — an unpark that arrives before the park is not lost, it makes the next park return immediately — which is what monitors lack and what makes the library's coordination easier to get right.

Q166. "What does volatile guarantee — and just as important, what does it not guarantee?"

Reveal answer

Strong answer volatile makes two promises about a single variable. Visibility: a write to a volatile field is guaranteed to be seen by every subsequent read of that field from any thread — no thread can go on reading a stale cached copy.

Ordering: the volatile acts as a fence — writes the thread made before a volatile write cannot be reordered to after it, and reads after a volatile read cannot be moved before it; formally, a volatile write happens-before every later read of that field, which drags all the writer's earlier work into view too.

What it does not give you is atomicity of compound operations: count++ on a volatile is still three separate steps — read the value, add one, write it back — and two threads can interleave those steps and lose an update.

Volatile also cannot make an invariant across two variables hold; it is strictly a one-variable, one-operation guarantee.

Land it Volatile answers "will other threads see this write, in order?" with yes — and answers "can I safely read-modify-write it?" with no; that split decides every use of the keyword.

Likely follow-ups
"What does volatile compile to on x86 versus ARM?"

On x86, which has a strong memory model, a volatile read is a plain load — the hardware already guarantees that loads are not reordered with other loads — and the compiler simply refrains from hoisting or caching it.

A volatile write is a store followed by a full fence, typically implemented as a lock addl $0, (%rsp) or an mfence, which costs tens of cycles because it drains the store buffer.

On ARM, which is weakly ordered, a volatile read compiles to a load-acquire instruction, ldar, and a volatile write to a store-release, stlr, plus a fence for the sequential-consistency requirement.

So volatile reads are nearly free on x86 and cheap on ARM; volatile writes are the expensive side on both. That asymmetry is why a read-mostly volatile field is fine and a write-heavy one is not.

"Does volatile on an array field make the elements volatile?"

No. The volatile applies to the reference — reads and writes of the field that points to the array — not to the array's elements, so volatileArray[i] = x is a plain write with no visibility guarantee to other threads.

The same holds for a volatile reference to any mutable object: the fields inside it are plain.

The fixes are AtomicIntegerArray and AtomicLongArray, which give volatile semantics per element; VarHandle with MethodHandles.arrayElementVarHandle, which lets me do volatile or release-acquire access to elements of an ordinary array; or replacing the array as a whole with a fresh one on every change, so the volatile reference swap publishes the new contents. This is one of the most common misunderstandings in code review.

"When would you use a VarHandle mode weaker than volatile, and why?"

When I need the ordering but not the global sequential consistency, in code hot enough for the difference to matter. setRelease and getAcquire give exactly the publish-and-observe guarantee: writes before the release are visible after the acquire that sees it.

What they drop is the guarantee that all volatile operations across all threads appear in one global order, which matters only for algorithms like Dekker's that reason about the relative order of writes to two different variables.

On x86 the difference is the fence on the write, so a release store is a plain store; on ARM it is the difference between stlr with a fence and without. Use cases are lock-free queues and single-producer counters.

For ordinary application code, volatile is the readable default and the difference is unmeasurable.

"Can volatile make a 64-bit read atomic, and does it cost anything for that?"

Yes, that is one of its explicit guarantees: reads and writes of volatile long and double fields are atomic, so a reader never sees half of one value and half of another.

On a 64-bit JVM there is no extra cost for that part, because the hardware does aligned 64-bit accesses atomically anyway; the cost of volatile is the ordering, not the atomicity.

On a 32-bit JVM, volatile 64-bit access may use a two-word atomic instruction or a lock, which is measurable. The distinction I keep clear is that this atomicity is per single read or write; volatileLong++ is still three operations and still races. For an atomic read-modify-write, AtomicLong is the tool.

Q167 · Scenario. "You made a hit counter volatile to fix a visibility bug. Under load testing at 50k requests, the counter reads about 41k. Where did the hits go?"

Reveal answer

Strong answer They were lost to interleaved read-modify-write — volatile fixed visibility and left atomicity broken:

HitCounter.java
class HitCounter {
    private volatile long count = 0;

    void hit() {
        count++;   // NOT one operation: (1) read count
                   //                    (2) add one
                   //                    (3) write it back
    }
}
// Thread A reads 41. Thread B reads 41.
// A writes 42. B writes 42. Two hits happened; the counter moved by one.
  1. The mechanics: count++ compiles to a read, an add, and a write. Volatile guarantees each read sees the latest write and each write becomes visible — but it puts no lock around the trio. Two threads read the same value in the same microsecond, both compute the same successor, and one increment is silently absorbed. At 50k concurrent requests, losing roughly one increment in five is exactly what heavy interleaving looks like.
  2. Confirm it cheaply: a stress test hammering hit() from many threads and comparing the counter to the invocation count reproduces the loss in seconds.
  3. The fix: make the read-modify-write a single atomic step — AtomicLong.incrementAndGet(), which uses a hardware compare-and-swap loop; or wrap the increment in synchronized; or, for very write-heavy counters, LongAdder, which spreads the contention across cells and sums on read.
  4. Prevention: any time a new value depends on the old value, volatile alone is disqualified — that is the one-line review rule.

Land it Volatile made every read honest and every write visible — it just never promised that read-plus-write is one step, and a counter is nothing but read-plus-write.

Likely follow-ups
"When is LongAdder better than AtomicLong, and what does it give up?"

AtomicLong.incrementAndGet is a compare-and-swap loop on one memory location, and under heavy contention from many cores, the cache line bounces between cores and the CAS retries pile up — throughput actually drops as more threads increment.

LongAdder keeps a base value plus an array of cells, and each thread hashes to its own cell, so increments from different cores hit different cache lines and scale linearly.

What it gives up is a cheap exact read: sum() adds up all cells without locking, so the result is a snapshot that may miss increments in flight, and there is no compareAndSet on the total.

For a metrics counter that is written constantly and read occasionally, LongAdder; for a value that other logic must read and act on atomically, AtomicLong.

"How would you spot this bug in code review before a load test?"

The signature is a volatile field with a compound operator: ++, --, +=, or any pattern of read the field, compute, write the field back.

I search for volatile declarations and look at every write site; if the new value depends on the old one, it is a race. Static analysis catches it too: SpotBugs reports VO_VOLATILE_INCREMENT for exactly this, and Error Prone has a similar check.

The other tell is a comment like "volatile makes this thread-safe", which is a misunderstanding worth a conversation. My reviewer question is "what happens if two threads execute this line at the same instant?

" — for an assignment the answer is one wins, which is fine; for an increment the answer is one is lost.

"The counter feeds a rate limiter. Does losing a few increments matter there?"

It matters in the direction of failing open: a lost increment means the limiter thinks fewer requests happened than did, so it admits more than the limit.

Under the heaviest load — exactly when the limiter should bite — contention is highest and the most increments are lost, so the limiter is weakest when it matters most. That is the pattern where an "approximately right" counter is wrong.

A rate limiter should use an atomic with a conditional update, compareAndSet or getAndUpdate that refuses to exceed the limit, so the admit decision and the count are one atomic step.

For a distributed limiter the same reasoning moves to Redis with a Lua script or INCR with expiry, which is atomic on the server.

"Is there a correct lock-free way to write count++ by hand?"

Yes, and it is what AtomicLong does internally: a compare-and-swap loop. Read the current value into a local, compute the new value, then attempt compareAndSet(current, next); if it returns false, another thread changed the value in between, so re-read and retry.

Since JDK 8 the JIT compiles getAndAdd directly to the x86 lock xadd instruction, which is a single atomic fetch-and-add with no loop at all, so the library version is faster than a hand-written CAS loop.

The general form, updateAndGet(v -> f(v)), is the way to write any read-modify-write on a single variable without a lock, and the constraint is that f must be pure and cheap, because it may run more than once under contention.

Q168. "So when is volatile by itself the right tool?"

Reveal answer

Strong answer Volatile alone is correct under two conditions: the write is a pure assignment — a new value that does not depend on the old one — and the invariant involves only that single variable.

There are three canonical cases:

  • A status flag, like volatile boolean shutdownRequested, where one thread writes true and workers poll it in their loops. Without volatile, the JIT may hoist the read out of the loop and the worker literally never notices.
  • A single-writer published value, like a metrics gauge that one thread updates and others only read.
  • A reference swap to an immutable snapshot. Build a fresh, immutable config object, then assign it to a volatile field. Readers atomically see either the complete old snapshot or the complete new one, never a mix — because the volatile write fences all the construction writes before it.

The disqualifiers are equally crisp. Increments, check-then-act, or any rule tying two variables together all push you to atomics or locks.

Land it My test is one sentence: if every write is "replace with a value I computed without reading the old one," volatile suffices — the moment the old value participates, it doesn't.

Likely follow-ups
"Why is the immutable snapshot idiom correct — walk me through the edges."

The writer constructs the new config object, which involves plain stores to its fields, and then does one volatile write of the reference.

The volatile write is a release: it cannot be reordered before the field stores, so by the time the reference is visible, the fields are too.

The reader does a volatile read, an acquire, and then reads the fields through that reference; its field reads cannot be reordered before the volatile read.

Together, the writer's volatile write happens-before the reader's volatile read that observes it, and program order extends that edge to the field stores and field reads.

The immutability is what makes it complete: because nobody ever writes those fields after construction, there is no later write for the reader to miss. If the config had a mutable field, the reader could see the snapshot with that field stale.

"When should the shutdown flag be volatile rather than using interrupt()?"

They solve slightly different problems and I often use both. A volatile flag is a stop signal for a loop that does not block: a computation that checks the flag each iteration.

interrupt() is the stop signal for a loop that does block: it wakes sleep, wait, take, and interruptible I/O, which a flag cannot.

A worker that does both — blocks on a queue and then does a long computation — needs the interrupt to wake it and can check isInterrupted() in the computation, so the flag becomes redundant.

Where the flag wins is clarity and ownership: the interrupt flag can be consumed by any library call along the way, while a named volatile boolean shutdownRequested belongs to my code and cannot be cleared by a third party.

"Is a volatile boolean enough for a 'started exactly once' guard?"

No, because "exactly once" is check-then-act: two threads can both read started == false and both proceed. The guard needs an atomic test-and-set, which is AtomicBoolean.compareAndSet(false, true) — the thread for which it returns true is the one that starts, everyone else sees false.

Volatile is the right tool for the mirror case, "has it started yet", where readers only observe. The distinction is the same as the increment: an assignment whose value depends on the current value is a compound operation.

Note that compareAndSet also gives the visibility edge, so anything the winner does before the set is visible to threads that later read the boolean; no additional volatile is needed.

Q169. "Explain happens-before in plain words, and give me the core rules you actually use."

Reveal answer

Strong answer Happens-before is the Java Memory Model's guarantee relation: if action A happens-before action B, then everything A wrote is guaranteed visible to B, and A is ordered before B. It is the only currency of cross-thread visibility — no happens-before edge, no guarantee, regardless of wall-clock timing. The rules I actually reason with:

  • Program order: within one thread, each statement happens-before the next — single-threaded code behaves as written.
  • Monitor rule: unlocking a monitor happens-before every subsequent lock of that same monitor — this is why synchronized publishes writes.
  • Volatile rule: a write to a volatile field happens-before every subsequent read of that field.
  • Thread start: everything a thread did before calling start() is visible inside the started thread.
  • Thread join: everything a thread did is visible to whoever returns from join() on it.

Edges also chain: if A happens-before B and B happens-before C, then A's writes are visible at C. Practical debugging becomes a search: find the chain of edges from the write to the read — and if you cannot, you have found the data race.

Land it "It ran earlier by the clock" proves nothing to the memory model — visibility flows only along happens-before edges, so my job is to make sure one exists between every shared write and its readers.

Likely follow-ups
"Which other library operations carry a happens-before edge that people forget about?"

Every blocking hand-off in java.util.concurrent. Putting into a BlockingQueue happens-before taking that element out, so the producer's writes to the object are visible to the consumer without any volatile on the object's fields.

Submitting a task to an executor happens-before the task runs; a task's completion happens-before Future.get() returns. CountDownLatch.countDown() happens-before await() returning; CyclicBarrier actions before the barrier are visible after it. Thread.start and join, as listed. Setting a value into an atomic happens-before reading it.

Any CompletableFuture completion happens-before its dependent stages run. Class initialization completing happens-before any thread's use of the class.

The practical rule is that if two threads communicate through a library object designed for communication, the edge is there; if they communicate through a plain field, it is not.

"Does happens-before mean 'happened earlier in time'?"

No, and that is the most common confusion. It is a relation about visibility, not wall-clock order.

If A happens-before B, then B is guaranteed to see A's effects; but two actions with no happens-before relation can still occur in any real-time order, and the one that occurred earlier by the clock is not guaranteed to be seen by the later one.

Conversely, an action that happens-before another may be reordered by the compiler as long as no observer can tell the difference. That is why "the write was two seconds before the read" proves nothing; only an edge does.

When I debug, I ask "what is the chain of edges from this write to this read?" and if I cannot draw it, the timing argument is irrelevant.

"What guarantee do final fields give, and what condition breaks it?"

The final-field freeze: when a constructor finishes, all final fields it assigned — and everything reachable through them at that moment — are guaranteed visible to any thread that obtains a reference to the object afterward, even without synchronization on the reference.

That is what makes immutable objects safely publishable through a racy field: a reader may see null or the object, but never a half-built object.

The condition that breaks it is the constructor leaking this before it completes: registering as a listener, starting a thread with this, storing this in a static. Then another thread can hold the reference before the freeze, and the guarantee is void.

The guarantee also does not extend to non-final fields, so a class with one plain field is not safely publishable without a volatile or lock.

"How does the JIT stay correct while reordering? Give me the rule it follows."

The as-if-serial rule plus the memory model's edges. Within one thread, the compiler may reorder any two operations that have no data dependency and are not separated by a synchronization action, because no single-threaded observer can tell.

At a synchronization action — a volatile access, a lock, an unlock — it must respect the edge: nothing after an acquire moves before it, nothing before a release moves after it.

Between threads, the guarantee is that a data-race-free program behaves as if all operations were interleaved in some sequentially consistent order.

The compiler's freedom is precisely the set of reorderings that are invisible to a race-free program, and a racy program gives up the interleaving guarantee entirely, which is why the racy config example can see states that no interleaving of the source code could produce.

Q170 · Scenario. "Thread A fills in a config object's fields, then sets a plain boolean ready = true. Thread B loops until ready is true, then reads the config — and intermittently sees null fields, but only on certain servers. How?"

Reveal answer

The real test Whether you believe instruction reordering is real, or think concurrency bugs are just "timing".

Strong answer Without volatile, nothing pins the flag write after the field writes — and nothing forces B to see them in that order:

  1. The writer side: the compiler and CPU may freely reorder independent stores, so ready = true can retire before some of the config field stores. A's single-threaded behavior is unchanged — which is the only thing plain code is guaranteed to preserve.
  2. The reader side is just as broken two ways: B can observe ready == true yet still read stale nulls for the fields, because no happens-before edge connects A's field writes to B's reads; or the JIT compiler can hoist the read of the plain ready out of B's loop entirely, leaving B spinning forever on a register.
  3. Why "only certain servers": hardware and JIT tiers differ. x86 has a fairly strong memory ordering, so the reorder shows rarely; ARM (a weakly-ordered CPU family common in newer server fleets) reorders aggressively, so the same JAR fails there. "Works on this box" is not evidence of correctness.
  4. The fix: declare ready as volatile. The volatile write forbids earlier stores from moving after it, and the volatile read forbids later loads from moving before it — so seeing ready == true now guarantees seeing every field written before it. Alternatives: publish under a common lock, or hand the object over via a mechanism that carries its own happens-before edge.

Land it A plain boolean flag is a claim with no enforcement — volatile is what turns "I set the flag last" into an ordering the reader can actually rely on.

Likely follow-ups
"You made ready volatile. Is the config's own object still safe if it has non-final, mutable fields?"

Safe for what the writer wrote before setting the flag, yes: the volatile write publishes every prior store, including plain stores to the config's fields.

It is unsafe for anything written after: if thread A later mutates a config field without another volatile write, thread B has no edge to that mutation and may never see it.

So the pattern is correct only if the config is effectively frozen once the flag is set, which is why I make the config class immutable — final fields, no setters — so the question cannot arise.

If the config must change over time, each change builds a new immutable instance and swaps it into a volatile reference, giving readers a consistent snapshot per read and a fresh edge per swap.

"How would you reproduce this on an x86 developer machine, where it 'never happens'?"

The reorder half is hard to reproduce on x86 because the hardware does not reorder stores with stores; the compiler half is easy. Take the reader, while (!ready) {}, and run it with C2 enabled: the loop never exits, because the load was hoisted.

That demonstrates the bug in one run. For the store-reorder half, jcstress has the message-passing test that, on an ARM machine — an Apple Silicon laptop is enough, or a Graviton instance — shows the "flag true, data stale" outcome within seconds.

The lesson I make explicit is that the platform difference is not a JVM bug: both behaviors are within the memory model, and the program was wrong on both platforms; x86 simply hid one half of it.

"What if thread B is a virtual thread — does anything change?"

Nothing about the memory model; virtual threads follow the same happens-before rules as platform threads, and the same volatile is required.

One practical difference: a virtual thread spinning on a non-volatile flag is worse than a platform thread doing it, because it never blocks, so it never unmounts from its carrier, and it occupies one of the few carrier threads permanently — with enough such spinners, every other virtual thread starves.

That makes a busy-wait loop a scheduler problem as well as a visibility problem.

The right shape for a virtual thread waiting for readiness is to block on a latch or a future, which parks it, releases the carrier, and provides the edge, so the volatile is not even needed.

Q171. "Walk me through double-checked locking: why was it famously broken, what makes it correct now, and what would you use instead?"

Reveal answer

Strong answer Double-checked locking tries to make lazy singleton initialization cheap: check the field without the lock, and only lock and initialize if it looks null. The historical bug is in the innocent-looking line instance = new Config(), which is really three steps — allocate memory, run the constructor, store the reference — and the JVM may reorder the store before the constructor finishes. A second thread doing the unlocked first check can then see a non-null reference, skip the lock entirely, and use a half-constructed object.

LazyConfig.java
class LazyConfig {
    private static volatile Config instance;   // volatile is the load-bearing word

    static Config get() {
        Config local = instance;               // one volatile read, kept in a local
        if (local == null) {
            synchronized (LazyConfig.class) {
                local = instance;              // re-check: another thread may have won
                if (local == null) {
                    instance = local = new Config();
                }
            }
        }
        return local;
    }
}

// Usually better — the holder idiom, lazy and lock-free by class-loading rules:
class ConfigHolder {
    private static class H { static final Config INSTANCE = new Config(); }
    static Config get() { return H.INSTANCE; }
}

Marking the field volatile fixes it: the volatile write cannot be reordered before the constructor's stores, so any thread that sees a non-null reference is guaranteed a fully built object. But in practice I prefer the holder idiom — the JVM's own class-initialization locking guarantees the nested class is initialized exactly once, lazily, on first use, with no volatile and no visible lock — or an enum singleton, which adds serialization safety for free.

Land it Double-checked locking is a great exam question and a mediocre pattern — knowing why it breaks proves you understand reordering, and knowing the holder idiom proves you don't need it.

Likely follow-ups
"Why copy the volatile field into a local variable? Isn't that just style?"

It is a real optimization and a correctness nicety. On the fast path, without the local, the code reads the volatile field twice — once in the null check and once in the return — and each is a volatile read that the JIT cannot merge.

With the local it is one volatile read. That is a measurable gain on ARM where a volatile read is an acquire instruction, and a small one on x86.

The correctness point is subtler: between two separate volatile reads, another thread could in theory replace the instance, and the method would return a different object than it checked. With the local, the checked value and the returned value are the same.

It is the pattern Joshua Bloch documents in Effective Java, and it costs nothing.

"Why is the holder idiom thread-safe with no volatile? What does the JVM guarantee?"

Class initialization is specified to be exactly-once and synchronized: the first thread to reference H takes the class's initialization lock, runs the static initializer, and marks the class initialized; any other thread arriving during that window blocks until it is done, and after that the JVM guarantees that all threads see the initialized statics — the completion of initialization happens-before any use.

Laziness comes from the fact that nested class H is not initialized when ConfigHolder is loaded; it is initialized on the first call to get().

After initialization, the JIT compiles get() to a plain load with no check, because the initialized state is a constant from then on. So it is faster than the volatile version and has no code to get wrong.

"When would you not want a lazy singleton at all?"

Most of the time in a modern service.

A singleton managed by a dependency-injection container is created once at startup, is testable because it can be replaced, and fails fast if its construction throws — whereas a lazy singleton throws at first use, deep in a request, at an unpredictable time.

Laziness is worth it only when construction is expensive and the object may never be used, or when initialization order between static singletons is a problem that laziness resolves.

Even then, a container's lazy bean scope gives me the same thing with a dependency graph I can see.

The enum singleton and the holder idiom are the right answers to the interview question and the right answers in library code with no container; in application code, the container is the right answer.

"What if Config's constructor can throw — how do the holder idiom and the enum behave?"

Badly, in a specific way worth knowing.

If the static initializer of H throws, the JVM wraps the exception in ExceptionInInitializerError for the first caller and marks the class as erroneous; every later caller gets NoClassDefFoundError with no useful cause, forever, for the life of that classloader. There is no retry.

The enum singleton has the same behavior, since the constants are initialized in the enum's static initializer.

So for a singleton whose construction can fail transiently — one that opens a connection, reads a file that might be locked — the holder idiom is the wrong tool; double-checked locking with a volatile, or a container with retry semantics, lets the next caller try again.

That is one of the few cases where the exam answer and the production answer differ.

Q172 · Scenario. "A class registers itself as a listener on an event bus in its own constructor. Rarely, the listener callback throws a NullPointerException on a field that the constructor definitely assigns. Explain the bug."

Reveal answer

The real test Whether you know safe publication and the this-escape trap — a bug that hides in perfectly readable code.

Strong answer The constructor leaked this before it finished — the object was published half-built:

  1. The moment bus.register(this) runs inside the constructor, the event bus holds a reference to an object whose constructor has not returned. If an event fires on another thread in that window, the callback runs against an object whose later field assignments have not happened — or are not yet visible — hence the impossible NullPointerException. It is rare because the window is microseconds, which is exactly why it survives testing.
  2. This also destroys the final field guarantee. The Java Memory Model promises that final fields are "frozen" and safely visible to all threads at the end of the constructor, and that promise is explicitly conditional on this not escaping during construction. Leak this early and even final fields can be seen unset.
  3. The fix: separate construction from publication. Make the constructor private and use a static factory that first fully constructs the object, and only then registers the completed instance on the bus. An init() or lifecycle callback after construction achieves the same separation.
  4. The same trap in other costumes: starting a thread from a constructor, passing this to any callback registry, or an inner class capturing the outer this — all publish an unfinished object.

Land it An object is only safe to share after its constructor returns — so construct first, publish second, and never let this out of a constructor's hands.

Likely follow-ups
"Show me the static factory version, and explain what makes it safe."

The constructor becomes private and does only field assignment: private Subscriber(Bus bus, Parser parser) { this.parser = parser; this.bus = bus; }. A static method does the rest: static Subscriber create(Bus bus, Parser parser) { Subscriber s = new Subscriber(bus, parser); bus.register(s); return s; }.

Safety comes from ordering: new returns only after the constructor has finished, so by the time register runs, every field assignment is complete, and if the fields are final, the freeze guarantee makes them visible to the bus's thread.

The bus's registration itself typically goes through a synchronized or concurrent collection, which provides the happens-before edge for non-final fields too. There is no window in which a reference to a partly built object exists outside the constructor.

"Is starting a thread in a constructor always wrong?"

Starting it is the problem; creating it is fine. A constructor may build a Thread object that captures this as long as start() is called later, from a start() or init() method on the finished object.

If the thread starts inside the constructor, it may run before the constructor's remaining assignments, and it also captures a reference to a subclass whose own constructor has not run yet — so a subclass field the thread reads is null even if the superclass constructor was careful.

Effective Java's guidance is the same for any escape: overridable method calls from a constructor have the identical hazard, since the override runs against uninitialized subclass state. The lifecycle-method pattern makes the ordering explicit and gives me a place to stop the thread too.

"How would you detect this-escape mechanically?"

The javac compiler has a lint category for it since JDK 21: -Xlint:this-escape warns when a constructor of a public class calls an overridable method or passes this somewhere before the constructor completes.

Error Prone and SpotBugs have related checks, and SpotBugs' SC_START_IN_CTOR flags a thread started in a constructor. I turn this-escape on as an error in library modules, where subclasses and callbacks are outside my control, and as a warning in application code.

At runtime the symptom is a rare NullPointerException on a field that is "definitely assigned", and I have learned to read that phrase as "assigned in the constructor, read from another thread before the constructor finished".

"Does making all the fields final fix the bug without changing the registration?"

No. The final-field guarantee is explicitly conditioned on this not escaping during construction; the freeze happens at the end of the constructor, and a reference that leaked before that point is not covered.

So with the registration still inside the constructor, another thread can observe the object through the bus before the freeze, and the final fields may appear null or default.

Finals fix the other half — unsafe publication of a fully constructed object through a racy reference — which is a different bug.

Both fixes together are the right design: final fields so the object is safely publishable, and construction before publication so there is a finished object to publish.

Q173. "A colleague says data races just mean 'the value might be stale for a few milliseconds, and that's fine for our use case.' Push back on that."

Reveal answer

Strong answer That mental model — "eventual freshness with a small lag" — is not what the Java Memory Model gives a racy program. It gives essentially no guarantees.

Concretely: staleness is unbounded, not brief — the JIT compiler may hoist a racy read out of a loop, so the thread reads a register forever and never sees the update; that is not a millisecond, that is a hang.

Order is not preserved — a reader can see the second write and not the first, which is how a "ready" flag can be true while the data it announces is absent, producing states no interleaving of the source code could ever create.

Even a single value can tear — a non-volatile long or double may legally be read as half of one write and half of another, yielding a number nobody wrote.

And the compiler optimizes assuming no races, so the transformations compound unpredictably across JVM versions and hardware.

Land it A benign data race isn't a small correctness discount — it is stepping outside the memory model's guarantees entirely, so the fix is an edge (volatile or a lock), not an argument about acceptable staleness.

Likely follow-ups
"Is there really no such thing as a benign race? What about String.hashCode?"

There is a narrow category the JDK itself uses, and it is worth understanding why it works. String.hashCode caches the hash in a non-volatile int field; two threads may both compute and store it.

It is safe because the computation is deterministic, so every thread that writes stores the same value; an int write is atomic, so a reader sees either zero or the correct hash, never garbage; and a reader that sees zero simply recomputes.

The race changes performance, never the result. Those three conditions — idempotent value, atomic single-word write, and reader tolerance of the stale value — are what make it benign, and they are rare. The colleague's case, where staleness affects behavior, meets none of them.

Even the JDK's version comes with a comment explaining the reasoning, which is the standard I would hold any deliberate race to.

"What tools can find data races, since tests don't?"

Three kinds. Static analysis with lock annotations: Error Prone's @GuardedBy checking turns "every access to this field must hold this lock" into a compile error.

Stress testing with jcstress, which runs small concurrent scenarios millions of times across cores and reports outcomes that the memory model permits but the author did not expect, including reordering outcomes that only appear on ARM. And dynamic race detection: Java has no ThreadSanitizer equivalent in HotSpot, but tools like the Java Pathfinder model checker for small pieces, or running the service under JFR and looking at fields accessed from many threads without any lock events, give partial coverage.

In practice, the highest-value tool is the review rule "name the edge", applied to every shared field.

"Give a concrete production example where the 'few milliseconds stale' assumption broke."

A feature-flag holder with a plain Map field that a refresh thread replaced every 30 seconds. On x86 in staging, request threads saw new flags within seconds.

In production on an ARM fleet, some request threads served stale flags for the life of the process — the JIT had compiled the hot handler with the map reference held in a register across the loop, so the refresh never became visible there.

The incident looked like a flag that "randomly" did not roll out to a subset of pods. The fix was one word, volatile, on the field, plus a review of every other cross-thread field in the service.

The lesson people took was that the staleness was not milliseconds; it was infinite, and it depended on which pod the request hit.

Drill · Deadlock, livelock & interruption

The closing group tests whether you can name how coordinated systems fail — frozen, spinning, or starved — and whether you know the one protocol that stops threads cleanly.

Q174. "What are the four necessary conditions for deadlock, and which one do you actually break in practice?"

Reveal answer

Strong answer A deadlock — threads frozen forever, each waiting for a lock another holds — requires all four of these at once, so removing any one prevents it:

  • Mutual exclusion: the resources are locks only one thread can hold at a time.
  • Hold and wait: a thread keeps the lock it has while waiting for another.
  • No preemption: nobody can forcibly take a lock away from its holder.
  • Circular wait: a cycle exists — A waits for B's lock while B waits for A's.

In practice the one I break is circular wait, with a global lock ordering: pick a total order over the locks — by account id, by a documented tier, by System.identityHashCode as a last resort — and require every thread to acquire multiple locks in that order. A cycle then becomes geometrically impossible, because a cycle needs someone acquiring against the order. The runner-up is breaking hold-and-wait with tryLock plus a timeout: if the second lock is not available, release everything, back off with some randomness, and retry — which converts a permanent freeze into a retry.

Land it All four conditions or no deadlock — and since ordering is free while timeouts add retry complexity, lock ordering is the default and tryLock is the fallback when order cannot be imposed.

Likely follow-ups
"How do you enforce a lock ordering across a large codebase, not just in one method?"

By making the order a property of the lock, not of the caller.

Each lock gets a level — a small integer in a wrapper class or an annotation — and a debug-mode check in the acquire path keeps a per-thread stack of held levels and throws if a thread tries to take a lock at a level lower than or equal to one it already holds.

That converts an ordering violation from a rare production deadlock into a deterministic exception in the first test that exercises the path.

For the common case of many locks of the same kind, like account locks, the order is by a stable key such as the ID, and a helper lockBoth(a, b) is the only permitted way to take two of them.

The documentation lives in the lock class, so it cannot drift from the code.

"Does the JVM detect deadlocks for you, and what can you do when it finds one?"

It detects them on request, not continuously. jstack and jcmd Thread.print run a cycle detection over monitors and ReentrantLocks at dump time and print "Found N Java-level deadlocks" with the threads and locks involved.

ThreadMXBean.findDeadlockedThreads() exposes the same check programmatically, so a health check can call it every minute and report a deadlock as unhealthy, which is how I get a pod restarted automatically rather than at 2am by a human.

What I cannot do is break the deadlock: there is no way to force a thread to release a monitor, and Thread.stop is gone.

So detection buys a faster restart and the exact stack traces for the fix, and prevention through ordering is still the real answer.

"Give me a deadlock that has nothing to do with locks."

Thread-pool starvation deadlock: a pool of ten threads where each task submits a subtask to the same pool and waits on its future.

Once ten outer tasks are waiting, the subtasks sit in the queue with no thread to run them, and everyone waits forever with no lock in sight; the dump shows all ten threads WAITING in Future.get.

The same shape appears with bounded queues — a producer blocks on a full queue while the consumer that would drain it is blocked waiting for that producer — and with database connection pools, where a transaction holding one connection requests a second.

The four conditions still apply with "resource" replacing "lock". The fix is the same family: never wait for a resource of a kind you are holding, or size the pool so that cannot exhaust it.

"What is the cost of the tryLock-with-timeout approach that makes ordering preferable?"

Three things. Complexity: every acquisition site needs a retry loop, a backoff, and a policy for giving up, which is much more code than a fixed order.

Livelock: two threads that both back off and retry in lockstep can spin without progress, so the backoff must be randomized.

And latency: a timeout means a thread waits the full timeout before discovering it should retry, so under contention the tail latency includes a multiple of the timeout, which for a 100ms timeout is a visible p99 hit.

Ordering has none of these costs; it is a rule about which lock first, enforced at the two-lock call sites, and it makes the deadlock structurally impossible rather than recoverable.

That is why ordering is the default and tryLock is the fallback where no natural order exists.

Q175 · Scenario. "Your payments service froze at 2am. CPU is near zero, requests time out, and a restart 'fixed' it. The code transfers money between accounts by locking the from-account, then the to-account. Diagnose and fix it."

Reveal answer

The real test The full senior loop: recognize deadlock from the symptoms, prove it, and name the ordering fix — not just say the word.

Strong answer Idle CPU with hung requests is the signature of threads waiting on each other, and the lock pattern confirms a classic two-lock deadlock:

  1. Diagnosis: a thread dump of the frozen process would show two threads BLOCKED, each owning the monitor the other wants, and the JVM prints the cycle explicitly under "Found one Java-level deadlock". The trigger: thread 1 runs transfer(a, b) and locks a; thread 2 concurrently runs transfer(b, a) and locks b; each now waits forever for the other's lock. All four deadlock conditions are present, and circular wait is the one this code hands out for free.
  2. The fix is a global acquisition order — always lock the lower-id account first, regardless of transfer direction:
Transfer.java
// BROKEN: lock order depends on argument order
void transfer(Account from, Account to, long amount) {
    synchronized (from) {
        synchronized (to) {          // T1: holds a, wants b
            from.debit(amount);      // T2: holds b, wants a  -- frozen forever
            to.credit(amount);
        }
    }
}

// FIXED: one global order (by unique id), same for every caller
void transfer(Account from, Account to, long amount) {
    Account first  = from.id() < to.id() ? from : to;
    Account second = (first == from) ? to : from;
    synchronized (first) {
        synchronized (second) {
            from.debit(amount);
            to.credit(amount);
        }
    }
}
  1. Now both transfers, in either direction, lock the same account first — no cycle can form. If ids can be equal (self-transfer), reject that case up front.
  2. Prevention: document the lock order, keep locked sections tiny, and prefer tryLock with timeout and backoff where a natural order does not exist — a timed-out transfer that retries is infinitely better than a frozen service at 2am.

Land it The restart didn't fix anything — it just rolled the dice again; only a global lock order makes the freeze structurally impossible.

Likely follow-ups
"Ordering by ID fixed it, and a month later the same freeze returns. What now?"

A new code path takes the locks in a different order, or a third lock entered the picture. First I get the evidence again: a thread dump with the deadlock section, which names the exact locks and stacks.

Typical findings are a batch job that locks accounts in list order rather than ID order; a new feature that locks a customer object and then an account, while the transfer path locks an account and then reaches the customer through a callback; or a database lock combined with a JVM lock, where one thread holds the row lock and waits for the monitor and the other holds the monitor and waits for the row.

The fix is to bring every acquisition through the same ordered helper and to treat any new lock as a design change that must be placed in the order, not just added.

"Why did the restart 'fix' it, and what does that tell you about the failure rate?"

The restart cleared the state: both threads died, the locks were released, and the process started fresh.

It fixed nothing because the code is unchanged and the deadlock needs only two concurrent transfers in opposite directions between the same pair of accounts, which is a probability question — low per request, but with millions of transfers per day it is a certainty within some window.

The rate tells me how often that pair-and-direction coincidence happens, which rises with traffic and with the popularity of a few accounts, such as a merchant account everyone pays.

So the failure will recur, sooner under higher load, and the on-call playbook that says "restart" is buying time, not safety. I would add the deadlock health check so the restart at least happens automatically while the fix ships.

"Should this even be in-JVM locking? What about the database?"

For money movement, the database is the real place. The transfer is a transaction: debit one row, credit another, commit.

With row locks, the same deadlock can happen inside the database — transaction one locks row A then wants B, transaction two the reverse — but the database detects it within seconds and aborts one transaction with a deadlock error that the application retries.

The same ordering discipline applies there: update the lower ID first, or lock both with SELECT ... FOR UPDATE ... ORDER BY id.

The in-JVM lock only helps for one instance and adds nothing once there are two; it also cannot cover a crash between debit and credit, which the transaction does.

So the honest answer is that the interview scenario tests lock ordering, and the production design removes the JVM lock entirely.

"What would you add to the dashboard so this is caught before the freeze?"

A deadlock detector metric and a lock-wait metric. The first is a scheduled call to ThreadMXBean.findDeadlockedThreads() exported as a gauge, alerting on any non-zero value — it catches the freeze within a minute and produces the stack traces automatically.

The second is JFR's jdk.JavaMonitorEnter event with a threshold, or Micrometer's thread-state gauges, so a rise in BLOCKED threads or in monitor wait time shows the contention growing before it becomes a full stop.

For the transfer path specifically, a histogram of transfer latency with a p99 alert catches the slowdown that precedes the deadlock, when a few threads are stuck but the pool is not yet exhausted.

Q176 · Scenario. "Two of your retrying workers each grab one resource, detect the other holds the second, politely release, retry — and the system burns 100% CPU making zero progress. What is this, and how is it different from deadlock?"

Reveal answer

Strong answer That is livelock — threads continuously active, continuously responding to each other, and collectively going nowhere. The everyday picture is two people meeting in a hallway who both step to the same side, then both step to the other side, forever — each reaction is individually reasonable, and the symmetry never breaks.

  1. The distinction from deadlock is in the dump and the CPU: deadlocked threads are BLOCKED and the CPU is idle; livelocked threads are RUNNABLE, the CPU is pegged, logs stream retry messages — yet throughput is zero. Deadlock is frozen; livelock is spinning.
  2. The mechanism: both workers run the same deterministic conflict-resolution rule — "if I can't get the second resource, release the first and immediately retry." Because they execute it in lockstep, every retry collides again. The politeness that was supposed to prevent deadlock became the failure mode.
  3. The fixes all break the symmetry: add randomized backoff — each worker sleeps a random interval before retrying, so their schedules decorrelate (this is exactly how Ethernet resolved collisions); or impose a priority or ordering so one worker deterministically wins and the other waits; or route the contended decision through a single arbiter so there is no symmetric race at all.
  4. Prevention: any "detect conflict, back off, retry" loop in a review gets one question — what guarantees two identical actors don't retry in lockstep? If the answer isn't randomness or ordering, it's a latent livelock.

Picture it Two workers that politely release and retry in lockstep, step by step, next to what a thread dump shows for livelock versus deadlock.

The setup: Each worker locks its first resource, tries the second, and on failure releases the first and retries at once.

livelock setupruns offline
final ReentrantLock a = new ReentrantLock(), b = new ReentrantLock();

void worker1() {                         // worker2 is the mirror image: b first, then a
    while (true) {
        a.lock();
        if (b.tryLock()) {               // got both: do the work
            try { work(); return; } finally { b.unlock(); a.unlock(); }
        }
        a.unlock();                      // ❌ TRAP: "politely" release and retry at once, in lockstep
    }
}

The trace: Both workers repeat the same four steps in the same rhythm, so every retry collides again.

lockstep trace
step  worker-1 (A then B)                 worker-2 (B then A)
1     lock A       ✓                      lock B       ✓
2     tryLock B    ✗ worker-2 holds it    tryLock A    ✗ worker-1 holds it
3     unlock A  (polite)                  unlock B  (polite)
4     lock A       ✓                      lock B       ✓      <- identical to step 1
...   steps 1-4 repeat forever            work() is never reached ✗

What you see: Both threads are RUNNABLE and the CPU is pegged, while the completed-jobs counter stays at zero.

thread dump and top
# illustrative output
"worker-1" ... java.lang.Thread.State: RUNNABLE      <- a deadlock would say BLOCKED or WAITING
    at java.base/java.util.concurrent.locks.ReentrantLock.tryLock(ReentrantLock.java:...)
    at Worker.worker1(Worker.java:9)
"worker-2" ... java.lang.Thread.State: RUNNABLE
top:  java  199% CPU      app log: retry #1204883      jobs completed per second: 0
Deadlock versus livelock, same two resources
DeadlockLivelock
Thread stateBLOCKED / WAITINGRUNNABLE
CPUidlepegged
Logssilentretry messages stream by
Throughputzerozero

Why: Both workers run the same deterministic rule at the same moment, so the symmetry never breaks.

The fix: Add capped exponential backoff with random jitter and a bounded attempt count.

livelock fixruns offline
void worker1() throws InterruptedException {
    for (int attempt = 1; attempt <= 8; attempt++) {
        a.lock();
        if (b.tryLock()) {
            try { work(); return; } finally { b.unlock(); a.unlock(); }
        }
        a.unlock();
        long cap = Math.min(200, 5L << attempt);                         // exponential, capped at 200 ms
        Thread.sleep((long) (cap * ThreadLocalRandom.current().nextDouble(0.5, 1.5)));  // ✅ FIX: jitter breaks the symmetry
    }
    throw new IllegalStateException("gave up after 8 attempts");
}

What you see now: One worker wakes first, takes both locks, and the other follows.

console
# illustrative output
worker-1  attempt 1  conflict, sleeping 11 ms        worker-2  attempt 1  conflict, sleeping 7 ms
worker-2  attempt 2  got both locks, work() done      <- schedules have decorrelated
worker-1  attempt 2  got both locks, work() done
top:  java  3% CPU          jobs completed per second: 480

Land it Deadlock is everyone waiting and livelock is everyone busily yielding — and the cure for livelock is injected asymmetry, usually a random backoff.

Likely follow-ups
"Randomized backoff — what are the actual numbers you would use?"

Exponential with jitter, capped.

Start at a base of a few milliseconds, double each retry, cap at something like 200ms so a burst of conflicts does not turn into multi-second waits, and multiply each delay by a random factor between 0.5 and 1.5 so two workers never share a schedule.

In code, delay = min(cap, base * 2^attempt) * ThreadLocalRandom.current().nextDouble(0.5, 1.5).

I also cap the attempt count, typically five to ten, after which the operation fails with a clear error rather than retrying forever, and I count retries as a metric because a rising retry rate is the early signal that contention is growing.

These are the same numbers used for retrying network calls, and for the same reason: decorrelation is what makes retries converge.

"How do you tell livelock from a legitimately busy system at 100 percent CPU?"

Throughput. A busy system is completing work — requests per second, records processed — in proportion to its CPU use; a livelocked system is at full CPU with a throughput near zero. So I look at the work counters first.

Then the profile: in a livelock, a CPU profile such as async-profiler's flame graph shows almost all time in the conflict-detection and retry path — acquiring, checking, releasing, sleeping — rather than in the business logic.

Logs show retry messages at a rate far above the request rate. Thread dumps show the same threads in the same retry frames across several samples. The combination of high CPU, zero progress, and a retry loop dominating the profile is the diagnosis.

"Is there a livelock that doesn't involve locks at all?"

Yes, retry storms between services. Service A calls B, B times out under load, A retries immediately, which increases B's load, which causes more timeouts, which causes more retries — the system is fully busy and completing nothing.

Message queues have one too: a consumer that fails a message and immediately re-delivers it to itself, forever, with every consumer doing the same on its own poison message.

Optimistic concurrency at scale is another: many writers retrying the same hot row, each retry invalidating the others, so the row is updated once per many attempts.

The cure is always asymmetry or a limit: jittered backoff, retry budgets, circuit breakers, dead-letter queues after N failures, or a single arbiter. The hallway picture applies to all of them.

Q177. "What is starvation, and where have you actually seen it happen?"

Reveal answer

Strong answer Starvation is when a thread that is ready and willing to run keeps losing the competition for a resource. It is not blocked by a bug — just perpetually outcompeted.

There are three realistic sources:

  • Unfair locks. Intrinsic monitors make no fairness promise. When a lock frees up, a freshly arriving thread can "barge" in ahead of threads that have been queued for seconds, so under sustained contention an unlucky thread can wait almost indefinitely.
  • Read/write imbalance. With a readers-writer scheme and a steady stream of readers, a writer can wait forever for the moment when no reader holds the lock. Writes starve while reads flow.
  • Priority misuse — starving low-priority threads, on platforms that do honour priorities.

The remedies are all about bounding the unfairness rather than eliminating it. Fair-mode locks grant in arrival order, at a real throughput cost, so I reach for fairness only when starvation is actually observed. Keeping lock hold times short makes the competition churn quickly. And capping how long readers can keep a writer waiting fixes the second case directly.

Picture it An unfair lock handing itself to a newly arriving thread again and again while an older waiter stays parked, and the per-thread wait numbers that expose it.

The setup: Many hot threads hammer one lock; a single thread that arrived early just wants one turn.

starvation setupruns offline
// ❌ TRAP: the default ReentrantLock is unfair, a thread arriving at the right instant may jump the queue
private final ReentrantLock lock = new ReentrantLock();

void hot() {                                  // run by 8 threads: hot-1 .. hot-8
    for (;;) { lock.lock(); try { updateCounter(); } finally { lock.unlock(); } }
}
void needsOneTurn() { lock.lock(); try { updateCounter(); } finally { lock.unlock(); } }   // run by "starved"

The trace: At every release the head of the queue has to be woken, while a running hot thread simply grabs the free lock first.

lock hand-off trace
release  owner -> next   parked queue (oldest first)   what happened
#1       hot-1 -> hot-3  starved                       hot-3 called lock() the instant it was free; CAS ✓ (barge)
                                                       starved was woken, found it taken again ✗ parks again
#2       hot-3 -> hot-5  starved                       same story ✗
#3       hot-5 -> hot-2  starved                       same story ✗      ... thousands of times

What you see: A JFR monitor-wait summary sorted by maximum wait shows a healthy median everywhere and one catastrophic tail.

jdk.JavaMonitorEnter / jdk.ThreadPark by thread
# illustrative output
thread     acquisitions   median wait   p99 wait   max wait
hot-1      41,210         0.02 ms       0.4 ms     3 ms
hot-2      40,977         0.02 ms       0.5 ms     4 ms
starved    3              1.9 s         6.8 s      6.8 s      <- fat tail, median fine elsewhere

Why: Nothing is stuck or buggy; the starved thread is simply outcompeted every time the lock changes hands.

The fix: Pay the fairness tax on this one lock only, because the measurement showed a real tail.

fair lockruns offline
private final ReentrantLock lock = new ReentrantLock(true);   // ✅ FIX: fair mode grants in arrival order

What you see now: The tail collapses, and total throughput drops, which is the price.

same table, fair lock
# illustrative output
thread     acquisitions   median wait   p99 wait   max wait
hot-1      13,044         0.07 ms       0.9 ms     9 ms
hot-2      13,051         0.07 ms       0.9 ms     8 ms
starved    1,000          0.07 ms       0.8 ms     9 ms       <- gets its turns; whole-system throughput is about 3x lower

Land it Unfair locks are faster and usually fine — I pay the fairness tax only when metrics show some thread's wait time growing without bound.

Likely follow-ups
"How would you measure starvation rather than suspect it?"

By measuring per-thread wait time on the lock, not the average. JFR's jdk.JavaMonitorEnter and jdk.ThreadPark events give the duration of each blocked acquisition with the thread name; sorted by maximum rather than mean, a starved thread shows waits of seconds while the median is microseconds.

With Micrometer I record a timer around the acquisition in the code path I suspect and look at the p99.9 and max.

The signature of starvation is a fat tail with a healthy median: throughput is fine, most requests are fine, and a few are catastrophically slow. That is different from contention, where the median itself rises.

If the maximum wait is bounded by a few milliseconds, there is no starvation, and fairness would only cost throughput.

"Where does writer starvation come from in ReentrantReadWriteLock, and how is it mitigated?"

In non-fair mode, readers can acquire the read lock whenever no writer holds the write lock, and with a steady stream of readers there is never a moment when zero readers hold it, so a queued writer waits indefinitely.

The mitigation built in is that once a writer is at the head of the wait queue, newly arriving readers block behind it rather than barging, which bounds the writer's wait to the duration of the readers already inside. Fair mode makes all acquisitions first-come-first-served.

The residual problem is reentrant readers: a thread holding the read lock that re-acquires it is allowed through even with a queued writer, to avoid deadlock, so deeply reentrant read paths can still hold writers off.

StampedLock avoids the issue differently by having no reader reentrancy at all.

"Can a thread pool cause starvation without any lock?"

Yes, in two ways. Queue starvation: a FIFO work queue behind a small pool means a task submitted during a burst waits behind everything ahead of it, and if the burst never ends, some tasks wait unboundedly — that is starvation by queue position.

Priority inversion in a pool: a PriorityBlockingQueue with a continuous supply of high-priority tasks means low-priority tasks never run, which is starvation by design and needs an aging rule where priority rises with wait time.

The third form is the common-pool problem: parallel streams starved by blocked CompletableFuture tasks. The instrument in every case is queue wait time per task, recorded from submission to start, and the fix is bounding the queue, aging priorities, or separating pools.

Q178. "What does calling interrupt() on a thread actually do? Does it stop the thread?"

Reveal answer

Strong answer It does not stop anything — interrupt() is a request, and Java's cancellation is cooperative by design. Mechanically it does exactly two things. First, it sets the target thread's interrupt flag, a boolean the thread carries.

Second, if the target is parked in a blocking method that promises interruptibility — wait(), sleep(), join() — that method wakes immediately and throws InterruptedException, clearing the flag as it does. That is all.

A thread crunching numbers with no blocking calls notices nothing unless its code periodically checks Thread.currentThread().isInterrupted() and reacts.

The design is deliberate: only the running code knows where it is safe to stop — after finishing the current record, after releasing resources — so the JVM delivers the request and the code chooses the stopping point.

Writing loops that check the flag, and treating InterruptedException as "wrap up and exit," is what makes a thread actually cancellable.

Picture it What the interrupt flag does to a sleeping thread versus a thread that is busy computing.

The setup: Two threads: one sleeps, one crunches numbers and never checks anything.

interrupt setupruns offline
Thread sleeper = new Thread(() -> {
    try { Thread.sleep(60_000); }
    catch (InterruptedException e) {
        System.out.println("sleeper woke, flag=" + Thread.currentThread().isInterrupted());
    }
});
Thread cruncher = new Thread(() -> {
    long n = 0;
    while (true) n++;                         // ❌ TRAP: never looks at the interrupt flag
});
sleeper.start(); cruncher.start();
sleeper.interrupt(); cruncher.interrupt();

The trace: The same call sets the same flag on both threads, but only one of them is in a method that checks it.

interrupt flag trace
step  call                    sleeper (in sleep)                       cruncher (in loop)
1     interrupt()             flag = true                              flag = true
2     JVM checks for waiter   sleep() sees flag, wakes ✓               nobody checks ✗
3     result                  throws InterruptedException, flag = false   flag stays true, loop keeps spinning

What you see: The sleeper reports that its flag was cleared, and the cruncher is still running.

console
sleeper woke, flag=false
cruncher: isAlive()=true   isInterrupted()=true   state=RUNNABLE      <- the request arrived, nobody read it

Why: interrupt() only sets a flag and wakes interruptible waiters; stopping is the target code's job.

The fix: Make the loop poll the flag and exit at a safe point.

cancellable loopruns offline
Thread cruncher = new Thread(() -> {
    long n = 0;
    while (!Thread.currentThread().isInterrupted()) {   // ✅ FIX: poll the flag once per unit of work
        n++;
    }
    // release resources here, then fall off the end
});

What you see now: The same interrupt() call now ends the thread.

console
cruncher: isAlive()=false      <- exited at the next flag check

Land it interrupt() delivers a message, not a bullet — cancellation only works if the target code was written to listen, which is a design responsibility, not a JVM feature.

Likely follow-ups
"Which blocking operations do not respond to interrupt, and what do you do about them?"

Classic blocking I/O: a read on a Socket stream or a FileInputStream ignores the interrupt flag and keeps blocking; closing the socket from another thread is the way to wake it, which throws SocketException in the reader.

Acquiring a synchronized monitor cannot be interrupted at all; ReentrantLock.lockInterruptibly() is the interruptible alternative. Object.wait and LockSupport.park do respond.

Since JDK 21 with virtual threads, most socket I/O in the JDK is implemented on interruptible NIO channels, so a virtual thread blocked in a socket read does wake on interrupt with a ClosedByInterruptException.

For everything else the escape hatch is a timeout on the blocking call — setSoTimeout, a JDBC query timeout — so the thread periodically returns to check the flag.

"What is the difference between isInterrupted() and Thread.interrupted()?"

isInterrupted() is an instance method that reads the flag and leaves it set. Thread.interrupted() is a static method that reads the flag for the current thread and clears it.

The static one exists for code that is about to handle the interrupt and wants to consume the request; the instance one is for polling.

The common bug is calling Thread.interrupted() in a log statement or a condition, which silently clears the flag so the rest of the code never sees it.

The rule: poll with Thread.currentThread().isInterrupted(), and only use interrupted() at the point where the code takes responsibility for the cancellation — typically right before throwing InterruptedException yourself.

"How does interruption interact with an executor's Future.cancel and shutdownNow?"

Future.cancel(true) on a FutureTask interrupts the thread running the task, if any, and marks the future cancelled; cancel(false) only prevents a not-yet-started task from running. shutdownNow() interrupts every worker and returns the queued tasks that never started.

In both cases the worker thread survives: ThreadPoolExecutor clears the interrupt flag before running the next task, so an interrupt meant for one task does not leak into the next.

That design has a corollary — a task that catches InterruptedException, restores the flag, and returns is doing the right thing, and the pool takes it from there.

A task that swallows it keeps running, and shutdownNow then waits on awaitTermination until the task finishes on its own.

"Why is cancellation cooperative rather than preemptive — what did preemptive cost?"

Preemptive cancellation is Thread.stop, and its cost was corrupted invariants: a thread killed at an arbitrary instruction leaves whatever it was updating half done, and because the kill releases its monitors, the half-done state becomes visible to everyone.

There is no way for the runtime to know where it is safe to stop a thread — only the code knows that it has finished writing the record, released the buffer, and left the data structure consistent.

Cooperative cancellation moves that knowledge to where it exists: the code checks for the request at points it chose, and the runtime only delivers the request.

The price is that uncooperative code cannot be stopped, which is why interruptibility is a design requirement for any long-running task and why I review for it.

Q179 · Scenario. "Cancel requests do nothing, and service shutdown takes ten minutes until it's force-killed. In the worker loop you find: catch (InterruptedException e) { /* ignore */ }. Connect the dots."

Reveal answer

The real test Whether you know that swallowing InterruptedException doesn't just ignore an error — it destroys the cancellation signal.

Strong answer That empty catch block is the whole outage — it eats the only stop signal the thread will ever get:

  1. Connect the mechanics: shutdown interrupts the worker threads. A worker parked in sleep() or wait() wakes with InterruptedException — and, crucially, the throw also clears the interrupt flag. The empty catch then discards the exception. At that instant the thread holds zero evidence it was ever asked to stop: no exception, no flag. So the loop condition still passes, the worker goes back to work, shutdown waits, and after the grace period the process gets force-killed — mid-write, without cleanup.
  2. The correct handling is one of exactly two moves. Either propagate: declare throws InterruptedException and let the loop unwind and terminate. Or, where you cannot throw — inside a Runnable, say — restore the flag and exit: call Thread.currentThread().interrupt() in the catch, then break out, so both this code and any caller checking the flag see the request.
  3. What is never correct is the silent swallow: it launders a cancellation request into nothing, and every layer above it — pool shutdown, timeouts, cancel buttons — silently stops working.
  4. Prevention: static analysis flags empty InterruptedException handlers, and the review rule is simple — that exception is not an error to log and forget, it is an instruction.

Picture it How the interrupt flag and the exception disappear together inside an empty catch block, and the shutdown test that exposes it.

The setup: A worker loop whose catch block ignores the exception.

swallowed interruptruns offline
Runnable worker = () -> {
    while (running) {
        try {
            Thread.sleep(1_000);              // poll for work
            doWork();
        } catch (InterruptedException e) {
            /* ignore */                      // ❌ TRAP: the only stop signal is destroyed here
        }
    }
};

The trace: Throwing InterruptedException clears the flag, so after the empty catch the thread holds no evidence it was asked to stop.

flag and exception trace
step  event                                    interrupt flag   exception in flight
1     pool.shutdownNow() -> worker.interrupt()  true             -
2     sleep() sees the flag, throws             false (cleared)  InterruptedException
3     catch { /* ignore */ }                    false            none ✗ signal is gone
4     while (running) still true                false            loop goes around again ✗

What you see: The shutdown test with a two-second budget fails, and the worker is still inside its loop.

shutdown test and thread dump
# illustrative output
pool.shutdownNow();
pool.awaitTermination(2, TimeUnit.SECONDS)   ->  false          <- worker did not stop
"pool-1-thread-1" ... java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.base/java.lang.Thread.sleep(Native Method)
    at Worker.lambda$run$0(Worker.java:7)       <- back in sleep(), asleep for the next second

Why: The catch block converted a cancellation request into nothing, so every layer above it stopped working.

The fix: Restore the flag and leave the loop.

restore the flag and exitruns offline
Runnable worker = () -> {
    try {
        while (running && !Thread.currentThread().isInterrupted()) {
            Thread.sleep(1_000);
            doWork();
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();   // ✅ FIX: restore the flag for callers, then exit
    } finally {
        cleanup();                            // runs on normal and interrupted exit
    }
};

What you see now: The same test passes within milliseconds.

shutdown test
# illustrative output
pool.shutdownNow();
pool.awaitTermination(2, TimeUnit.SECONDS)   ->  true           <- worker unwound and exited

Land it InterruptedException means "please stop" — you may forward the message or act on it, but swallowing it converts a clean shutdown into a kill -9.

Likely follow-ups
"You fixed the catch block, and shutdown still takes minutes. What next?"

Then the worker is stuck somewhere that interruption does not reach, or the shutdown sequence itself is wrong. I take a thread dump during the slow shutdown and read the worker's frame.

If it is in a blocking socket read or a JDBC call, the interrupt cannot wake it, and the fix is a timeout on that call or closing the connection from the shutdown path.

If it is in a long computation that never checks the flag, I add isInterrupted() checks to the loop.

If the worker is idle and the pool is waiting anyway, the shutdown code is calling awaitTermination with a huge timeout before ever calling shutdownNow, or a non-daemon thread outside the pool is holding the JVM open.

And I check terminationGracePeriodSeconds against the measured drain time so the platform is not killing the process mid-drain.

"Show me the correct catch block for a Runnable that cannot throw."

Inside the loop: catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } — or return, depending on the structure.

correct catch in a loopruns offline
while (!Thread.currentThread().isInterrupted()) {
    try {
        process(queue.take());
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();   // restore for callers and finally blocks
        break;                                // and actually stop
    }
}

The first line restores the flag so that code further up the stack, including the pool's own logic and any finally blocks that check for cancellation, sees the request; the second line exits the loop so the thread actually stops.

If there is cleanup to do — flushing a buffer, closing a resource — it goes in a finally around the loop, not in the catch, so it runs on normal exit too.

What I do not do is log at error level, because an interrupt during shutdown is expected, and a service that logs a stack trace on every clean shutdown trains people to ignore stack traces.

"Is wrapping it in a RuntimeException acceptable?"

Only if the flag is restored first, and even then it is a compromise.

throw new RuntimeException(e) without restoring the flag has the same problem as swallowing: the unchecked exception unwinds the current task, but the thread's interrupt status is clear, so anything that catches the runtime exception and continues — a retry wrapper, a framework's error handler — proceeds as if no cancellation was requested.

With Thread.currentThread().interrupt() before the throw, both signals exist. Some libraries have a dedicated type for this, such as Guava's UncheckedExecutionException pattern or Spring's approach of restoring and rethrowing as an IllegalStateException.

The cleanest option is still to declare the checked exception where possible and let callers decide.

"How do you make sure this never regresses across a large codebase?"

Build-time rules plus a shutdown test. SonarQube's S2142, "InterruptedException should not be ignored", and Error Prone's equivalent flag the empty or log-only catch; I set them to fail the build. SpotBugs has a related check for catching InterruptedException without restoring the flag.

Then a test that starts the real worker with a short-running task, calls shutdownNow(), and asserts awaitTermination(2, SECONDS) returns true — a swallowed interrupt makes it return false and fails the test in two seconds. Run that test for every long-running worker type.

The combination catches both the pattern at review time and the behavior at test time, which is more than either does alone.

Q180. "Why were Thread.stop() and Thread.suspend() deprecated? They sound convenient."

Reveal answer

Strong answer Both are convenient in exactly the way a fire alarm that cuts the building's power is convenient. Thread.stop() kills a thread asynchronously — an error surfaces at whatever instruction the thread happens to be executing, including halfway through updating a data structure.

Worse, as the thread dies it releases every monitor it holds, so the locks that were protecting the half-finished mutation open up and every other thread now sees corrupted state, with no exception and no trace — the damage surfaces minutes later somewhere unrelated.

Thread.suspend() fails in the opposite direction: it freezes the thread but the thread keeps all its locks, so anything needing one of them blocks until a matching resume() — and if the resumer itself needs such a lock first, that is a deadlock by API design.

The replacement is the cooperative protocol: interrupt() plus a volatile stop flag, letting the thread exit at a point where its invariants hold and its resources are released. Modern JDKs have removed stop() outright.

Picture it What a monitor-protected transfer looks like when stop() lands in the middle of it, and the suspend()/resume() lock cycle.

The setup: A transfer that must keep the total constant, guarded by one lock.

transfer under a lockruns offline
synchronized (lock) {
    from -= 100;          // total is now 100 short
    // <- stop() can land here: ThreadDeath is thrown at this instruction
    to   += 100;
}

The trace: The thread dies at an arbitrary instruction and drops its monitor on the way out.

stop() trace
step  thread T1 (transferring)                  thread T2 (auditing)          state
1     lock acquired                                                           from=1000 to=500  total=1500
2     from -= 100                                                             from=900  to=500  total=1400
3     stop() hits T1, ThreadDeath unwinds                                     monitor released ✗ invariant broken
4                                                  lock acquired ✓            reads total=1400, no exception ✗

What you see: The audit sees corrupted state with no error, and on a current JDK the call itself is refused.

console
audit: total=1400 (expected 1500)                      <- silent corruption, noticed minutes later elsewhere
// on a modern JDK the call itself fails:
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.lang.Thread.stop(Thread.java:...)
suspend() / resume() cycle
T1: synchronized (lock) { ... suspended here, still HOLDING lock ... }
T2: synchronized (lock) { t1.resume(); }      <- T2 waits for lock, T1 can never release it  ✗ deadlock

Why: stop() frees monitors around half-done work, and suspend() freezes a thread while it keeps its monitors.

The fix: Cooperative cancellation: the thread checks a volatile flag or the interrupt flag and exits where its invariants hold.

cooperative stopruns offline
private volatile boolean stopRequested;

void run() {
    while (!stopRequested && !Thread.currentThread().isInterrupted()) {   // ✅ FIX: check at a safe point
        synchronized (lock) { from -= 100; to += 100; }                  // never abandoned mid-way
    }
}
void requestStop(Thread t) { stopRequested = true; t.interrupt(); }

What you see now: The thread leaves between transfers and the invariant holds.

console
audit: total=1500 (expected 1500)
worker exited cleanly after current transfer

Land it stop() releases locks around broken invariants and suspend() holds locks indefinitely — one corrupts, the other deadlocks, which is why cancellation in Java is cooperative or nothing.

Likely follow-ups
"What exactly happens if I call Thread.stop() on a current JDK?"

As of Aug 2026, it throws UnsupportedOperationException unconditionally. JDK 20 changed stop(), suspend(), and resume() from deprecated-but-working to always throwing, so the methods still exist for binary compatibility but do nothing except fail.

Before that, JDK 11 had already made stop() throw when called on a thread other than the current one in some cases, and Thread.stop(Throwable) was removed in JDK 11.

So code that relied on stop() to kill runaway tasks — some old test frameworks and scripting sandboxes did — breaks at runtime on modern JDKs, and the replacement is cooperative: interrupt plus a timeout, and for truly untrusted code, running it in a separate process that can be killed by the operating system.

"How do you stop a runaway computation that ignores interrupts, then?"

Inside one JVM, you cannot, safely, and that is the honest answer.

What I can do is limit the damage: run it on a dedicated thread so it does not occupy a shared pool, mark that thread daemon so it does not block JVM exit, stop feeding it work, and report it.

If runaway code is a real risk — user-supplied scripts, plugins — the design must put it where it can be killed: a separate process with a CPU and memory limit, or a sandboxed engine that inserts its own cancellation checks into the code it runs, which is what GraalVM's polyglot engine does with its resource limits.

Within Java code I own, the fix is to make the computation cooperative — an isInterrupted() check per unit of work — and to treat a loop without one as a bug.

"Why did suspend() and resume() have a deadlock by design, concretely?"

Because suspend() froze the target thread wherever it was, holding whatever monitors it held, with no way for anyone else to get those monitors until resume() was called.

Now suppose the thread that will call resume() first needs a lock the suspended thread holds — a common situation, since the resumer often needs to update shared state to decide whether to resume.

The resumer blocks on the lock, the suspended thread cannot release it because it is frozen, and the resume call never happens. Nothing in the API prevented this, and it was not a rare misuse; it was the ordinary use.

The replacement is state-based: a thread that should pause checks a flag and waits on a condition, releasing its locks, which is the pattern wait() was built for.

07 · java.util.concurrentExecutors, Locks & Concurrent Collections — Q181–Q220

This section drills the concurrency toolkit — the classes in java.util.concurrent that a senior engineer is expected to configure, compose, and debug from memory. Interviewers here are rarely testing whether you know a class exists; they are testing whether you can predict what it does under load, and whether you have been burned by its defaults. Every pool, lock, and collection below has a famous failure mode, and the questions are built around them.

Drill · Thread pools & the executor framework

These questions test whether you can predict what a pool actually does when traffic exceeds capacity — the submission algorithm, the queue, and the defaults that decide whether your service degrades gracefully or dies.

Q181. "Why do we use thread pools at all? What is actually wrong with creating a new thread per task?"

Reveal answer

The real test Whether you understand a pool as a resource-bounding device, not just a performance trick.

Strong answer A platform thread — the traditional Java thread backed one-to-one by an operating-system thread — is expensive twice over. Creating one is a native call that takes on the order of a millisecond, and each one reserves stack memory, about one megabyte by default.

If I create a thread per task, my thread count follows my request rate, which means an unbounded input directly creates unbounded memory use and an operating-system scheduler juggling thousands of runnable threads, and the service collapses exactly when it is busiest.

A thread pool — a fixed set of reusable worker threads pulling tasks from a queue — fixes both problems: creation cost is paid once, and concurrency is capped at a number I chose.

Just as importantly, the pool gives me one place to put a queue, a rejection policy, thread names, metrics, and shutdown logic.

Picture it The same traffic spike against thread-per-task and against a bounded pool, as thread counts, memory and pool state.

The setup: A service whose requests each hold a thread for 200 ms; traffic jumps from 500 to 5,000 requests per second.

thread per task versus poolruns offline
// ❌ TRAP: thread count follows request rate
void onRequest(Request r) { new Thread(() -> handle(r)).start(); }

// ✅ FIX: concurrency is capped at a number I chose, overflow is an explicit decision
private final ThreadPoolExecutor pool = new ThreadPoolExecutor(
        200, 200, 0, TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(500),
        new ThreadPoolExecutor.AbortPolicy());
void onRequest(Request r) { pool.execute(() -> handle(r)); }

Make the invisible visible: Little's law turns the request rate into the number of threads that thread-per-task would need.

arithmetic
threads in flight = arrival rate x time per request
normal: 500 req/s x 0.2 s =   100 threads x 1 MB stack reserved = 0.1 GB
spike : 5,000 req/s x 0.2 s = 1,000 threads x 1 MB              = 1 GB   + 1,000 x ~1 ms creation cost
pool  : core=max=200, queue=ArrayBlockingQueue(500) -> 200 threads x 1 MB = 0.2 GB at ANY request rate

The trace: The pool shows its state as the spike arrives.

pool state: core=200 max=200 queue=ArrayBlockingQueue(500)
moment          threads: N alive, queue: M waiting               rejected
normal  500/s   threads: 200 alive (about 100 busy), queue: 0    0 per s
spike  5,000/s  threads: 200 alive (all busy), queue: 500 (full)  about 4,000 per s   ✗ visible, handleable
Same spike, three designs
new Thread per taskfixed platform poolvirtual thread per task
Threads at 5,000 req/s1,0002001,000
Stack memoryabout 1 GB reservedabout 0.2 GB reservedheap objects, no 1 MB stack
Calls hitting the database1,000 at onceat most 2001,000 at once unless a Semaphore bounds them
Overload signalnone, until memory or the scheduler gives outRejectedExecutionExceptionnone unless you add a bound

Going deeper The senior nuance as of Aug 2026 is that virtual threads changed the "why".

A virtual thread is a lightweight thread scheduled by the JVM onto a small pool of carrier threads; it costs a few hundred bytes of heap instead of a megabyte of reserved stack, and creating one is a plain object allocation.

So Executors.newVirtualThreadPerTaskExecutor() really does create a thread per task, and that is the recommended pattern for blocking IO on JDK 21 and later.

What survives from the old argument is the bounding half: virtual threads remove the cost of threads, but they do not remove the need to bound concurrency against the things behind the threads, such as a database connection pool of 20 or a downstream that handles 500 requests per second.

With virtual threads that bound moves out of the thread pool and into a Semaphore or a rate limiter around the scarce resource.

So my honest answer today is: pool platform threads because they are expensive; do not pool virtual threads, but still bound the work they do.

Land it The deep reason for a pool is not speed — it is turning unbounded demand into bounded resource use with an explicit overflow policy.

Likely follow-ups
"Where does that one megabyte per thread actually come from, and can I change it?"

It is the thread's stack reservation, controlled by the -Xss flag, or per thread through the Thread constructor that takes a stack size.

On 64-bit Linux the default is 1 MB. The important detail is that it is reserved virtual address space, not committed memory: the operating system only backs the pages the thread actually touches, so a thread with a shallow stack may use 50 KB of real memory.

What still hurts is the count. Ten thousand threads reserve 10 GB of address space, the kernel scheduler has ten thousand runnable entities to juggle, and each context switch costs a few microseconds.

So I can lower -Xss to 256k for a thread-heavy service, but I would rather fix the design than tune the stack, because a deep recursion in a 256k stack fails with StackOverflowError in production.

"So with virtual threads on JDK 21, do thread pools become obsolete?"

Pools of virtual threads become pointless, but bounding does not. As of Aug 2026 the JDK guidance is explicit: never pool virtual threads, because they are cheap to create and pooling them just caps concurrency for no memory benefit.

But the thread was never the only scarce resource. If ten thousand virtual threads all borrow from a HikariCP pool of 20 connections, 9,980 of them queue on the pool and time out, which is the same overload with a different stack trace.

So I keep bounds where the scarcity really is: a Semaphore with 200 permits around a downstream call, the connection pool's own connectionTimeout, and a rate limiter at intake.

The thread pool used to bound all of that as a side effect; with virtual threads I have to bound each resource on purpose.

"What is the actual cost of a context switch, and when does it dominate?"

A context switch between platform threads costs roughly one to five microseconds of kernel time, plus the indirect cost of cold CPU caches when the new thread's data is not in L1 or L2, which can be worse than the switch itself.

It dominates when threads are far more numerous than cores and mostly runnable rather than blocked.

A CPU-bound service with 8 cores and 800 runnable threads spends a visible fraction of its time switching, and you see it in vmstat as a high context-switch column and high system CPU. When threads are mostly parked waiting for IO, the switches are rare and the cost is negligible, which is why an IO-bound pool can safely be ten times the core count.

The verification is simple: compare user CPU against system CPU in top; if system time is climbing with thread count, switching is the tax.

"How would you prove in production that thread creation, not the work itself, is the bottleneck?"

Three pieces of evidence. First, a JFR recording, which is Java Flight Recorder, the built-in low-overhead profiler: the jdk.ThreadStart event count per second tells me how many threads I am creating, and if it tracks request rate one-to-one, I am creating a thread per request.

Second, a thread dump or jcmd <pid> Thread.print showing thousands of threads with generic names like Thread-8123, which means nobody owns them. Third, memory: the JVM's native memory tracking, enabled with -XX:NativeMemoryTracking=summary and read with jcmd <pid> VM.native_memory, shows the Thread category growing with load.

If those three line up, and the fix of a bounded pool flattens both the thread count and the latency, the case is proven.

Q182. "Walk me through exactly what happens, step by step, when I submit a task to a ThreadPoolExecutor."

Reveal answer

The real test Almost everyone gets the order wrong — the pool grows only when the queue is full, and interviewers know it.

Strong answer The submission algorithm has a fixed order:

  1. If fewer than corePoolSize threads are running, the executor starts a brand-new worker for this task — even if existing workers are idle.
  2. Once the core is full, the task is offered to the work queue. If the queue accepts it, the task waits there.
  3. Only if the queue refuses the task — meaning the queue is full — does the executor create extra threads, up to maximumPoolSize.
  4. If the pool is already at maximum and the queue is full, the task goes to the RejectedExecutionHandler.

The counterintuitive part is step three: the pool does not grow because workers are busy; it grows because the queue is full. With an unbounded queue, step three can never happen, so maximumPoolSize is decorative.

what ThreadPoolExecutor does with a submitted taskruns offline
new ThreadPoolExecutor(core, max, keepAlive, unit, queue, threadFactory, handler);

// execute(task) follows this order, and the order is the part people get wrong:
//
// 1. If poolSize < corePoolSize      -> START A NEW THREAD, even if others are idle.
// 2. Else, TRY TO QUEUE the task.
// 3. Only if the QUEUE IS FULL       -> start a new thread, up to maximumPoolSize.
// 4. If the queue is full AND poolSize == max -> REJECT via the handler.

// THE CONSEQUENCE THAT SURPRISES EVERYONE (Q183):
new ThreadPoolExecutor(10, 200, 60, SECONDS, new LinkedBlockingQueue<>());
// LinkedBlockingQueue with no capacity argument is UNBOUNDED. It is therefore
// never full, so step 3 is unreachable and the pool NEVER GROWS PAST 10.
// maximumPoolSize=200 is dead configuration, and the queue grows until OOM.

// FIX — a bounded queue is what makes max meaningful.
new ThreadPoolExecutor(10, 200, 60, SECONDS,
        new ArrayBlockingQueue<>(500),
        new ThreadFactoryBuilder().setNameFormat("orders-%d").build(),   // NAME them
        new ThreadPoolExecutor.CallerRunsPolicy());

// Executors.newFixedThreadPool(n) has exactly the unbounded-queue problem;
// Executors.newCachedThreadPool() has max = Integer.MAX_VALUE with a
// SynchronousQueue, so it creates an unbounded number of THREADS instead.
// Both are why the guidance is to construct ThreadPoolExecutor directly.

The queue-before-growth order is the whole answer. Most people assume the pool grows to max and then queues; it queues first, which makes an unbounded queue silently cap the pool at corePoolSize and turn a thread-pool problem into a heap problem.

Picture it A small pool shown as state after every submission, so you can see the exact task where a thread is created, where a task queues, and where it is rejected.

The setup: A pool with two core threads, a maximum of four, and a queue that holds two; every task blocks and never finishes during the experiment.

pool for the walk-throughruns offline
ThreadPoolExecutor pool = new ThreadPoolExecutor(
        2, 4, 60, TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(2),                       // holds at most 2 waiting tasks
        new ThreadPoolExecutor.AbortPolicy());
CountDownLatch never = new CountDownLatch(1);              // tasks wait on this, so no worker frees up
for (int i = 1; i <= 7; i++) pool.execute(() -> never.await());   // task i

The trace: After each submit, the state is shown as threads running and tasks waiting in the queue.

pool state: core=2 max=4 queue=ArrayBlockingQueue(2)
submit   threads: N running, queue: M waiting   what the executor did
task 1   threads: 1 running, queue: 0 waiting   poolSize 0 < core 2  -> NEW THREAD, runs task 1
task 2   threads: 2 running, queue: 0 waiting   poolSize 1 < core 2  -> NEW THREAD (even if worker-1 were idle)
task 3   threads: 2 running, queue: 1 waiting   core full -> queue.offer ✓ QUEUED
task 4   threads: 2 running, queue: 2 waiting   queue.offer ✓ QUEUED, queue is now full
task 5   threads: 3 running, queue: 2 waiting   offer ✗ (full), poolSize 2 < max 4 -> NEW THREAD runs task 5, NOT task 3
task 6   threads: 4 running, queue: 2 waiting   offer ✗, poolSize 3 < max 4 -> NEW THREAD, pool is at max
task 7   threads: 4 running, queue: 2 waiting   offer ✗, poolSize 4 == max -> REJECTED ✗ AbortPolicy throws

What you see: The seventh submit throws, and the pool getters agree with the table.

console
# illustrative output
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task ... rejected from
  java.util.concurrent.ThreadPoolExecutor@1b2c3d[Running, pool size = 4, active threads = 4, queued tasks = 2, completed tasks = 0]
largestPoolSize=4  queue=2

Why: The pool grows only when the queue refuses a task, so the queue type decides when step three can happen at all (Q183 shows the same tasks under three queues).

Land it The queue is consulted before the pool grows — so your choice of queue, not your maximum, decides how the pool behaves under load.

Likely follow-ups
"Why did the designers make the pool consult the queue before growing? It seems backwards."

Because the design treats core threads as the steady-state capacity and the extra threads as an emergency measure for when buffering has already failed.

The idea is that a short burst should be absorbed by the queue at no cost, and only a sustained overload that fills the queue justifies the expense of spinning up more threads. That logic is sound for a bounded queue of modest size.

It only feels backwards because the factory methods pair it with an unbounded queue, where the emergency can never be declared.

If I want the opposite behavior, threads first and queue second, I use a SynchronousQueue, which has no capacity, so every offer fails when no thread is waiting and the pool grows immediately up to maximum.

Tomcat's own executor subclasses the queue to prefer growing threads before queueing, precisely because the default order surprised people.

"What happens to a task submitted after shutdown(), and what does prestartAllCoreThreads do?"

After shutdown() the executor is in the SHUTDOWN state, and any new submission is routed straight to the rejection handler, which by default throws RejectedExecutionException. Tasks already in the queue still run to completion.

That is why I always call shutdown() only after intake has stopped, otherwise callers get exceptions during a deploy.

prestartAllCoreThreads() is the fix for a cold-start latency problem: normally core threads are created lazily, one per submission until the core is full, so the first few requests after a restart each pay thread creation.

Calling it at startup creates every core thread immediately, so the first request at peak traffic finds warm workers.

I use it in services where the first second after deploy matters, such as anything behind a load balancer that starts routing the instant the health check passes.

"How does the executor know a worker is idle, and when does it retire it?"

Each worker runs a loop that pulls the next task from the queue. Workers above core size do not block forever; they call queue.poll(keepAliveTime, unit), and if that returns null because nothing arrived in the keep-alive window, the worker exits and the thread dies.

Core workers call take(), which blocks indefinitely, unless allowCoreThreadTimeOut(true) is set, in which case they use the timed poll too. So idleness is not tracked with a separate timer; it falls out of the timed poll.

A practical consequence is that with a 60-second keep-alive and bursty traffic every 90 seconds, the pool grows and shrinks on every burst and pays thread creation each time; setting keep-alive to a few minutes, or raising core size, removes that churn.

"Does submit() behave differently from execute() when the task throws?"

Yes, and it matters for observability. execute(Runnable) runs the task directly on the worker, so an uncaught exception propagates out of the task, the worker thread dies, its UncaughtExceptionHandler logs it, and the pool replaces the thread. You at least see a stack trace.

submit() wraps the task in a FutureTask, which catches every Throwable and stores it in the future. Nothing is logged, the worker survives, and the exception only appears if someone calls get(). So a fire-and-forget submit() silently eats every failure.

execute versus submit when the task throws
pool.execute(() -> { throw new IllegalStateException("boom"); });
pool.submit (() -> { throw new IllegalStateException("boom"); });

// console:
Exception in thread "pool-1-thread-1" java.lang.IllegalStateException: boom      <- from execute(): worker dies, handler prints
    at Demo.lambda$main$0(Demo.java:5)
// submit(): nothing printed, worker survives; the exception sits in the Future until someone calls get()

My rule is: if I am not going to read the future, use execute(), or wrap the body in a try/catch that logs, so failures are visible either way.

Q183 · Scenario. "I configured a pool with core=10, max=200, and a LinkedBlockingQueue. Under heavy load the pool never has more than 10 threads and latency is terrible. Why?"

Reveal answer

Strong answer I would diagnose it in this order:

  1. First I check the queue construction. A LinkedBlockingQueue created with no capacity argument is unbounded — its capacity is Integer.MAX_VALUE, effectively infinite.
  2. Then I apply the submission algorithm: the pool only grows past core size when the queue rejects a task. An unbounded queue never rejects anything, so the growth step is unreachable. The maximum of 200 will never be used; the pool is permanently a 10-thread pool.
  3. That explains the latency: every task beyond what 10 threads can process sits in the queue, and the observed latency is mostly queue-wait time. I would confirm by logging executor.getQueue().size() — I expect it to be enormous and growing.

The fix has three parts:

  • Bound the queue. For example new LinkedBlockingQueue<>(500) or an ArrayBlockingQueue, and choose a rejection policy deliberately, because now rejection can actually happen.
  • Or prefer threads over queueing. A SynchronousQueue holds nothing and forces a handoff, so the pool grows instead.
  • Prevent a repeat. Put queue depth and active-thread count on a dashboard, because a silently filling queue is invisible in logs until users complain.

Picture it The exact pool from the question as state at successive moments, then the same eight tasks under three different queue types.

The setup: The misconfigured pool, with tasks that take about 100 ms and arrive at 3,000 per second.

the pool from the questionruns offline
ThreadPoolExecutor pool = new ThreadPoolExecutor(
        10, 200, 60, TimeUnit.SECONDS,
        new LinkedBlockingQueue<>());             // ❌ TRAP: no capacity argument => Integer.MAX_VALUE, offer() never fails
// drain rate = 10 threads / 0.1 s = 100 tasks per second;  arrival rate = 3,000 per second

The trace: Each row is a moment after the spike begins; the queue never refuses, so the pool never grows.

pool state: core=10 max=200 queue=LinkedBlockingQueue(unbounded)
moment    submitted  completed   threads: N running, queue: M waiting
t=0.00 s       10          0     threads: 10 running, queue: 0         first 10 tasks each start a NEW THREAD
t=0.01 s       40          0     threads: 10 running, queue: 30        core full -> offer ✓ ... max=200 is never consulted
t=1 s       3,000        100     threads: 10 running, queue: 2,890
t=10 s     30,000      1,000     threads: 10 running, queue: 28,990
t=60 s    180,000      6,000     threads: 10 running, queue: 173,990   the task arriving now waits 1,740 s (29 min) ✗
Same workload, core=2 max=4, tasks 1 to 8 arriving while every worker is busy
after taskLinkedBlockingQueue()ArrayBlockingQueue(2)SynchronousQueue
11 running, 0 waiting1 running, 0 waiting1 running, 0 waiting
22 running, 0 waiting2 running, 0 waiting2 running, 0 waiting
32 running, 1 waiting2 running, 1 waiting3 running, 0 waiting (new thread)
42 running, 2 waiting2 running, 2 waiting4 running, 0 waiting (at max)
52 running, 3 waiting3 running, 2 waiting (new thread)REJECTED
62 running, 4 waiting4 running, 2 waiting (at max)REJECTED
72 running, 5 waitingREJECTEDREJECTED
82 running, 6 waitingREJECTEDREJECTED

What you see: The pool getters confirm the pool never grew.

pool getters, 60 s into the spike
# illustrative output
poolSize=10  activeCount=10  queued=173990  largestPoolSize=10  completed=6000
                                                      ^ never above 10, although maximumPoolSize=200

Why: The queue is offered each task before the pool grows, and a queue that is never full never says no.

The fix: Bound the queue so growth and rejection can actually happen.

bounded queueruns offline
ThreadPoolExecutor pool = new ThreadPoolExecutor(
        10, 200, 60, TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(500),             // ✅ FIX: bounded => step 3 (grow) and step 4 (reject) are reachable
        new ThreadPoolExecutor.AbortPolicy());

What you see now: The same load now grows the pool to its ceiling, fills the queue, and sheds the excess visibly.

pool state: core=10 max=200 queue=ArrayBlockingQueue(500)
# illustrative output
moment    threads: N running, queue: M waiting
t=0.00 s  threads: 10 running, queue: 0
t=0.2 s   threads: 10 running, queue: 500 (full)          next tasks: offer ✗ -> NEW THREAD each
t=0.3 s   threads: 200 running, queue: 500 (full)         at max; capacity = 200 / 0.1 s = 2,000 per s
steady    threads: 200 running, queue: 500, rejected about 1,000 per s ✓ overload is visible now
poolSize=200  activeCount=200  queued=500  largestPoolSize=200

Land it An unbounded queue quietly converts a burst of traffic into unbounded latency — bounding the queue is what turns overload into a visible, handleable event.

Likely follow-ups
"You bounded the queue at 500, and now the service throws RejectedExecutionException at peak. Was that the wrong fix?"

No, that is the fix working: the overload that was previously hidden as latency is now visible as a rejection. The next decision is what the caller should experience.

For a web endpoint I catch the rejection and return 503 with a Retry-After header, so the client backs off and the load balancer can route elsewhere. If the callers can afford to slow down, CallerRunsPolicy converts the rejection into backpressure.

And I check the numbers: if rejections happen at a load the service should handle, the pool is undersized, so I size it with the wait-ratio formula and revisit.

The one thing I do not do is put the unbounded queue back, because that just reconverts a clear signal into a silent one.

"How do you choose the queue capacity number? Why 500 and not 50 or 50,000?"

From the latency budget, using Little's law. If the pool drains 200 tasks per second and the most queue wait I will tolerate is 250 milliseconds, the queue should hold about 200 times 0.25, which is 50 tasks.

A queue of 50,000 at that drain rate means the last task waits over four minutes, by which time its caller has long since timed out, so the pool is doing dead work.

I also check the memory side: 50,000 tasks each holding a 10 KB request body is 500 MB of heap. So the capacity is the smaller of what the latency budget allows and what memory allows, and it is usually surprisingly small.

I then confirm with a queue-depth metric under load test that the queue fills briefly on bursts and drains, rather than sitting full.

"What metrics would you export from the pool so this is caught before users complain?"

Five numbers from ThreadPoolExecutor's own getters: getActiveCount(), getPoolSize(), getQueue().size(), getCompletedTaskCount(), and a counter I increment in a custom rejection handler. With Micrometer, ExecutorServiceMetrics.monitor(registry, executor, "payment-pool") wires most of that up automatically.

The alert I actually page on is queue depth above, say, 50 percent of capacity for more than a minute, and any non-zero rejection rate.

I also record task queue-wait time by timestamping at submit and at start, because a growing wait time is the earliest signal, well before the queue is full.

Active count sitting at core size with queue depth climbing is exactly the signature of this scenario, and a dashboard shows it in one glance.

"Would a SynchronousQueue have been a better default here?"

It depends what I want under burst.

A SynchronousQueue makes the pool grow to 200 threads immediately when tasks arrive faster than 10 workers finish them, so latency stays low at the price of 200 platform threads and whatever they contend on downstream, and once 200 are busy the next task is rejected outright with no buffering at all.

That is right for latency-sensitive request handling where a short queue is preferable to a long wait. A small bounded queue is better for batch-like work where a brief wait is fine and I want a stable thread count.

The trap with SynchronousQueue is thread churn: threads above core die after keep-alive and are recreated on the next burst, so I set keep-alive to a minute or more and consider a higher core size.

Q184. "How do you actually size a thread pool? Give me numbers, not vibes."

Reveal answer

The real test Whether you can do the wait-ratio arithmetic out loud instead of saying "we'd load test it".

Strong answer It depends on what the threads spend their time doing.

  1. For CPU-bound work — work limited by the processor itself, like compression or scoring — more threads than cores just adds context switching. I size at roughly the core count from Runtime.getRuntime().availableProcessors(), maybe plus one.
  2. For IO-bound work — threads mostly waiting on input/output such as network or disk — the formula is threads ≈ cores × (1 + wait time / compute time). Worked example: on an 8-core box, if each request spends 5 ms computing and 45 ms waiting on a downstream call, that is 8 × (1 + 45/5) = 80 threads to keep all cores busy while most threads are parked waiting.
  3. As a sanity check I use Little's law in one line: concurrent requests in flight = arrival rate × time per request, so 1,000 requests per second at 80 ms each means about 80 in flight — my pool and everything behind it must cover that.

Then I decide two more things:

  • Idle behaviour. Threads above core size die after keepAliveTime idle, and allowCoreThreadTimeOut(true) lets even core threads retire, which suits bursty services that are idle most of the day.
  • The measured ratio. I load test, because the wait ratio in the formula is measured, not guessed.

Picture it The sizing arithmetic with real numbers on an 8-core box, and a table of what each thread count actually delivers.

Make the invisible visible: First the actors and their limits, then the arithmetic.

actors and limits
cores            Runtime.getRuntime().availableProcessors()   = 8   (or -XX:ActiveProcessorCount=N)
pool size        corePoolSize / maximumPoolSize                      (and queue capacity)
downstream       HikariCP maximumPoolSize (default 10), connectionTimeout (default 30000 ms)
task profile     compute = 5 ms CPU,  wait = 45 ms blocked on a downstream call  -> 50 ms per task
worked arithmetic
CPU-bound : threads = cores + 1                 = 8 + 1               = 9
I/O-bound : threads = cores x (1 + wait/compute) = 8 x (1 + 45/5)      = 80
throughput = threads / time per task            = 80 / 0.050 s        = 1,600 tasks/s
CPU busy   = throughput x compute / cores       = 1,600 x 0.005 / 8   = 100%
Little     : in flight = 1,000 req/s x 0.080 s  = 80   <- the pool and everything behind it must cover this
What each thread count delivers (8 cores, 5 ms compute, 45 ms wait unless stated)
Workload and threadsThroughputCPU busyVerdict
I/O, 8 threads8 / 0.05 = 160 per s10%Underused: 7 cores idle while threads wait
I/O, 80 threads1,600 per s100%Right size
I/O, 200 threadsstill about 1,600 per s100%120 extra threads add memory and queueing, no throughput
I/O, 80 threads, DB pool of 20, call = the 45 ms20 / 0.045 = about 444 per sabout 28%60 threads parked on the connection pool; size to 20 or grow the DB pool
I/O, 80 threads, downstream slows to 200 ms80 / 0.205 = about 390 per sabout 24%Ratio is now 40, ideal pool is 8 x 41 = 328
CPU-bound, 10 ms per task, 9 threadsabout 800 per s100%Right size
CPU-bound, 10 ms per task, 80 threadsabout 800 per s100%Each task now takes about 100 ms wall time instead of 10: pure switching overhead
Decision table
SymptomRoot causeAction
Low CPU, rising latency, queue growingPool smaller than the wait-ratio numberRaise threads toward cores x (1 + wait/compute), check the downstream can take it
High system CPU, many runnable threadsPool far larger than cores for CPU-bound workCut to cores + 1
Threads blocked on the connection poolPool larger than the narrowest resource behind itCap at the minimum of formula and downstream capacity

Land it The formula gets you a starting point; measuring the real wait-to-compute ratio under production-like load gets you the answer.

Likely follow-ups
"Your formula gave 80 threads, but the database pool only has 20 connections. Now what?"

Then 80 is wrong, because the thread count must not exceed the narrowest resource behind it.

If every task needs a connection, 60 of my 80 threads will block on HikariCP's pool waiting for a connection, and each will eventually hit connectionTimeout, which defaults to 30 seconds, and fail.

The honest sizing is the minimum of the wait-ratio number and the downstream capacity, so 20 here, or I raise the connection pool if the database can take it.

HikariCP's own guidance is that a pool of around core count times two plus spindle count saturates most databases, so 20 connections may already be right.

The senior move is to size the chain end to end: intake threads, worker threads, connection pool, and downstream rate limit, each no larger than the next one can serve.

"How do you measure the wait-to-compute ratio in production rather than guess it?"

Two measurements per task. Compute time is CPU time, read with ThreadMXBean.getCurrentThreadCpuTime() at the start and end of the task, or from a JFR recording's per-thread CPU samples. Wall time is a simple System.nanoTime() pair around the task.

Wait time is wall minus CPU. Averaged over a few thousand tasks at realistic load, that gives the ratio directly. In the example, 5 ms of CPU inside 50 ms of wall time is a ratio of 9.

I also watch how it changes under load, because a downstream that slows from 45 ms to 200 ms changes the ratio from 9 to 40, and a pool sized for 9 will then sit mostly idle.

That is the argument for pairing a fixed pool with a timeout on the downstream call, so the ratio stays bounded.

"Does availableProcessors() tell the truth inside a container?"

As of Aug 2026 it does, with a caveat. Since JDK 10 the JVM reads the cgroup CPU limits, so in a Kubernetes pod with a CPU limit of 2 it returns 2 even on a 64-core host.

The caveat is CPU requests versus limits: with a request of 500 millicores and no limit, the JVM may report the full host core count, size the common pool and garbage collector threads accordingly, and then get throttled.

So I either set an explicit CPU limit, or pin the number with -XX:ActiveProcessorCount=2.

I verify with jcmd <pid> VM.info or by logging availableProcessors() at startup, and I check the container's CPU throttling counter in cpu.stat under the cgroup directory, because heavy throttling means the JVM thinks it has more cores than it is allowed to use.

"With virtual threads, does this sizing exercise go away?"

The thread arithmetic goes away; the capacity arithmetic does not. With Executors.newVirtualThreadPerTaskExecutor() I never choose a thread count, because a blocked virtual thread unmounts from its carrier and costs almost nothing, so 10,000 concurrent IO-bound tasks run on a handful of carriers.

But Little's law still governs the resources behind them: 1,000 requests per second at 80 ms is still 80 in flight, still needing 80 connections or a queue in front of a pool of 20.

And one specific trap remains: a virtual thread that blocks inside a synchronized block pinned its carrier before JDK 24; from JDK 24 onward that pinning is gone, but native calls and some file IO still pin.

So on JDK 21 I check with -Djdk.tracePinnedThreads=full and replace hot synchronized with ReentrantLock where pinning shows up.

Q185. "Name the four built-in rejection policies. When is CallerRunsPolicy a feature, and when is it a trap?"

Reveal answer

Strong answer When the pool and queue are both full, the RejectedExecutionHandler decides the task's fate.

The four built-ins are:

  • AbortPolicy is the default and throws RejectedExecutionException, so the caller knows.
  • CallerRunsPolicy makes the submitting thread execute the task itself.
  • DiscardPolicy drops the task silently.
  • DiscardOldestPolicy drops the oldest queued task and retries.

CallerRunsPolicy is a feature when I want backpressure — pushing the slowdown back onto the producer — because a submitter busy running a task cannot submit more, so intake naturally throttles to what the system can absorb.

It is a trap when the submitting thread is itself a scarce acceptor: if a message-consumer poll loop or an event-loop thread gets stuck running a slow task, the entire intake pipeline stalls behind it. Silent discards, meanwhile, should never ship without a counter metric.

Picture it One full pool, one extra task, and what happens to that task and to the queued one under each of the four handlers.

The setup: One worker busy, one task queued, queue full, then task 3 arrives.

full pool, task 3 arrivesruns offline
ThreadPoolExecutor pool = new ThreadPoolExecutor(
        1, 1, 0, TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(1),
        new ThreadPoolExecutor.CallerRunsPolicy());     // swap this line for each policy in the table
CountDownLatch hold = new CountDownLatch(1);
pool.execute(() -> hold.await());                       // task 1: the single worker is busy
pool.execute(task2);                                    // task 2: queue now full
pool.execute(task3);                                    // task 3: the handler decides its fate

The trace: Same state, four different outcomes for task 3.

Task 3 under each policy
PolicyTask 3Queued task 2Who runs task 3What the caller sees
AbortPolicyrejectedstays queuednobodyRejectedExecutionException from execute
CallerRunsPolicyruns nowstays queuedthe submitting thread (for example main)execute returns only after task 3 finishes: intake pauses
DiscardPolicydropped silentlystays queuednobodynothing, and with submit its Future never completes
DiscardOldestPolicyqueued insteaddroppeda worker, laternothing, and task 2's Future never completes

What you see: With CallerRunsPolicy the task prints the submitter's thread name.

console
# illustrative output
task 3 ran on thread: main            <- the submitter did the work; it could not submit task 4 meanwhile

Land it CallerRuns is deliberate backpressure — brilliant when the caller can afford to slow down, dangerous when the caller is the one thread everything else depends on.

Likely follow-ups
"You said CallerRunsPolicy gives backpressure. Show me the failure where it does not."

The failure is when the caller is a thread that everyone shares. Take a Kafka consumer: one poll loop thread hands records to a worker pool. When the pool rejects and the poll thread runs the task itself, it stops polling for the duration.

If the task takes longer than max.poll.interval.ms, which defaults to five minutes, the broker decides the consumer is dead, triggers a rebalance, and the partition is reassigned while the original consumer is still processing, so records get handled twice.

consumer log when the poll thread runs the task
# illustrative output
WARN  pool-queue full, CallerRunsPolicy: task running on thread "kafka-poll-loop" (queue=500/500)
...  5 minutes pass with no poll() call ...
WARN  [Consumer clientId=c-1, groupId=g] consumer poll timeout has expired. The time between subsequent
      calls to poll() was longer than max.poll.interval.ms, which typically implies that the poll loop
      is spending too much time processing messages.
INFO  rebalance: partition 7 reassigned to c-2       <- records still being processed here are handled twice

The same shape happens on a Netty event loop or a Tomcat acceptor thread. So the rule is: CallerRunsPolicy only when the submitting thread is itself a disposable worker, such as one request thread among two hundred, never when it is a singleton loop.

"When would you write a custom RejectedExecutionHandler instead of using a built-in?"

Almost always in production, because none of the built-ins emits a metric. My usual handler increments a counter, logs the pool name and queue size at a rate-limited level, and then delegates to whichever built-in behavior I want.

A second common custom handler is a bounded blocking submit: instead of rejecting, it calls executor.getQueue().offer(task, 200, MILLISECONDS) and only throws if that times out, which gives a short grace period before shedding load.

A third is priority-aware shedding, which drops the task if it carries a low-priority marker and otherwise falls back to caller-runs.

The handler is only a few lines, and it is the one place where overload becomes visible, so I treat it as a required piece of every pool, not an afterthought.

"Is DiscardOldestPolicy ever the right choice?"

Rarely, and only when the queue holds items that are superseded by newer ones.

A good example is a metrics or telemetry pipeline where each queued item is a snapshot of the same gauge; dropping the oldest snapshot to make room for the newest is exactly what you want, because the oldest is the least useful.

It is wrong whenever every task matters individually, such as orders or emails, and it is particularly nasty with submit(), because the dropped task's Future is never completed, so a caller waiting on get() without a timeout hangs forever.

Even in the telemetry case I would pair it with a discard counter, because a steadily rising discard rate means the pipeline is undersized rather than merely bursty.

"How would you test that your rejection policy actually behaves under overload?"

With a deterministic unit test, not a load test.

I build a ThreadPoolExecutor with core one, max one, and an ArrayBlockingQueue of size one, submit one task that blocks on a CountDownLatch so the single worker is busy, submit a second that fills the queue, and then submit a third.

With AbortPolicy I assert RejectedExecutionException; with a custom handler I assert the counter incremented and the fallback ran on the calling thread. Then I release the latch and assert the queued task completes. That test takes milliseconds and pins down the exact behavior.

Separately, in staging I run a load test at 150 percent of rated capacity and check the rejection metric rises while p99 latency stays bounded, which proves the policy sheds rather than queues.

Q186 · Scenario. "A service built on Executors.newFixedThreadPool(50) died with OutOfMemoryError during a traffic spike, and the heap dump is full of queued Runnables. What happened, and what do you change?"

Reveal answer

Strong answer This is the classic hidden-default failure of the Executors factory methods.

  1. The heap dump confirms the mechanism: millions of task objects held by LinkedBlockingQueue nodes. newFixedThreadPool(50) is 50 threads in front of an unbounded queue.
  2. During the spike, producers submitted faster than 50 workers could drain. Every excess task was accepted into the queue, nothing was ever rejected, so there was no error signal — the queue simply grew until the heap was exhausted, and the whole process died instead of shedding load. OOM here stands for out of memory.
  3. I would also flag the sibling trap while I am there: newCachedThreadPool has the opposite defaults — a zero-capacity handoff queue and a maximum of Integer.MAX_VALUE threads — so under the same spike it creates threads without limit until stack memory or the scheduler gives out.

The fix is to construct ThreadPoolExecutor explicitly, with five decisions spelled out:

  • Sizes. A deliberate core and maximum.
  • Queue. Bounded, sized from the memory budget and the acceptable wait.
  • Rejection policy. Chosen on purpose.
  • Thread names. A custom ThreadFactory that names threads something like payment-worker-3, because at 3am the thread dump that says pool-7-thread-12 tells you nothing about which pool is drowning.
  • Prevention. Queue-depth and rejection-count metrics with alerts, and a load test that pushes past capacity on purpose.

Picture it What the two factory methods really construct, the heap growing during the spike, and the heap-dump evidence.

The setup: A fixed pool of 50 threads whose tasks take 250 ms, hit by 1,000 tasks per second with about 20 KB of request data each.

the factory callruns offline
ExecutorService pool = Executors.newFixedThreadPool(50);       // ❌ TRAP: reads like a limit, hides an unbounded queue
for (Request r : incoming) pool.execute(new ChargeTask(r));    // each ChargeTask holds ~20 KB

Make the invisible visible: The factories are one-line constructors; here is what they expand to.

what the factories generateruns offline
// Executors.newFixedThreadPool(n)
new ThreadPoolExecutor(n, n, 0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>());           // unbounded: offer() never fails, nothing is rejected

// Executors.newCachedThreadPool()
new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
        new SynchronousQueue<Runnable>());              // no queue, but threads without limit

The trace: Drain is 50 / 0.25 s = 200 tasks per second against 1,000 arriving, so the queue gains 800 tasks (about 16 MB) every second on a 2 GB heap.

pool state: core=50 max=50 queue=LinkedBlockingQueue(unbounded), -Xmx2g
moment     threads: N running, queue: M waiting     heap held by queued tasks
t=10 s     threads: 50 running, queue: 8,000          about 160 MB
t=60 s     threads: 50 running, queue: 48,000         about 0.96 GB
t=120 s    threads: 50 running, queue: 96,000         about 1.9 GB    GC runs back to back, frees almost nothing
t=125 s    OutOfMemoryError ✗                         nothing was ever rejected, so there was no signal before this

What you see: The heap dump's dominator tree is one queue, and the log ends in the OOM.

heap dump (MAT dominator tree) and log
# illustrative output
Class Name                                                  Retained Heap
java.util.concurrent.LinkedBlockingQueue @ 0x7a1f4c000      1.9 GB   (95%)
 `- LinkedBlockingQueue$Node x 96,412                        each -> ChargeTask -> Request (~20 KB)
Exception in thread "http-nio-8080-exec-41" java.lang.OutOfMemoryError: Java heap space

Why: Fifty busy workers refuse nothing, because an unbounded queue accepts every task until the heap is gone.

The fix: Spell out the constructor: bounded queue, deliberate policy, named threads.

explicit poolruns offline
ThreadPoolExecutor pool = new ThreadPoolExecutor(
        50, 50, 0, TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(500),                          // ✅ FIX: 500 x 20 KB = 10 MB worst case
        r -> new Thread(r, "payment-worker-" + counter.incrementAndGet()),
        new ThreadPoolExecutor.AbortPolicy());                  // ✅ FIX: overload becomes an exception you handle

What you see now: The queue plateaus at its bound, the excess is rejected and counted, and the heap stays flat.

pool state: core=50 max=50 queue=ArrayBlockingQueue(500)
# illustrative output
moment     threads: N running, queue: M waiting     rejected      heap held by queued tasks
t=10 s     threads: 50 running, queue: 500 (full)    7,500        10 MB
t=60 s     threads: 50 running, queue: 500 (full)    37,500       10 MB      <- flat, no OutOfMemoryError

Land it The Executors factories hide the two numbers that decide survival under overload — queue bound and maximum threads — so for production pools I always spell out the full constructor.

Likely follow-ups
"You bounded the queue and added a rejection policy, but the service still ran out of memory. What do you look at next?"

Then the queue was not the only unbounded thing. I open the heap dump in Eclipse MAT and read the dominator tree, which shows which objects retain the most memory.

The usual suspects after the queue are: the tasks themselves each holding a large request body or a full entity graph, so 500 queued tasks times 10 MB is still 5 GB; a List<Future> that the submitter keeps and never clears, so completed futures retain their results; or a per-task ThreadLocal that workers never remove, which accumulates across the pool's lifetime.

I would also check whether the load itself moved elsewhere, such as into HTTP client buffers or an unbounded Netty write queue. The principle is the same: find the collection whose size tracks request rate, and bound it.

"Why does Executors.newCachedThreadPool exist at all if it is so dangerous?"

It was designed for many short-lived, bursty, non-blocking tasks where the number in flight is naturally small, such as handing off tiny callbacks, and in that setting it works: threads are reused when free and retire after 60 seconds idle.

The danger is purely that nothing caps it, so any workload where tasks block or arrive faster than they finish grows threads without limit.

In practice I never use it in a service; if I want the cached behavior, I build a ThreadPoolExecutor with a SynchronousQueue and an explicit maximum, which is the same thing with a ceiling.

And as of Aug 2026, for the use case it was meant for, Executors.newVirtualThreadPerTaskExecutor() is the better answer, because unbounded virtual threads cost bytes rather than megabytes.

"How do you name and size pools so a 3am thread dump is readable?"

With a ThreadFactory that names threads by purpose and instance, such as payment-worker-3, and sets them as daemon or not on purpose. A short lambda does it: wrap Executors.defaultThreadFactory(), call newThread, then setName(prefix + counter.incrementAndGet()).

I also set an UncaughtExceptionHandler in the factory so a dying worker logs which pool it belonged to. In Spring, ThreadPoolTaskExecutor.setThreadNamePrefix("payment-") does the same.

The payoff in a thread dump is immediate: I can count how many payment-worker threads are blocked in socket reads versus how many notify-worker threads are idle, and know which pool is drowning without reading a single stack frame.

"How would you reproduce this failure in a load test before it happens in production?"

By deliberately pushing past capacity and watching the heap. I configure the test to send 3x the rated throughput for five minutes, with the downstream stubbed to add 200 ms of latency so the workers drain slowly.

I watch three graphs: queue depth, old-generation heap after each GC, and rejection count. With the old configuration, queue depth climbs linearly and old-gen never comes back down after collections, which is the leak signature; the process dies or GC pauses balloon within minutes.

With the fixed configuration, queue depth plateaus at capacity, rejections rise, and heap stays flat. I make that a pass/fail gate: heap after GC must stay under some threshold during overload.

This is the one load test I insist on, because the happy-path load test never exercises the queue.

Q187. "How do you shut down an executor cleanly? What is the difference between shutdown and shutdownNow?"

Reveal answer

Strong answer The clean sequence has three parts in a fixed order:

  1. shutdown() is the polite one: the executor stops accepting new tasks, but everything already running or queued is allowed to finish.
  2. awaitTermination(timeout, unit) blocks for a bounded time waiting for that drain to complete. Without this step, shutdown is a fire-and-forget hope.
  3. shutdownNow() is the escalation if the timeout expires. It interrupts every worker thread and returns the list of tasks that never started, which I can log or persist for replay. Then I wait briefly once more.

The crucial honesty point is that shutdownNow() only interrupts. Interruption is cooperative, so a task that ignores its interrupt flag will keep running regardless.

In a service, I wire this sequence into the container's lifecycle hook so deploys drain in-flight work instead of dropping it.

Picture it The pool's lifecycle state, its workers and its queue at each step of the shutdown ladder, including the task that ignores the interrupt.

The setup: Four workers, six tasks waiting, and one task that swallows interrupts.

the shutdown ladderruns offline
pool.shutdown();                                           // 1. stop intake, let the queue drain
try {
    if (!pool.awaitTermination(20, TimeUnit.SECONDS)) {    // 2. bounded wait
        List<Runnable> neverStarted = pool.shutdownNow();  // 3. interrupt workers, take back the queue
        log.warn("{} tasks never started", neverStarted.size());
        if (!pool.awaitTermination(5, TimeUnit.SECONDS))
            log.error("pool did not terminate: some task ignores interrupts");   // ❌ cooperative: cannot force it
    }
} catch (InterruptedException e) {
    pool.shutdownNow();
    Thread.currentThread().interrupt();
}

The trace: Lifecycle states are RUNNING, SHUTDOWN, STOP, TIDYING and TERMINATED.

pool state during shutdown (4 workers, 6 queued)
moment                state       threads: N running, queue: M waiting     new submit()
before                RUNNING     threads: 4 running, queue: 6 waiting      accepted
shutdown()            SHUTDOWN    threads: 4 running, queue: 6 waiting      RejectedExecutionException ✗ (by design)
t=12 s                SHUTDOWN    threads: 4 running, queue: 0 waiting      queue drained ✓ running tasks continue
t=20 s timeout        SHUTDOWN    threads: 1 running, queue: 0 waiting      one task is still running
shutdownNow()         STOP        workers interrupted, queue emptied        the task honours it ✓ or ignores it ✗
all workers gone      TIDYING -> TERMINATED  threads: 0                     awaitTermination returns true

What you see: The log shows which rung finished the job, and a thread dump names a task that ignored the interrupt.

shutdown log
# illustrative output
INFO  shutdown() called, 6 queued
WARN  awaitTermination(20 s) timed out, calling shutdownNow(), 0 tasks never started
ERROR pool did not terminate: some task ignores interrupts
"payment-worker-3" ... java.lang.Thread.State: RUNNABLE      <- still inside a loop that never checks the flag

Why: shutdownNow() only sets interrupt flags and cannot stop code that never looks at them.

Land it shutdown then awaitTermination then shutdownNow is the standard ladder — and shutdownNow is only as forceful as your tasks' willingness to honor interruption.

Likely follow-ups
"How does this fit into a Kubernetes rolling deploy end to end?"

The sequence is: Kubernetes sends SIGTERM, then waits up to terminationGracePeriodSeconds, which defaults to 30 seconds, before SIGKILL. In Spring Boot I set server.shutdown=graceful and spring.lifecycle.timeout-per-shutdown-phase=20s, so on SIGTERM the web server stops accepting new connections, in-flight requests finish, and then my @PreDestroy or SmartLifecycle.stop() runs the executor ladder with a budget that fits inside the remaining grace period.

Two gotchas matter. First, the readiness probe must fail before or at SIGTERM, otherwise the load balancer keeps sending traffic to a pod that is refusing it; a preStop hook with a few seconds of sleep gives the endpoints controller time to catch up.

Second, the sum of all shutdown phases must be under the grace period, or SIGKILL drops whatever is left.

grace-period budget (illustrative numbers)
terminationGracePeriodSeconds                      30 s
  preStop hook (fail readiness, let endpoints catch up)  -  5 s
  spring.lifecycle.timeout-per-shutdown-phase            - 20 s   <- web drain + executor ladder fit in here
  slack before SIGKILL                                   =  5 s
sum of phases must stay under 30 s, or SIGKILL drops whatever is left ✗
"What happens to the tasks that shutdownNow returns, and what do you do with them?"

They are the runnables still sitting in the queue that never started; running tasks are not in that list, they are simply interrupted.

If the work is idempotent and durable somewhere else, such as messages that will be redelivered by the broker, I log the count and let redelivery handle it.

If the tasks are the only record of the work, I need them persisted before the process exits: serialize an identifier for each to a database table or an outbox, and replay on startup.

The design point is that a task should carry enough identity to be replayed, so I queue a command object with an ID, not an anonymous lambda capturing half the request.

If I find myself unable to describe a queued task in a log line, it is not safe to shut down under.

"What if awaitTermination keeps timing out because one task never finishes?"

First I find out which task, with a thread dump during the drain: the worker that is still running shows its stack, and that tells me whether it is blocked in an uninterruptible call such as a socket read without a timeout, or spinning in a loop that never checks the interrupt flag.

The fix is in the task: give the blocking call a timeout, or have the loop check Thread.currentThread().isInterrupted(). For the immediate deploy, the process will be SIGKILLed after the grace period anyway, so the honest question is whether that task's partial work is safe to abandon.

If not, that is a bug regardless of shutdown; the work must be transactional or idempotent. I would also make the executor threads daemon threads, so a stuck worker cannot keep the JVM alive after main has exited.

"Does close() on ExecutorService change any of this in newer JDKs?"

Since JDK 19, ExecutorService extends AutoCloseable, and its default close() calls shutdown() and then waits, effectively forever, for termination, re-interrupting and calling shutdownNow() only if the waiting thread itself is interrupted.

So try-with-resources on an executor is convenient for short-lived, task-scoped executors, especially newVirtualThreadPerTaskExecutor(), where the block does not exit until every task is done.

It is not a replacement for the ladder in a long-lived service, because the wait is unbounded and a stuck task blocks shutdown indefinitely.

In a service I still write the three-step sequence with an explicit timeout; in a batch job or a fan-out helper, I use try-with-resources and enjoy the guarantee that nothing leaks out of the block.

Q188 · Scenario. "A ScheduledExecutorService job that runs every minute silently stopped a week ago. There are no errors anywhere in the logs. What happened, and how do you fix it?"

Reveal answer

Strong answer This is the most famous sharp edge of scheduleAtFixedRate and scheduleWithFixedDelay.

  1. The contract says: if any execution of the task throws an exception, all subsequent executions are suppressed — the periodic task is cancelled permanently.
  2. The reason nothing was logged is that the exception is not thrown anywhere visible; it is captured inside the returned ScheduledFuture, and it only surfaces if someone calls get() on that future — which nobody does for a periodic job. So one bad run a week ago, perhaps a transient network failure, killed the schedule silently.
  3. To confirm, I would take a thread dump: the scheduler thread is alive and idle, and the task simply is not in its queue anymore.

The fix is to make the task incapable of throwing: wrap the entire body in try { work(); } catch (Throwable t) { log.error("job failed", t); }, so a failed run is logged and the schedule survives. I usually extract that into a reusable safe-runnable wrapper so no one forgets.

Prevention is the more senior point: monitor the job's last successful run timestamp and alert when it goes stale, because "absence of errors" is exactly what this failure mode looks like.

Picture it A schedule that dies on run 3, what the future and the thread dump show afterwards, and the same job with the safe wrapper.

The setup: A job scheduled every minute whose third run hits a transient failure.

scheduled jobruns offline
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> handle = ses.scheduleWithFixedDelay(() -> {
    syncOrders();                       // ❌ TRAP: run 3 throws IllegalStateException("db timeout")
}, 0, 1, TimeUnit.MINUTES);             // nobody ever calls handle.get()

The trace: The exception is stored in the ScheduledFuture and the task is not rescheduled.

run timeline
run  time    outcome                              next run scheduled?
1    10:00   ✓ ok                                 yes, 10:01
2    10:01   ✓ ok                                 yes, 10:02
3    10:02   ✗ IllegalStateException("db timeout") stored inside the ScheduledFuture; NO next run, NO log line
4    10:03   - never happens                       the future is "done"
...  a week passes in silence

What you see: The log simply stops, the future reports done, and the scheduler thread is idle.

log, future and thread dump
# illustrative output
10:00 sync ok     10:01 sync ok                  <- last line, then nothing for a week
handle.isDone()  = true                          <- a live periodic task would say false
handle.get()     -> java.util.concurrent.ExecutionException: java.lang.IllegalStateException: db timeout
"pool-1-thread-1" ... java.lang.Thread.State: WAITING (parking)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(...)   <- empty queue, task is gone

Why: The contract says a periodic task that throws is suppressed from all later executions.

The fix: Make the task incapable of throwing, and alert on a stale success timestamp.

safe wrapperruns offline
static Runnable safe(String name, Runnable body, AtomicLong lastSuccess) {
    return () -> {
        try { body.run(); lastSuccess.set(System.currentTimeMillis()); }
        catch (Throwable t) { log.error("job {} failed", name, t); }   // ✅ FIX: the schedule survives
    };
}
ses.scheduleWithFixedDelay(safe("orders", this::syncOrders, lastSuccess), 0, 1, TimeUnit.MINUTES);

What you see now: Run 3 is logged with its stack trace and run 4 happens.

log
# illustrative output
10:01 sync ok
10:02 ERROR job orders failed: java.lang.IllegalStateException: db timeout
    at Jobs.syncOrders(Jobs.java:31) ...
10:03 sync ok                                    <- schedule survived; alert fires if lastSuccess is older than 3 minutes

Land it One uncaught exception cancels a periodic task forever and tells no one — so periodic tasks must swallow-and-log, and monitoring must watch for missing successes, not just present errors.

Likely follow-ups
"You wrapped the body in try/catch Throwable, but catching an Error like OutOfMemoryError seems wrong. Is it?"

It is a fair concern, and the answer is that I catch Throwable to keep the schedule alive but I do not pretend the process is healthy. For Exception subclasses I log and continue.

For Error subclasses I log, and for the specific case of OutOfMemoryError or StackOverflowError I let the platform handle it, typically by running with -XX:+ExitOnOutOfMemoryError so the orchestrator restarts the container rather than letting a half-broken JVM limp on.

So the wrapper is: catch Exception, log, continue; catch Error, log, rethrow. Rethrowing kills the schedule, but a JVM that has hit an OOM should be restarted anyway, and the missing-success alert will fire if it is not.

"The task did not throw; it just hung. How is that different, and how do you handle it?"

It looks identical from outside, no runs and no errors, but the mechanism is different: scheduleAtFixedRate never overlaps executions, so if one run blocks forever, every subsequent run queues behind it and none ever start.

A thread dump distinguishes the two cases: for an exception, the scheduler thread is idle and the task is gone from the queue; for a hang, the scheduler thread is inside my task, blocked on a socket or a lock.

thread dump: exception versus hang
# illustrative output
exception: "pool-1-thread-1" WAITING (parking) at DelayedWorkQueue.take      <- scheduler idle, task gone from queue
hang:      "pool-1-thread-1" RUNNABLE at java.net.SocketInputStream.socketRead0 / Jobs.syncOrders   <- inside my task, later runs queue behind it

The fix is a per-run deadline: run the real work on a separate executor and future.get(timeout) from the scheduled task, cancelling on timeout, or put timeouts on every blocking call the job makes. Either way, the last-success-timestamp alert catches both cases with the same rule.

"Fixed rate or fixed delay for this job, and why?"

Fixed delay for anything that touches a shared resource.

scheduleAtFixedRate(task, 0, 1, MINUTES) tries to start a run every minute on the clock; if a run takes 90 seconds, the next one starts immediately after, and the scheduler tries to catch up on missed slots, so a slow dependency turns into back-to-back hammering.

scheduleWithFixedDelay waits one minute after each run finishes, so a slow run naturally spaces the next one out, which is gentler on the database or downstream. Fixed rate is right when the cadence itself matters, such as emitting a metric every 10 seconds.

For a job like "sync orders every minute" I choose fixed delay, and I add jitter across instances so 30 pods do not all sync at the same second.

"In a Spring application, does @Scheduled have the same problem?"

No, and that is a good reason to prefer it. Spring's @Scheduled wraps each run in a DelegatingErrorHandlingRunnable that catches the exception, logs it through the configured ErrorHandler, and keeps the schedule alive, so a single failure does not cancel the job.

What Spring does share with the raw scheduler is the single-thread default: as of Aug 2026 the default TaskScheduler has a pool size of one unless spring.task.scheduling.pool.size is raised, so one slow job delays every other scheduled job in the application.

I set the pool size to the number of jobs that may overlap, and for multi-instance deployments I add ShedLock or a database lock so a job runs on exactly one pod per tick.

Drill · Futures & CompletableFuture

This group tests whether you know which thread runs each stage of an async pipeline, and what actually happens when a stage fails, blocks, or times out.

Q189. "What are the limitations of plain Future, and what does CompletableFuture add?"

Reveal answer

Strong answer A Future is only a claim ticket for a result.

Plain Future has four gaps:

  • Blocking. get() blocks the calling thread, which defeats the point of going asynchronous.
  • No callbacks. There is no way to attach code for when it completes.
  • No composition. I cannot say "when this finishes, feed it into that" or "combine these two results" without a thread parked on get().
  • Clumsy errors. Failures arrive as an ExecutionException wrapper at the get() call site.

CompletableFuture adds all of the missing pieces:

  • Callbacks: non-blocking thenApply and thenAccept.
  • Chaining: dependent async steps with thenCompose.
  • Combining: thenCombine, plus fan-out with allOf and anyOf.
  • Failure handling: built-in timeouts and an exception pipeline.
  • Manual completion: complete(), which lets me bridge callback-based libraries into the futures world.

Picture it One task, fetch the user, then their orders, then combine with their loyalty points, written both ways, with a thread timeline for each and a table of outcomes.

The setup: Task: fetch the user (50 ms), then that user's orders (80 ms, needs the user), while fetching loyalty points (60 ms) in parallel, then combine orders and points into a summary. Version 1 uses Future.

shared task with Futureruns offline
ExecutorService pool = Executors.newFixedThreadPool(4);          // threads: pool-1-thread-1 .. 4

Summary summary(long id) throws Exception {                      // runs on the request thread
    Future<Integer> pointsF = pool.submit(() -> loyalty.points(id));      // 60 ms
    Future<User>    userF   = pool.submit(() -> userClient.fetch(id));    // 50 ms
    User user = userF.get();                                      // ❌ request thread BLOCKS here
    Future<List<Order>> ordersF = pool.submit(() -> orderClient.forUser(user.id()));   // 80 ms
    List<Order> orders = ordersF.get();                           // ❌ BLOCKS again
    return new Summary(orders, pointsF.get());                    // combine on the request thread
}

The setup: Version 2: the same task with CompletableFuture, on an explicit I/O pool.

shared task with CompletableFutureruns offline
ExecutorService ioPool = Executors.newFixedThreadPool(4, namedFactory("io-pool"));

CompletableFuture<Summary> summary(long id) {                    // returns at once
    CompletableFuture<Integer> points =
        CompletableFuture.supplyAsync(() -> loyalty.points(id), ioPool);             // 60 ms
    return CompletableFuture.supplyAsync(() -> userClient.fetch(id), ioPool)         // stage 1, 50 ms
        .thenCompose(user -> CompletableFuture.supplyAsync(
                () -> orderClient.forUser(user.id()), ioPool))                       // stage 2, 80 ms
        .thenCombine(points, (orders, pts) -> new Summary(orders, pts))              // stage 3
        .orTimeout(2, TimeUnit.SECONDS)
        .exceptionally(ex -> Summary.degraded());
}

Make the invisible visible: Which thread blocks, and which thread runs each step, drawn as columns over time.

thread timeline, Future version (ms)
time   request thread (http-exec-1)      pool-1-thread-1      pool-1-thread-2      pool-1-thread-3
0      submit(points), submit(user)      fetchPoints ......   fetchUser ....
0      userF.get()  BLOCKED ............ (60 ms)              (50 ms)
50     get() returns; submit(orders)                                               fetchOrders ..........
50     ordersF.get()  BLOCKED ......................................................... (80 ms)
130    get() returns; pointsF.get() is instant (done at 60); new Summary(...) here
total 130 ms, and the request thread was parked for 130 of them  ✗
thread timeline, CompletableFuture version (ms)
time   request thread (http-exec-1)   io-pool-1                     io-pool-2        io-pool-3
0      builds the chain, RETURNS      stage 1 fetchUser ....        fetchPoints ....
0      free for the next request ✓    (50 ms)                       (60 ms)
50                                    stage 1 done -> runs the      (points done at 60)
                                      thenCompose function, which
                                      submits fetchOrders ------------------------------> fetchOrders ..........
130                                                                                       stage 2 done -> runs the
                                                                                          thenCombine callback: new Summary(...)
total 130 ms, request thread blocked for 0 ms ✓   (callbacks ran on the thread that completed the upstream stage)
Outcomes for the same task
FutureCompletableFuture
Blockingget() parks the caller for each step: 130 ms parkedNothing blocks unless you call join() or get() at the end
Chaining (orders need the user)Sequential get() calls with a blocked thread between themthenCompose(user -> ...), the next stage starts on its own
Combining (orders + points)Call get() on both and combine by handthenCombine(points, (orders, pts) -> ...)
Exception handlingget() throws checked ExecutionException; never called means never seenexceptionally, handle, whenComplete; join() throws CompletionException
Timeoutget(2, SECONDS) throws TimeoutException, the task keeps running unless you cancelorTimeout fails the future, completeOnTimeout substitutes a value; the task still keeps running
Which pool runs itThe pool you submitted to (pool-1)supplyAsync without an executor uses ForkJoinPool.commonPool(); with an executor, yours; plain thenApply runs on the completing thread

Land it Future lets you ask "is it done yet?"; CompletableFuture lets you declare "when it is done, do this next" — and that inversion is what makes real async pipelines possible.

Likely follow-ups
"What does CompletableFuture still not give you that you have to add yourself?"

Four things.

It does not propagate context: an MDC logging context, a trace ID, or a Spring SecurityContext set on the submitting thread is not visible in a stage running on a pool thread, so I wrap the executor with a decorator that copies and restores those, or use Micrometer's ContextExecutorService.

It does not cancel upstream work: cancelling a downstream stage does nothing to the supplier already running. It does not bound the number of stages in flight, so a loop that creates a million futures creates a million objects.

And its default executor is the common pool, which is shared and small. Structured concurrency, StructuredTaskScope, which became final in JDK 25, addresses the first two by tying subtasks to a scope that cancels and propagates as a unit.

"Give me a concrete case where complete() bridges a callback library into futures."

An asynchronous message-broker client with a callback API is the typical case. I create var cf = new CompletableFuture<RecordMetadata>(), then call producer.send(record, (meta, ex) -> { if (ex != null) cf.completeExceptionally(ex); else cf.complete(meta); }), and return cf.

Callers now compose it with thenCompose or orTimeout like any other future.

The two rules that make the bridge safe are: exactly one of complete or completeExceptionally must be called on every path, including the path where send throws synchronously before the callback is registered; and I usually add orTimeout, because a callback the library never fires leaves the future pending forever and anyone joining it hangs.

"What happens to a CompletableFuture that nobody ever completes?"

Nothing, and that is the danger. It sits there incomplete, every dependent stage stays incomplete, and any thread calling join() or get() without a timeout parks forever. There is no leak detector for it, and it does not show up as an error.

The symptoms are threads parked in CompletableFuture.waitingGet in a thread dump, and a slowly rising count of blocked request threads. The defenses are: always get(timeout, unit) or orTimeout when blocking on a future whose completion depends on something external, and audit every manual complete path.

In tests I use assertTimeoutPreemptively so a never-completed future fails the test rather than hanging the build.

"As of the current JDK, when would you pick structured concurrency over CompletableFuture?"

When the tasks form a unit whose lifetime matches a method call.

With StructuredTaskScope, final in JDK 25, I open a scope, fork subtasks that run on virtual threads, and join() with a policy such as fail-fast on the first error; when the scope closes, every subtask is guaranteed finished or cancelled, and an exception in one cancels the rest automatically.

That fixes the two things fan-out with allOf gets wrong: leaked work that keeps running after the caller gave up, and stack traces that lose the parent.

I still reach for CompletableFuture for long-lived pipelines, event-driven callbacks, and code that must run on JDK 21 without preview flags. For a request-scoped fan-out to three services on JDK 25, the scope version is shorter and safer.

Q190. "thenApply versus thenCompose — when do you use which?"

Reveal answer

The real test This is the map-versus-flatMap question in disguise; the giveaway is the nested future type.

Strong answer thenApply transforms the value inside the future with a plain function — value in, value out, like map on a stream.

thenCompose is for when the next step is itself asynchronous: its function returns a new CompletableFuture, and compose flattens the two stages into one, like flatMap.

The tell-tale symptom of using the wrong one is the type: if I call thenApply with a function that returns a future, I end up holding a CompletableFuture<CompletableFuture<User>> — a future of a future — which forces an awkward inner join.

So the rule I actually apply while coding: synchronous transformation, thenApply; next async call that depends on this result, thenCompose. Fetching a user ID and then fetching that user's orders from another service is the canonical compose chain.

Picture it The user-then-orders step from the shared task with the wrong and the right method, the resulting types, and the thread-blocking cost of the wrong one.

The setup: Same task as Q189: stage 2 is itself an async call that returns a future.

thenApply versus thenComposeruns offline
CompletableFuture<User> userCf = CompletableFuture.supplyAsync(() -> userClient.fetch(42), ioPool);

var wrong = userCf.thenApply(user -> orderClient.forUserAsync(user.id()));     // ❌ TRAP: the function returns a future
var right = userCf.thenCompose(user -> orderClient.forUserAsync(user.id()));   // ✅ FIX: flattened
// forUserAsync returns CompletableFuture<List<Order>>

Make the invisible visible: The type of what you hold tells you which method you used.

Method versus type
CallFunction returnsYou now hold
thenApply(user -> user.name())StringCompletableFuture<String>
thenApply(user -> forUserAsync(...))CompletableFuture<List<Order>>CompletableFuture<CompletableFuture<List<Order>>>
thenCompose(user -> forUserAsync(...))CompletableFuture<List<Order>>CompletableFuture<List<Order>>

The trace: The nested version forces an inner join, which parks the thread that runs that stage.

threads, thenApply plus inner join versus thenCompose
time  thenApply(...)+ inner.join()                       thenCompose(...)
50    io-pool-1: function runs, inner = forUserAsync()   io-pool-1: function runs, inner = forUserAsync()
50    io-pool-1: inner.join()  PARKED 80 ms ✗            compose subscribes to inner; io-pool-1 returns to the pool ✓
130   io-pool-1 resumes                                  io-pool-3: inner completes, composed future completes

What you see: The compiler shows the nested type, and a thread dump shows the pool thread parked in the join.

thread dump excerpt
# illustrative output
"io-pool-1" ... java.lang.Thread.State: WAITING (parking)
    at java.base/java.util.concurrent.CompletableFuture$Signaller.block(CompletableFuture.java:...)
    at java.base/java.util.concurrent.CompletableFuture.join(CompletableFuture.java:...)   <- the nested join

Land it If the nested type CompletableFuture-of-CompletableFuture ever appears, you wanted thenCompose — it is flatMap for futures.

Likely follow-ups
"If a function passed to thenApply throws, what happens to the chain?"

The stage completes exceptionally with a CompletionException wrapping whatever was thrown, and every dependent stage down the chain also completes exceptionally with the same cause, skipping their own functions.

Nothing is logged, and the exception travels silently until a terminal join(), get(), or an exceptionally or handle stage receives it. So a chain of five thenApply calls with a failure in the second runs the first two functions only.

The practical rule is that every chain ends in one of three things: a join with a timeout that someone reads, a handle that converts the failure to a response, or a whenComplete that logs it.

A chain that ends in thenAccept with no error handling loses every failure.

"What happens if the function passed to thenCompose returns null?"

The stage fails with a NullPointerException, because compose needs a real future to subscribe to, and the resulting CompletableFuture completes exceptionally rather than with a null value.

thenCompose returning null
userCf.thenCompose(user -> user.isActive() ? orderClient.forUserAsync(user.id()) : null)   // ❌ TRAP: early exit returns null
        .join();
// -> java.util.concurrent.CompletionException: java.lang.NullPointerException
// ✅ FIX: return CompletableFuture.completedFuture(List.of()) on the short-circuit branch

This is a genuine bug I have seen when a method that normally returns a future has an early-exit path that returns null. By contrast, a thenApply function returning null is fine: the stage simply completes with null.

So in code review, I check that every branch of a compose function returns a future, using CompletableFuture.completedFuture(defaultValue) for the short-circuit branches. If the downstream chain wants to treat "no result" as a value, I compose with a future of Optional.

"Show me a chain that combines both, a dependent async call followed by a synchronous shaping step."

Fetching the user, then the user's orders, then building a summary is the shape. In code: userClient.findAsync(id).thenCompose(user -> orderClient.forUserAsync(user.id())).thenApply(orders -> new Summary(orders.size(), total(orders))).

The first hop is compose because the order lookup is itself asynchronous and depends on the user; the second hop is apply because building a summary is a pure in-memory transformation.

If the summary also needed the user object, I would nest: thenCompose(user -> orderClient.forUserAsync(user.id()).thenApply(orders -> new Summary(user, orders))), so the user stays in scope. I keep each lambda one line so the type of every intermediate future is obvious.

"Is there a performance difference between the two?"

Not one that matters at the call site; both allocate a small dependent-stage object. The difference that does matter is what the misuse costs.

Using thenApply with an async function and then calling join() on the inner future inside the next stage turns the async step into a blocking one on whatever thread runs that stage, which may be a pool worker or an IO thread, so it silently consumes a thread for the duration of the inner call.

That is a capacity loss, not a per-call overhead. The compose version subscribes to the inner future without blocking, so the thread returns to the pool while the network call is in flight. So the "performance" argument for compose is really the thread-occupancy argument.

Q191. "thenApply versus thenApplyAsync — which thread actually runs my callback?"

Reveal answer

Strong answer With plain thenApply, the callback runs on whichever thread happens to complete the previous stage — typically the worker thread that produced the result. And if the future was already complete when I attached the callback, it runs immediately on my own calling thread.

That ambiguity matters: if the completing thread belongs to someone else — say an HTTP client's internal IO thread, where HTTP is the HyperText Transfer Protocol — then my expensive or blocking callback hijacks that thread and stalls the client's event handling for everyone.

thenApplyAsync removes the ambiguity by always dispatching the callback to a pool: the ForkJoin common pool by default, or an executor I pass explicitly as the second argument.

My working rule: cheap, non-blocking transformations can stay non-async; anything heavy or blocking gets the async variant with a named executor.

Picture it Which thread runs a callback for each variant, depending on whether the upstream future was already complete when the callback was attached.

The setup: Stage 1 of the shared task runs on io-pool; each variant attaches a callback that prints its thread name.

which thread runs the callbackruns offline
CompletableFuture<User> user = CompletableFuture.supplyAsync(() -> userClient.fetch(42), ioPool);

user.thenApply(u -> log("thenApply, attached early"));                            // before it completes
Thread.sleep(200);                                                                // now the future is complete
user.thenApply(u -> log("thenApply, attached late"));                             // ❌ TRAP: runs on THIS thread
user.thenApplyAsync(u -> log("thenApplyAsync, no executor"));                     // common pool
user.thenApplyAsync(u -> log("thenApplyAsync, ioPool"), ioPool);                  // ✅ the only one you fully control

The trace: The answer depends on two things: the variant, and whether the future was complete at attach time.

Thread that runs the callback
VariantUpstream not complete yetUpstream already complete
thenApplythe thread that completes upstream (io-pool-1)the attaching thread (main)
thenApplyAsync(fn)a ForkJoinPool.commonPool workera ForkJoinPool.commonPool worker
thenApplyAsync(fn, ioPool)an io-pool threadan io-pool thread

What you see: Each callback logs its thread name.

console
# illustrative output
thenApply, attached early       on io-pool-1
thenApply, attached late        on main                                    <- the caller's own thread
thenApplyAsync, no executor     on ForkJoinPool.commonPool-worker-1
thenApplyAsync, ioPool          on io-pool-2

Land it Non-async callbacks run on someone else's thread at an unpredictable moment — so the async variant with an explicit executor is the only version where you truly control the thread.

Likely follow-ups
"How would you prove in production which thread your callback ran on?"

Log Thread.currentThread().getName() at the top of the callback for a day and look at the distribution.

With non-async stages I typically see three families: the pool thread that completed the upstream stage, such as io-pool-7; the HTTP client's own thread, such as HttpClient-1-Worker-3 for the JDK client; and the request thread itself, such as http-nio-8080-exec-12, for the cases where the future was already complete at attach time.

callback thread-name distribution after a day
# illustrative output
io-pool-*                    18,204 calls     <- completed the upstream stage
http-nio-8080-exec-*          3,911 calls     <- future was already complete when attached
HttpClient-1-Worker-*         2,877 calls     <- ✗ the client's own IO threads run my callback: switch to thenApplyAsync(fn, ioPool)

A JFR recording gives the same answer without code changes: filter method samples by the callback's method name and group by thread.

If the client's IO thread family shows up at all for anything heavier than a field copy, that is the smoking gun for switching to the async variant.

"What goes wrong specifically when a blocking callback lands on an HTTP client's IO thread?"

Most async HTTP clients, including the JDK HttpClient and Netty-based ones such as Reactor Netty, drive every connection on a small number of event-loop threads, often one per core.

A response completes on one of those threads, and if my callback then does a JDBC call for 50 ms, that event loop cannot read or write any other socket for 50 ms.

Every other in-flight request on that loop stalls, timeouts fire, and under load the client looks like it is failing even though the servers are fine. Netty even detects this and logs a BlockingOperationError in some code paths.

The general rule is that event-loop threads may only do non-blocking work measured in microseconds; everything else is handed off with thenApplyAsync(fn, executor).

"If I pass an executor to supplyAsync, do downstream non-async stages also run on it?"

Not by contract. The executor passed to supplyAsync runs only the supplier.

A following thenApply runs on whichever thread completes the supplier stage, which in practice is the same executor thread because it is the one finishing the supplier, but it is a consequence, not a guarantee.

If the supplier had already finished before the thenApply was attached, the callback runs on the attaching thread instead. Every thenApplyAsync without an executor argument goes back to the common pool, not to my executor.

So if a whole pipeline should run on one pool, I pass the executor to every async stage. In a codebase I care about, I wrap this in a small helper so nobody can forget the second argument.

"Can I change the default executor so I never have to pass it?"

Partly. Since JDK 9, CompletableFuture has a defaultExecutor() method that subclasses can override, together with newIncompleteFuture(), so a custom subclass can make every async stage without an explicit executor use my pool.

That works but is invasive, because every future in the chain must be created through the subclass.

The simpler, more common approach is a factory class with methods like Async.supply(supplier) that always pass the named IO pool, and a static-analysis rule, an ArchUnit test or an Error Prone check, that forbids calling supplyAsync or thenApplyAsync with a single argument.

As of Aug 2026 the system property java.util.concurrent.ForkJoinPool.common.parallelism can resize the common pool, but that treats the symptom rather than the cause.

Q192 · Scenario. "After moving outbound HTTP calls to CompletableFuture.supplyAsync, unrelated parallel streams across the whole service got slow, and sometimes everything stalls at once. What is going on?"

Reveal answer

Strong answer This is common-pool starvation, and I would walk it through in order:

  1. supplyAsync with no executor argument runs tasks on ForkJoinPool.commonPool() — a single pool shared by the entire JVM (Java Virtual Machine), sized at roughly cores minus one. Parallel streams use the very same pool. That shared-ness is the link between "my HTTP code" and "unrelated streams got slow".
  2. HTTP calls are blocking IO. When my requests occupy all of the common pool's few workers, they are not computing — they are parked in socket reads for tens or hundreds of milliseconds each. Every other user of the pool now waits in line behind blocked threads.
  3. To confirm, I take a thread dump and look for ForkJoinPool.commonPool-worker-N threads all sitting in socket read frames. That signature is the diagnosis.

The fix is to give blocking work its own home: create a dedicated, bounded executor sized with the IO wait-ratio formula and pass it explicitly — supplyAsync(task, ioPool) — reserving the common pool for pure computation.

On a current JDK, an executor backed by virtual threads is an even better home for blocking calls. The ForkJoinPool.ManagedBlocker mechanism exists to compensate the pool for blocking, but an explicit executor is simpler and clearer.

Prevention is a team rule plus code review: nothing that blocks ever runs on the common pool.

Picture it The JVM-wide common pool with every worker parked in an HTTP read while a parallel stream waits, the thread-dump lines that prove it, and the same service after the fix.

The setup: Blocking HTTP calls on supplyAsync with no executor, on an 8-core machine, next to an unrelated parallel stream.

blocking work on the common poolruns offline
// ForkJoinPool.commonPool().getParallelism() == 7 on 8 cores (cores - 1)
CompletableFuture<Body> f = CompletableFuture.supplyAsync(() -> http.get(url));   // ❌ TRAP: no executor => common pool, and it blocks

long n = orders.parallelStream().filter(Order::isOpen).count();                    // unrelated code, same 7 workers

The trace: Seven slow calls take all seven workers, so the stream's tasks queue behind sockets.

common pool state: parallelism=7
moment                  common pool workers (7)                          the stream's tasks
7 HTTP calls arrive     7 of 7 parked in socket read, ~200 ms each        wait in the pool queue ✗
200 ms later            calls finish, 7 more calls already queued         next in line is another HTTP call ✗
under steady load       workers never become free for CPU work            stream takes 480 ms instead of 12 ms

What you see: A thread dump shows every common-pool worker in a socket read, entered through AsyncSupply.

thread dump excerpt
# illustrative output
"ForkJoinPool.commonPool-worker-1" ... java.lang.Thread.State: RUNNABLE
    at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:...)
    at HttpCalls.fetch(HttpCalls.java:22)
    at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:...)
... same stack for commonPool-worker-2 through worker-7 ...

Why: The common pool is one small JVM-wide pool, and blocking workers in it starves everything else that uses it.

The fix: Give blocking work its own bounded executor and name it in every call.

dedicated I/O poolruns offline
ExecutorService ioPool = new ThreadPoolExecutor(
        100, 100, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100),
        namedFactory("http-io"), new ThreadPoolExecutor.AbortPolicy());

CompletableFuture<Body> f = CompletableFuture.supplyAsync(() -> http.get(url), ioPool);   // ✅ FIX: blocking work off the common pool

What you see now: Common-pool workers are idle, the HTTP threads carry the waiting, and the stream is fast again.

thread dump excerpt and timing
# illustrative output
"ForkJoinPool.commonPool-worker-1" ... WAITING (parking) at ForkJoinPool.awaitWork    <- idle, free for the stream
"http-io-17" ... RUNNABLE at sun.nio.ch.NioSocketImpl.read                             <- the blocking now happens here
parallel stream: 12 ms

Land it The common pool is one small shared resource for the whole JVM — block it with IO and you have silently coupled every parallel stream in the process to your slowest downstream service.

Likely follow-ups
"You moved the HTTP calls to a dedicated pool, but the parallel streams are still slow. What next?"

Then something else is still blocking the common pool, and I go back to the thread dump.

Common second offenders are: parallelStream() pipelines themselves doing IO inside a map, which is the same mistake in different clothing; CompletableFuture.runAsync calls elsewhere without an executor; and library code, for example some reactive adapters or a logging appender, quietly using the common pool.

The dump shows ForkJoinPool.commonPool-worker-N threads and their stacks, and each blocked stack names the culprit.

If nothing is blocked and the streams are still slow, then the pool is simply too small for the CPU work, and I confirm by checking whether the streams' total CPU time per request matches their wall time; if it does, it is a real compute bottleneck and needs a bigger box or a smarter algorithm, not a thread fix.

"What exactly does ManagedBlocker do, and why did you not just use it?"

ForkJoinPool.ManagedBlocker is an interface with block() and isReleasable(); when a common-pool worker calls ForkJoinPool.managedBlock(blocker), the pool notices that a worker is about to block and temporarily spawns a compensating thread so parallelism is preserved.

It is how Phaser and some JDK internals stay friendly to the pool.

I did not use it because it requires wrapping every blocking call in a blocker object, it can create many compensation threads under load, up to a cap of a few hundred, and it hides the fact that blocking work is on the wrong pool.

It is the right tool inside a library that must run on the common pool and occasionally blocks; in application code, a dedicated executor is clearer and easier to size and monitor.

"How big should that dedicated IO pool be, and what happens at 10 times the traffic?"

From the wait-ratio formula and the downstream's capacity.

If each HTTP call is 2 ms of CPU and 60 ms of waiting on 8 cores, the formula gives 8 times 31, roughly 250 threads, but the real ceiling is the HTTP client's connection pool, say 100 per route, so I size at 100 and give the pool a bounded queue of about the same size.

At 10 times the traffic the pool saturates, the queue fills, and the rejection handler fires; that is the correct outcome, because the downstream cannot absorb 10 times the calls either. What I do not want is the pool silently growing to 2,500 platform threads.

As of Aug 2026 the better answer for this shape is Executors.newVirtualThreadPerTaskExecutor() plus a Semaphore of 100 permits around the call, which gives the same bound with no thread arithmetic.

"How do you prevent this from being reintroduced by the next engineer?"

Three layers. A code-level guard: an ArchUnit or Error Prone rule that fails the build on supplyAsync, runAsync, or thenApplyAsync called with one argument, and on parallelStream() outside an approved package.

A runtime guard: a startup check that logs the common pool's parallelism, and a scheduled sampler that alerts if any commonPool-worker thread spends more than a few milliseconds in a blocking state, which is cheap to implement with ThreadMXBean.getThreadInfo.

And a design guard: all blocking IO clients are injected as beans that already carry their executor, so the easy path is the correct path.

The rule "nothing blocks on the common pool" goes into the team's review checklist, but I trust the build rule more than the checklist.

Q193. "exceptionally versus handle versus whenComplete — what is the difference, and what exception type do you actually catch?"

Reveal answer

Strong answer They differ in when they run and whether they can change the outcome. exceptionally runs only on failure and returns a replacement value — it is the recovery hook, like a catch block that supplies a fallback.

handle runs on both success and failure, receives the pair (result, throwable) with one of them null, and returns a new value — so it can transform both paths, useful for converting outcomes into a uniform response type.

whenComplete also sees both, but it is an observer: it cannot replace the result, so it is for side effects like logging and metrics — though if the callback itself throws, that failure takes over.

The subtlety interviewers probe: an exception thrown in an earlier stage arrives wrapped — join() throws CompletionException and get() throws ExecutionException — so my error handling must unwrap getCause() before matching on the real exception type.

Picture it The orders stage of the shared task failing, what each of the three hooks receives and can change, and the wrapper types you see at the end.

The setup: The orders fetch throws, and three hooks are attached in turn.

failing orders stageruns offline
CompletableFuture<List<Order>> orders = CompletableFuture.supplyAsync(() -> {
    throw new IllegalStateException("orders 503");                 // the supplier fails
}, ioPool);

orders.exceptionally(ex -> { log("exceptionally got " + ex); return List.of(); });
orders.handle((r, ex)    -> { log("handle got r=" + r + " ex=" + ex); return r == null ? List.of() : r; });
orders.whenComplete((r, ex) -> log("whenComplete got r=" + r + " ex=" + ex));

The trace: The hooks differ in when they run and in whether their return value replaces the result.

What each hook does
HookRuns on successRuns on failureReceivesCan replace the outcome
exceptionallyno (value passes through)yesthe throwableyes, returns a fallback value
handleyesyesresult and throwable, one is nullyes, both paths
whenCompleteyesyesresult and throwableno: an observer; if it throws, its exception takes over

What you see: The hooks receive the wrapper, and the blocking getters add their own.

console
# illustrative output
exceptionally got java.util.concurrent.CompletionException: java.lang.IllegalStateException: orders 503
handle got r=null ex=java.util.concurrent.CompletionException: java.lang.IllegalStateException: orders 503
whenComplete got r=null ex=java.util.concurrent.CompletionException: java.lang.IllegalStateException: orders 503
orders.join() -> java.util.concurrent.CompletionException: java.lang.IllegalStateException: orders 503   <- whenComplete did not change it
orders.get()  -> java.util.concurrent.ExecutionException: java.lang.IllegalStateException: orders 503

Why: Dependent stages carry failures as CompletionException, and the blocking getters wrap again in their own type.

The fix: Unwrap the cause before branching on the real exception type.

unwrap before matchingruns offline
orders.exceptionally(ex -> {
    Throwable cause = (ex instanceof CompletionException && ex.getCause() != null) ? ex.getCause() : ex;
    if (cause instanceof IllegalStateException) return List.of();      // ✅ FIX: match the real cause, not the wrapper
    throw new CompletionException(cause);                              // rethrow wrapped so it is not wrapped twice
});

What you see now: The fallback runs for the real cause, and anything else still propagates as one wrapper.

console
# illustrative output
cause = java.lang.IllegalStateException: orders 503   -> returned List.of(), summary is degraded but delivered

Land it Recover with exceptionally, transform both paths with handle, observe with whenComplete — and always unwrap the CompletionException before you branch on the cause.

Likely follow-ups
"Show me the unwrap code, because getCause() alone is not always enough."

The wrapping can be nested, so I loop. A small helper: static Throwable unwrap(Throwable t) { while ((t instanceof CompletionException || t instanceof ExecutionException) && t.getCause() != null) t = t.getCause(); return t; }.

unwrap helperruns offline
static Throwable unwrap(Throwable t) {
    while ((t instanceof CompletionException || t instanceof ExecutionException) && t.getCause() != null)
        t = t.getCause();                                   // loop: wrapping can be nested
    return t;
}

Then in the handler: .exceptionally(ex -> { var cause = unwrap(ex); if (cause instanceof TimeoutException) return fallback(); throw new CompletionException(cause); }). Two details matter.

Rethrowing from exceptionally must wrap in CompletionException or the future will wrap it again, which produces those double-wrapped stack traces people complain about.

And a thrown exception inside the supplier of supplyAsync arrives already wrapped once, whereas one thrown in a later thenApply may be unwrapped, so the loop makes the handler indifferent to where the failure originated.

"Where in the chain should the error handler go, and does position change what it sees?"

Position matters completely. exceptionally only catches failures from stages upstream of it; a failure in a stage after it passes through untouched.

So an exceptionally placed right after supplyAsync recovers the fetch but not the transformation that follows, and one at the very end recovers everything before it.

My convention is one terminal handle at the end that converts any failure into a response, plus targeted exceptionally stages only where a specific fallback exists, such as returning an empty recommendations list if that one call fails.

Also note that a recovered failure makes downstream stages run with the fallback value, so a fallback placed early means later stages must tolerate the fallback shape.

"What does exceptionallyCompose add, and when would you use it?"

Added in JDK 12, exceptionallyCompose is to exceptionally what thenCompose is to thenApply: the recovery function returns a future instead of a value.

That is the right tool when the fallback is itself asynchronous, for example trying a replica or a cache after the primary fails: primary.fetch(id).exceptionallyCompose(ex -> replica.fetch(id)). With plain exceptionally I would have to block on the replica call inside the handler or return a nested future.

There is also an async variant that takes an executor, useful when the fallback blocks. Whatever I choose, I still unwrap the cause before deciding whether a fallback is appropriate, because retrying a replica on a 400 Bad Request is pointless.

"How do you make sure a failure in a fan-out is logged exactly once, not once per stage?"

By logging at the point where I decide the outcome, not in every intermediate stage. Each of the three fan-out futures gets a whenComplete that records a metric tagged by dependency, because that is per-dependency information I want.

The combined allOf chain gets a single terminal handle that logs the unwrapped cause once with the request ID and returns the response. Intermediate stages get no logging.

If I also need the failing stage's identity, I wrap each dependency's exception in a small typed exception that names the dependency, so the terminal log line says "pricing failed: timeout" rather than three generic lines.

The metric count per dependency and the single log line per request keep dashboards accurate and logs readable.

Q194. "How would you call three services in parallel, combine their results, and enforce an overall timeout?"

Reveal answer

Strong answer Fan out with independent futures on an explicit IO pool, join them with allOf, and bound the whole thing with orTimeout:

product-page-fanout.java
CompletableFuture<Price>   price   = CompletableFuture.supplyAsync(() -> pricing.fetch(id), ioPool);
CompletableFuture<Stock>   stock   = CompletableFuture.supplyAsync(() -> inventory.fetch(id), ioPool);
CompletableFuture<Reviews> reviews = CompletableFuture.supplyAsync(() -> ratings.fetch(id), ioPool);

CompletableFuture<ProductPage> page =
    CompletableFuture.allOf(price, stock, reviews)
        .thenApply(v -> assemble(price.join(), stock.join(), reviews.join()))
        .orTimeout(800, TimeUnit.MILLISECONDS);

The pieces of the pattern are:

  • allOf returns a CompletableFuture<Void> and carries no values, so inside thenApply I call join() on each original future. That is safe because they are all complete by then, so join returns instantly.
  • anyOf is the first-one-wins counterpart, useful for racing redundant replicas.
  • orTimeout fails the future with TimeoutException after the deadline.
  • completeOnTimeout substitutes a fallback value instead, a degraded page with reviews missing, say.

One honest caveat: a timeout completes the future, but the underlying HTTP call keeps running unless the client has its own timeout, so I set both.

Picture it The three branches as bars on a timeline for a healthy request and for a slow reviews service, showing the deadline firing while the call keeps running.

The setup: Three branches of 120, 90 and 300 ms in the healthy case, and reviews taking 2,000 ms in the slow case, with the 800 ms orTimeout from the code above.

The trace: Total time is the slowest branch, not the sum, and the timeout bounds the caller but not the call.

fan-out timeline (ms)
healthy      0        100       200       300                       800
price        |==========120|
stock        |=====90|
reviews      |==========================300|
allOf done at 300 ms  (sequential would have been 120 + 90 + 300 = 510)   ✓

slow reviews 0        100                                          800                       2000
reviews      |============================================================|xxxxxxxxxxxxxxxxxxxx|
orTimeout fires at 800 ms: page future fails; the HTTP call keeps running until 2,000 ms ✗ (connection and thread held)

What you see: The caller gets the timeout at 800 ms, while the pool still shows the call in flight.

console
# illustrative output
t=300 ms   page assembled
t=800 ms   page.join() -> java.util.concurrent.CompletionException: java.util.concurrent.TimeoutException
t=800 ms   connection pool: active=1 (reviews call still running)       <- until t=2000 ms

Why: orTimeout completes the future, not the work behind it.

The fix: Set the HTTP client's own timeout below the fan-out deadline, so the client lets go first.

client timeout below the deadlineruns offline
HttpRequest req = HttpRequest.newBuilder(uri).timeout(Duration.ofMillis(700)).build();   // ✅ FIX: client gives up at 700 ms
// ... the fan-out keeps orTimeout(800, TimeUnit.MILLISECONDS) as the outer bound

What you see now: The call ends at 700 ms, before the fan-out deadline, and nothing is left running.

console
# illustrative output
t=700 ms   reviews call: java.net.http.HttpTimeoutException       <- connection released
t=700 ms   connection pool: active=0

Land it allOf gives you the barrier, re-joining gives you the values, and orTimeout bounds the user's wait — but only the HTTP client's own timeout actually stops the work.

Likely follow-ups
"One of the three fails fast. Do the other two keep running, and is that a problem?"

They keep running. allOf completes exceptionally as soon as any input fails, but it does not cancel the other inputs; those HTTP calls continue to completion and their results are discarded.

It is a problem when the calls are expensive or when it happens at scale, because a failing dependency then leaks a full fan-out of wasted work per request.

The fix is to cancel explicitly: in the terminal handler, call cancel(true) on the remaining futures and, more importantly, cancel the underlying HTTP requests, which the JDK client supports if I keep the request future it returned.

As of Aug 2026, StructuredTaskScope in JDK 25 with the fail-fast joiner does this automatically: the first failure cancels the sibling subtasks and the scope's join throws. For request-scoped fan-out on JDK 25, that is the cleaner tool.

"You said the timeout completes the future but the HTTP call keeps running. What is the concrete cost and fix?"

The cost is occupancy.

Each abandoned call still holds a pooled connection and, on a platform-thread executor, a worker thread until the client's own timeout or the server's response, so at 500 requests per second with a 10-second downstream hang, 800 ms of user-facing timeout hides 5,000 zombie calls in flight, which exhausts the connection pool in seconds.

The fix is two-layered: set the client's read timeout below the fan-out deadline, for example 700 ms against an 800 ms orTimeout, so the client releases the connection first; and cancel the request on timeout by keeping the client's future and cancelling it in a whenComplete on the timed-out stage.

Verification is a metric on the client's connection-pool pending count; it should stay near zero during a downstream slowdown.

"How do you make this degrade instead of failing when only reviews time out?"

Per-branch timeouts with fallback values, then a combined deadline. Each optional call gets completeOnTimeout(Reviews.empty(), 500, MILLISECONDS) and an exceptionally that returns the same empty value after logging, so a slow or failed reviews service yields an empty section rather than an error.

The required calls, price and stock, keep orTimeout and fail the page. Then allOf is applied and the whole thing still carries an outer deadline.

I also expose a header or field such as partial: true so the client can show a "reviews unavailable" state and so I can count partial responses as a metric; a rising partial rate is often the earliest warning that a dependency is degrading.

"At what fan-out width does this pattern stop working, and what replaces it?"

At around 20 to 50 branches the problems change character. Each branch is a connection and possibly a thread, so a 50-way fan-out at 200 requests per second is 10,000 concurrent calls, which exceeds most connection pools and turns the fan-out into the load problem.

Tail latency also compounds: with 50 calls each having a 1 percent chance of being slow, about 40 percent of pages hit at least one slow branch.

The replacements are: batch endpoints so one call fetches 50 items; a hedged request for the slowest branches, sending a second copy after the p95 and taking the first response; and caching the stable branches.

If the fan-out is inherent, virtual threads remove the thread cost, but the connection and tail-latency arithmetic stays, so batching is the real answer.

Q195 · Scenario. "You call future.cancel(true) on a slow task, but the logs show it ran to completion anyway. Why, and what would you change?"

Reveal answer

Strong answer Cancellation in Java is cooperative, and this scenario is usually one of two honest gaps:

  1. First I check what kind of future it is. On a FutureTask from an executor, cancel(true) interrupts the worker thread. But interruption only sets a flag and wakes up methods that declare InterruptedException, like sleep or BlockingQueue.take. A task in a pure computation loop, or blocked in IO that ignores interrupts, never notices the flag and simply keeps running.
  2. If it is a CompletableFuture, the surprise is bigger: its cancel(true) does not interrupt anything at all — the argument is ignored. It merely marks the future as cancelled so downstream stages see a CancellationException, while the supplier keeps executing and its eventual result is thrown away.

The fix is to make tasks cancellable on purpose:

  • Long loops periodically check Thread.currentThread().isInterrupted() and exit.
  • Blocking calls use interruptible or timeout-aware variants.
  • Catch blocks that catch InterruptedException either rethrow it or restore the flag with Thread.currentThread().interrupt(), so the signal is not swallowed.
  • External work: if I truly need to abort it, I cancel at the source, the HTTP request or database statement, not just the future wrapping it.

Picture it Three tasks cancelled with the same call, and what each one actually does afterwards.

The setup: A sleeping task and a busy loop on a FutureTask, plus a CompletableFuture supplier that works for five seconds.

three kinds of cancelruns offline
Future<?> sleeping = pool.submit(() -> { Thread.sleep(60_000); return null; });          // interruptible
Future<?> busy     = pool.submit(() -> { while (true) { crunch(); } });                  // ❌ TRAP: never checks the flag
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> { work(5_000); return "done"; }, pool);

sleeping.cancel(true); busy.cancel(true); cf.cancel(true);

The trace: Same call, three different effects.

cancel(true) outcomes
TaskFuture saysWorker threadWork stops?
FutureTask in Thread.sleepisCancelled() == truegets InterruptedException at onceWorks: stops in milliseconds
FutureTask in a busy loopisCancelled() == trueflag set, nobody reads it, still RUNNABLEFails: runs to the end, CPU still burning
CompletableFuture supplierisCancelled() == true, dependents get CancellationExceptionno interrupt is sent at allFails: runs 5 s, result thrown away

What you see: The futures say cancelled while a worker is still busy.

console and thread dump
# illustrative output
busy.isCancelled() = true      cf.isCancelled() = true
"pool-1-thread-2" ... java.lang.Thread.State: RUNNABLE     <- still crunching after cancel(true)
    at Demo.crunch(Demo.java:14)
supplier finished at +5.0 s, result discarded

Why: cancel marks the future and sets a flag, and only code that polls the flag can react; CompletableFuture does not even set it.

The fix: Poll the flag and cancel the underlying resource.

cancellable taskruns offline
Future<?> busy = pool.submit(() -> {
    while (!Thread.currentThread().isInterrupted()) { crunch(); }     // ✅ FIX: poll the flag
    return null;
});
cf.whenComplete((r, ex) -> { if (cf.isCancelled()) statement.cancel(); });   // ✅ FIX: cancel at the source

What you see now: The loop exits right after the cancel, and the query is aborted server-side.

console
# illustrative output
"pool-1-thread-2" state=TIMED_WAITING (idle in pool)     <- loop exited at the next flag check
statement.cancel() called; database reports the query as cancelled

Land it cancel is a polite request, not a kill switch — a task stops early only if it was written to listen, and CompletableFuture.cancel does not even ask.

Likely follow-ups
"You made the loop check isInterrupted, and it still runs to completion. What else could be going on?"

Two likely causes. First, something in the loop swallowed the interrupt: a library call that catches InterruptedException and does not restore the flag clears it, so my check never sees it.

I find that by putting a breakpoint or a log inside any catch block for InterruptedException in the call path, and by searching for catches that neither rethrow nor call Thread.currentThread().interrupt().

Second, the wrong thread was interrupted: with CompletableFuture.supplyAsync, cancel interrupts nothing, and with a FutureTask the interrupt goes to the worker that is running the task, but if the task handed work to another executor, that inner worker never gets the signal.

A thread dump during the "cancelled" run shows which thread is doing the work and whether it matches the one that received the interrupt.

"How do you actually cancel an in-flight HTTP request or database query?"

At the source, with the client's own cancellation. The JDK HttpClient.sendAsync returns a CompletableFuture whose cancel(true) does attempt to abort the exchange, one of the few places where the flag is honored, because the client registers a dependent action. Apache HttpClient has request.abort().

For JDBC, Statement.cancel() asks the driver to cancel the running query server-side; Postgres and MySQL drivers support it, and setQueryTimeout(seconds) does the same on a timer.

The pattern is to hold a handle to the cancellable resource in the task and wire the future's cancellation to it: future.whenComplete((r, ex) -> { if (future.isCancelled()) statement.cancel(); }). Without that wiring, cancelling the Java future leaves the database still grinding through the query.

"Why does CompletableFuture.cancel ignore mayInterruptIfRunning, and does anything newer fix that?"

Because a CompletableFuture does not know which thread, if any, is computing its value; it might be completed by a callback from a library, by complete() from any thread, or by a supplier on some executor, so there is no thread to interrupt.

The designers chose to have cancel mean "complete exceptionally with CancellationException" and nothing more.

What fixes it is structured concurrency: in StructuredTaskScope, final in JDK 25, each subtask runs on its own virtual thread owned by the scope, so the scope can and does interrupt subtasks when it is cancelled or closed.

That is the first JDK mechanism where cancelling a unit of async work reliably interrupts the thread doing it, and it is the main reason I prefer scopes for request-scoped fan-out on JDK 25.

"Where does a swallowed interrupt usually hide in a real codebase, and how do you find it?"

In catch blocks written to make the compiler happy. The classic is catch (InterruptedException e) { log.warn("interrupted"); } inside a retry loop or a sleep helper, which clears the flag and continues; the thread has been asked to stop and carries on as if nothing happened.

I find them with a grep for catch (InterruptedException and a review of each, or, more reliably, with a static analysis rule: SonarQube's "InterruptedException should not be ignored" rule and Error Prone's equivalent flag exactly this.

The fix in every case is either to rethrow, or to call Thread.currentThread().interrupt() and return. I also check that Future.get() call sites propagate rather than swallow, because that is the second most common hiding place.

Drill · Locks, atomics & coordinators

Here the interviewer wants reasons, not fashion: when an explicit lock earns its complexity over synchronized, what compare-and-swap really does, and which coordinator fits which shape of waiting.

Q196. "When do you reach for ReentrantLock instead of synchronized?"

Reveal answer

Strong answer My checklist is short: I take ReentrantLock — an explicit lock object, reentrant meaning the thread holding it may acquire it again — only when I need a feature synchronized cannot give me.

Those features are: tryLock() with a timeout, so a thread can give up instead of deadlocking; lockInterruptibly(), so a waiting thread can be cancelled; an optional fairness mode; and multiple Condition objects on one lock.

Otherwise I default to synchronized — the keyword that acquires the monitor, the built-in lock every Java object carries — because it is simpler, modern JVMs make it fast, and it physically cannot be leaked: the monitor is released automatically when the block exits, even by exception.

An explicit lock demands the discipline of lock() immediately followed by try, with unlock() in finally — forget that once and you have a permanent hang.

Picture it A monitor and an explicit lock as owner plus waiters, what each looks like in a thread dump, and a leaked lock with its fix.

Make the invisible visible: Both are a lock with one owner and a queue of waiters; only the lock lets you leave the queue.

owner and waiters
synchronized (obj)                          ReentrantLock lock
  owner : T1                                  owner : T1  (holdCount 1)
  entry queue : T2, T3  (cannot give up)      wait queue  : T2, T3
                                                tryLock(200 ms) -> T2 can give up ✓
                                                lockInterruptibly() -> T3 can be cancelled ✓
                                                newCondition() x N -> several wait sets on one lock

What you see: A thread dump names the monitor or the lock object each waiter is blocked on.

thread dump lines
# illustrative output
synchronized:   - waiting to lock <0x000000076ab12340> (a Account)
                - locked <0x000000076ab12340> (a Account)                       <- on the owner
ReentrantLock:  - parking to wait for <0x000000076ab56780> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
                Locked ownable synchronizers:                                   <- shown with jcmd <pid> Thread.print -l
                - <0x000000076ab56780> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)

The setup: The price of an explicit lock is that releasing it is your job.

leaked lockruns offline
lock.lock();
validate(order);           // ❌ TRAP: throws => unlock() is skipped, the lock stays held forever
lock.unlock();

What you see: Every later caller parks forever, and the owner is an idle pool thread.

jcmd <pid> Thread.print -l
# illustrative output
"pool-2-thread-4" ... WAITING (parking) at AbstractQueuedSynchronizer.parkAndCheckInterrupt   <- one of many waiters
"pool-2-thread-1" ... WAITING (idle in pool)
    Locked ownable synchronizers:
    - <0x000000076ab56780> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)   <- the idle thread still owns it ✗

The fix: Put lock() immediately before try and unlock() in finally.

lock, try, finallyruns offline
lock.lock();
try {
    validate(order);       // ✅ FIX: any exception still reaches finally
} finally {
    lock.unlock();
}

What you see now: After a failing call the lock is free.

test assertions
# illustrative output
after validate() threw:  lock.isLocked() = false    lock.getHoldCount() = 0

Land it ReentrantLock is a feature purchase paid for with manual-release risk — buy it for tryLock, interruptibility, fairness, or multiple conditions, and not otherwise.

Likely follow-ups
"As of the current JDK, does the virtual-thread pinning issue change your default?"

As of Aug 2026 it changes it only on JDK 21 through 23.

On those versions a virtual thread that blocks inside a synchronized block or method pins its carrier thread, so a few hundred virtual threads blocked in synchronized IO can starve the carrier pool, and the fix was to switch hot paths to ReentrantLock, which does not pin.

JDK 24 removed that limitation, so synchronized no longer pins on blocking. So on JDK 25 my default is back to synchronized for simple mutual exclusion.

On JDK 21 in a virtual-thread-heavy service, I run with -Djdk.tracePinnedThreads=full, or watch the jdk.VirtualThreadPinned JFR event, and convert only the monitors that actually show up as pinning.

"Show me the tryLock pattern that avoids deadlock, and what you do when it fails."

The pattern acquires with a timeout and gives up cleanly: if (!lock.tryLock(200, MILLISECONDS)) { metrics.increment("lock.timeout"); throw new ServiceBusyException(); } try { work(); } finally { lock.unlock(); }.

tryLock patternruns offline
if (!lock.tryLock(200, TimeUnit.MILLISECONDS)) {       // expected hold time is ~2 ms, so 200 ms means something is wrong
    metrics.increment("lock.timeout");
    throw new ServiceBusyException();                   // fail fast, do not retry in a tight loop
}
try { work(); } finally { lock.unlock(); }

On failure I do not retry in a tight loop; I fail the operation quickly, usually as a 503 or a retryable error to the caller, and count it.

For two-lock deadlock avoidance specifically, I try both locks with timeouts and release the first if the second fails, then back off with jitter and retry a bounded number of times.

The timeout value comes from the lock's expected hold time: if the critical section is 2 ms, waiting 200 ms means something is badly wrong and failing is better than queueing. The counter tells me whether that ever happens.

"Is there a performance difference between the two in the current JVM?"

For uncontended use, essentially none: both are a compare-and-swap on the fast path, and synchronized benefits from JIT optimizations such as lock elision and coarsening that ReentrantLock cannot get.

Under heavy contention they behave similarly, since both park waiting threads; ReentrantLock historically had an edge in fairness options and its wait queue, but modern monitors, especially with the lightweight locking mode that became default around JDK 23 and 24, closed the gap.

The measurable difference is in memory and diagnostics: a ReentrantLock is an extra object per guarded resource, and thread dumps show monitor ownership with "locked" annotations for synchronized but need -XX:+PrintConcurrentLocks or a jcmd Thread.print -l to show ReentrantLock owners. I decide on features, not on speed.

"How do you catch a forgotten unlock in review or in tests?"

In review, the shape rule is mechanical: every lock() must be followed immediately by try, with the unlock() as the first statement in finally, and no code between lock() and try that could throw.

Error Prone and SpotBugs both have rules that flag a lock acquired without a matching release on all paths.

In tests, I assert the lock's state: after the method under test returns or throws, lock.isLocked() must be false, and for reentrancy bugs lock.getHoldCount() must be zero on the test thread.

In production, the symptom of a leaked lock is a slowly growing count of threads parked in AbstractQueuedSynchronizer.parkAndCheckInterrupt against the same lock, and jcmd <pid> Thread.print -l shows the owner as a thread that is idle in the pool.

Q197. "What does Condition give you over wait and notify? Sketch a bounded buffer with it."

Reveal answer

Strong answer A Condition is a waiting room attached to a lock — and one lock can own several. That is the whole advantage: an object's monitor has exactly one wait set, so producers waiting for space and consumers waiting for items sit in the same room, and you must wake everyone with notifyAll and let the wrong ones re-check and go back to sleep. With two conditions I wake exactly the side I helped:

bounded-buffer.java
final ReentrantLock lock = new ReentrantLock();
final Condition notFull  = lock.newCondition();
final Condition notEmpty = lock.newCondition();

void put(T item) throws InterruptedException {
    lock.lock();
    try {
        while (count == capacity)      // loop, never 'if': re-check after every wake-up
            notFull.await();
        enqueue(item);
        notEmpty.signal();             // wake exactly one waiting consumer
    } finally {
        lock.unlock();
    }
}
// take() mirrors this: while empty -> notEmpty.await(); dequeue; notFull.signal()

The old rules still apply unchanged: you must hold the lock to await or signal, and the wait lives in a while loop because a thread can wake spuriously or find the state already consumed by another thread. What changed is precision — signal() on the right condition replaces a broadcast to everybody.

Picture it One wait set versus two, with the bounded buffer in a concrete state, and the wake-up that breaks code using if instead of while.

Make the invisible visible: A monitor has one wait set; a lock can own one per concern.

wait sets, buffer capacity 2, full
monitor (synchronized + wait/notifyAll)       lock + two Conditions
  one wait set: P1 P2 C1                        notFull  set: P1 P2    notEmpty set: C1
  a take() calls notifyAll(): wakes all 3       a take() calls notFull.signal(): wakes P1 only ✓
  P2 and C1 re-check, sleep again ✗             P2 and C1 stay asleep, no wasted wake-ups

The setup: Why the wait must sit in a while: a second consumer can slip in between the signal and the wake-up.

if instead of whileruns offline
lock.lock();
try {
    if (count == 0)            // ❌ TRAP: 'if', so a woken thread does not re-check
        notEmpty.await();
    return dequeue();          // may run with count == 0
} finally { lock.unlock(); }

The trace: Consumer C1 is signalled, but C3 reaches the lock first.

interleaving
step  producer           C1 (waiting in await)        C3 (fresh arrival)         count
1     enqueue, signal()  woken, must re-acquire lock                              1
2                        waiting for the lock         lock() ✓ dequeue()           0
3                        lock ✓, 'if' already passed  unlock                       0
4                        dequeue() on an empty buffer ✗                            0

What you see: The failure is an exception from the empty buffer or a null item.

console
# illustrative output
java.util.NoSuchElementException     (or ArrayIndexOutOfBoundsException, or a null item, depending on the buffer)

The fix: Re-check the condition in a loop, as the bounded buffer in the answer does.

while loopruns offline
while (count == 0)             // ✅ FIX: re-check after every wake-up
    notEmpty.await();
return dequeue();              // now count > 0 is guaranteed here

What you see now: The same interleaving puts C1 back to sleep instead of failing.

interleaving
step 4  C1 re-checks: count == 0 -> await() again ✓      no exception, C1 waits for the next put

Land it Condition is wait/notify with separate wait sets per concern — same discipline, but targeted wake-ups instead of waking the whole room.

Likely follow-ups
"Why signal instead of signalAll here, and when is signalAll still required?"

signal() wakes one waiter on that condition, which is enough because each put creates exactly one item and one consumer can take it; waking every consumer would just make the others re-check and sleep again.

signalAll() is required when a state change may satisfy more than one waiter, or when waiters on the same condition are waiting for different things. For instance, a putAll(items) that adds five items should signalAll, or signal in a loop five times.

It is also the safe choice if a waiter can be interrupted or time out between being signalled and acquiring the lock, because a lost single signal leaves one item with no consumer awake.

When in doubt, signalAll is correct and merely less efficient; signal is an optimization that needs an argument.

"Why would you write this instead of using ArrayBlockingQueue?"

I would not, in production. ArrayBlockingQueue is exactly this code, written by the JDK authors, with the two-condition design inside it. I write the bounded buffer in interviews to prove I understand the mechanism, and in real code I reach for the JDK queue.

The cases where hand-rolled conditions earn their place are when the waiting condition is not "empty or full": for example, waiting until a specific key is present, waiting until the sum of pending sizes drops below a byte budget, or coordinating three states such as idle, draining, and stopped.

Even then I first check whether Semaphore, CountDownLatch, Phaser, or a CompletableFuture expresses it, because the JDK primitives have had their spurious-wakeup and lost-signal bugs shaken out.

"What is a spurious wakeup concretely, and can you demonstrate it?"

A spurious wakeup is await() returning without any thread having signalled.

It is permitted by the Java memory model and by the underlying POSIX pthread_cond_wait, which the JVM uses on Linux, because the operating system can wake a waiter early after a signal delivery or for its own scheduling reasons.

It is rare, so I cannot reliably demonstrate it on demand, but the same defensive loop also covers the common case that is easy to demonstrate: two consumers both signalled, the first takes the only item, and the second wakes to an empty buffer.

A test with one producer and two consumers that use if instead of while fails with an index-out-of-bounds or a null item within a few thousand iterations, and that is the demonstration I use in code review.

"How would you add a timed put that gives up after 100 milliseconds?"

With awaitNanos, which returns the remaining time so the loop stays correct across spurious wakeups.

In code: long nanos = unit.toNanos(timeout); lock.lock(); try { while (count == capacity) { if (nanos <= 0) return false; nanos = notFull.awaitNanos(nanos); } enqueue(item); notEmpty.signal(); return true; } finally { lock.unlock(); }.

timed putruns offline
boolean offer(T item, long timeout, TimeUnit unit) throws InterruptedException {
    long nanos = unit.toNanos(timeout);
    lock.lock();
    try {
        while (count == capacity) {
            if (nanos <= 0) return false;              // gave up: caller can shed or retry
            nanos = notFull.awaitNanos(nanos);         // returns the REMAINING time; reuse it
        }
        enqueue(item); notEmpty.signal(); return true;
    } finally { lock.unlock(); }
}

The key detail is re-using the returned nanos rather than resetting the timeout each iteration; otherwise a stream of spurious or unhelpful wakeups could extend the wait far beyond 100 milliseconds. This is exactly the shape of ArrayBlockingQueue.offer(e, timeout, unit).

A timed put is what turns a blocking buffer into a backpressure tool, since the caller can decide to shed or retry when it returns false.

Q198 · Scenario. "A read-heavy in-memory cache guarded by one synchronized block became a bottleneck at high traffic. What do you try, and what is the catch?"

Reveal answer

Strong answer I would work it in this order:

  1. Confirm the diagnosis with a profiler or thread dump: many threads blocked entering the same monitor, and the workload measurably read-dominated — say 95 percent reads. Exclusive locking makes those readers queue single-file even though concurrent readers cannot harm each other.
  2. Introduce ReentrantReadWriteLock. Any number of threads may hold the read lock simultaneously. The write lock is exclusive and waits for all readers to leave. For a read-mostly cache, read throughput scales with cores almost immediately.
  3. State the catch before the interviewer does. There are three parts:
    • Writer starvation: in the default non-fair mode a writer can wait a long time while readers keep streaming in. For a cache that means updates and invalidations arrive late, so stale data is served under peak load.
    • The mitigation: the implementation blocks newly arriving readers once a writer is queued, and fair mode enforces ordering. Fairness costs throughput.
    • No upgrade: turning a read lock into a write lock is not allowed. Attempting it deadlocks, so you must release and re-acquire.
  4. Offer the simpler alternatives: for a plain key-value cache, ConcurrentHashMap usually beats any hand-rolled lock; and for tiny read-hot critical sections, StampedLock's optimistic mode is faster still.

Picture it One monitor serialises every reader; a read-write lock lets readers share, and the lock state at five moments shows how a queued writer holds back new readers.

The setup: a cache where every method takes the same monitor.

Cache.javaruns offline
final class Cache {
    private final Map<String, String> map = new HashMap<>();

    // ❌ TRAP: readers cannot overlap, although concurrent reads are harmless
    synchronized String get(String k)         { return map.get(k); }
    synchronized void put(String k, String v) { map.put(k, v); }
}

Make the invisible visible: the read-write lock state at successive moments, in non-fair mode, with one writer arriving.

lock state over timeruns offline
moment  event                       readers holding  writer  wait queue (head first)
t0      R1 R2 R3 call readLock      R1 R2 R3         -       -
t1      W calls writeLock           R1 R2 R3         -       [W]
t2      R4 calls readLock           R1 R2 R3         -       [W, R4]  <- R4 queues behind the waiting writer
t3      R1 R2 R3 unlock             -                W       [R4]     <- last reader out hands over to W
t4      W unlocks                   R4               -       -

What you see: a thread dump taken at peak with most request threads blocked on the one monitor.

thread dump excerptruns offline
# illustrative output
"http-nio-8080-exec-17" #61 prio=5 tid=0x00007f2c ... waiting for monitor entry
   java.lang.Thread.State: BLOCKED (on object monitor)
        at com.example.Cache.get(Cache.java:6)
        - waiting to lock <0x000000076ab12340> (a com.example.Cache)
# 38 of 48 request threads show the same "waiting to lock <0x000000076ab12340>" line

Why: a monitor admits one thread at a time, so 95 percent of the traffic (reads) queues behind itself even though readers cannot harm each other.

The fix: a read-write lock around the same map, with release in finally.

CacheRw.javaruns offline
final class CacheRw {
    private final Map<String, String> map = new HashMap<>();
    private final ReentrantReadWriteLock rw = new ReentrantReadWriteLock();

    String get(String k) {
        rw.readLock().lock();                 // ✅ FIX: readers share the lock
        try { return map.get(k); } finally { rw.readLock().unlock(); }
    }
    void put(String k, String v) {
        rw.writeLock().lock();                // exclusive: waits for all readers
        try { map.put(k, v); } finally { rw.writeLock().unlock(); }
    }
}

What you see now: the same dump query after the change.

thread dump excerptruns offline
# illustrative output
$ jcmd 4711 Thread.print | grep -c "waiting to lock"
0
# Result: readers no longer park; time shows up as CPU in ReadLock.lock instead

Land it ReadWriteLock is the right shape for read-mostly data, but I would say out loud that a ConcurrentHashMap probably deletes the problem instead of tuning it.

Likely follow-ups
"You switched to ReentrantReadWriteLock and throughput barely improved. Why might that be?"

Two usual reasons. First, the read lock is not free: acquiring it does a compare-and-swap on the lock's shared state word, so with 32 cores hammering the same lock, that one cache line bounces between cores and becomes the bottleneck even though no thread ever blocks.

That shows up as high CPU with little progress and is why StampedLock's optimistic read exists.

Second, the critical section may be doing more than a lookup, for example deserializing or computing under the read lock, so the writer waits a long time and reads still serialize behind writes.

I verify with a profiler. If time is inside ReentrantReadWriteLock.ReadLock.lock it is contention on the lock word. If it is inside my code under the lock, I shrink the critical section.

And I re-ask whether a ConcurrentHashMap deletes the lock entirely.

CPU profile summaryruns offline
# illustrative output (32 threads, 95% reads)
 41%  ReentrantReadWriteLock$ReadLock.lock    <- CAS on the shared state word: lock-word contention
 38%  Cache.get -> HashMap.get                 <- the real work
 12%  everything else
"Why is read-to-write upgrade forbidden, and how do you write the check-then-update safely?"

Because two threads holding the read lock could both try to upgrade, and each would wait for the other to release its read lock, which is a deadlock by construction; the JDK refuses rather than risk it, so writeLock().lock() while holding the read lock blocks forever.

Downgrade, write to read, is allowed.

The safe pattern is to release the read lock, acquire the write lock, and re-check the condition, because another writer may have updated the state in the gap.

upgrade deadlockruns offline
read.lock();
try {
    if (!present) {
        write.lock();   // ❌ TRAP: blocks forever - this thread still holds the read lock
    }
} finally { read.unlock(); }

So: read.lock(); try { if (present) return value; } finally { read.unlock(); } write.lock(); try { if (!present) load(); return value; } finally { write.unlock(); }. Or use StampedLock.tryConvertToWriteLock(stamp), which upgrades atomically when no other reader is present and returns zero otherwise.

"What does ConcurrentHashMap do differently that makes it faster than any read-write lock here?"

Reads in ConcurrentHashMap take no lock at all. A get reads the table and the bucket's nodes through volatile reads, which on x86 are ordinary loads, so 64 readers on 64 cores scale linearly and touch no shared writable word.

Writes lock only the individual bucket head with a tiny synchronized block, so two writers on different keys never contend, and a resize is cooperative, with multiple threads transferring bins in parallel.

For a cache I would use computeIfAbsent for atomic load-on-miss, with the caveat that the loading function must be short and must not touch the same map, because it runs while the bucket is locked.

If I need eviction and expiry as well, Caffeine is built on the same lock-free read design with a bounded size, and is the answer for anything beyond a plain map.

"How would you measure the read/write ratio and lock contention to justify the change?"

Two measurements. For the ratio, a pair of counters or Micrometer timers around the read and write paths for a day gives the split directly; if it is not at least around 90 percent reads, a read-write lock will not pay for itself.

For contention, I use a JFR recording with the jdk.JavaMonitorEnter event. It records every time a thread blocks entering a synchronized block for longer than the threshold, which defaults to 20 milliseconds, with the total per monitor class. JFR's lock-instances view then ranks monitors by blocked time.

For ReentrantLock and friends the equivalent is the jdk.ThreadPark event. If the cache's monitor is at the top of that list with hundreds of blocked events per second, the change is justified, and the same recording after the change is the proof it worked.

Q199. "How does StampedLock's optimistic read work, and what are its sharp edges?"

Reveal answer

Strong answer tryOptimisticRead() does not acquire anything — it just returns a stamp, a version number of the lock's state.

I read the fields I need into local variables, then call validate(stamp): if no writer acquired the lock since my stamp, my reads were consistent and I am done without ever taking a lock; if validation fails, I fall back to acquiring the real read lock and re-reading.

The speed comes from writing nothing shared: a normal read lock updates the lock's state, which bounces cache lines between cores; an optimistic read is a pure read.

The sharp edges are real:

  • Not reentrant: re-acquiring inside the same thread blocks you against yourself.
  • No Condition support.
  • Garbage before validation: values read before a failed validation cannot be trusted. I copy to locals first and never act on them until validate passes.

Picture it A reader and a writer interleaved, with the lock version after each step, so you can see exactly where an optimistic read goes torn and where validate catches it.

The setup: a point with two fields, a writer that moves both under the write lock, and a reader that uses the optimistic path.

Point.javaruns offline
class Point {
    private final StampedLock sl = new StampedLock();
    private double x = 3, y = 4;

    void move(double nx, double ny) {
        long w = sl.writeLock();
        try { x = nx; y = ny; } finally { sl.unlockWrite(w); }
    }
    double distanceFromOrigin() {
        long stamp = sl.tryOptimisticRead();
        double lx = x, ly = y;                    // copy to locals FIRST
        if (!sl.validate(stamp)) {                // a writer got in: locals may be torn
            stamp = sl.readLock();
            try { lx = x; ly = y; } finally { sl.unlockRead(stamp); }
        }
        return Math.hypot(lx, ly);                // use only the locals
    }
}

The trace: the writer calls move(6, 8) while the reader is between its two field reads.

thread interleavingruns offline
# illustrative stamp values
step  reader                           writer                    lock state
1     stamp = tryOptimisticRead() = 256                          unlocked, version 256
2     lx = x  -> 3
3                                      writeLock() = 384         write-locked
4                                      x = 6; y = 8
5     ly = y  -> 8                                               reader holds the torn pair (3, 8)
6                                      unlockWrite()             unlocked, version 512
7     validate(256) -> false  ✓ caught                           512 != 256
8     readLock(); lx=6, ly=8; unlock   -> hypot(6, 8) = 10.0  ✓

What you see: what the reader would have returned if it skipped the validation.

consoleruns offline
# without validate:  Math.hypot(3, 8) = 8.544...   <- neither the old 5.0 nor the new 10.0
# with validate:     Math.hypot(6, 8) = 10.0                 <- consistent

Land it Optimistic read is for tiny, read-dominated critical sections where you can cheaply redo the read — outside that shape, its non-reentrancy makes it a footgun.

Likely follow-ups
"Show me the full optimistic read pattern, including the fallback."

The canonical shape for a two-field point class is the distanceFromOrigin method in the Picture it block above.

The order is load-bearing: copy every field to locals first, then validate, then use only the locals.

Between the optimistic stamp and validate a writer may have changed x but not yet y, so the locals could be torn; validation detects that and the fallback re-reads under a real read lock.

validate also returns false if the stamp is zero, which is what tryOptimisticRead returns while a writer holds the lock, so the fallback path covers that case automatically.

"Why must the reads go into locals? What actually goes wrong if I use the fields after validate?"

Because validation certifies the past, not the future. validate(stamp) says no writer acquired the lock between the stamp and the validate call, so any values loaded in that window are consistent.

A field read after validate is outside the certified window; a writer might have started in the meantime, and I could combine a pre-validate x with a post-validate y.

There is also a compiler subtlety: the fields are not volatile, so without the memory fence that validate performs internally, the JIT could reorder the field loads after the validation check.

Reading into locals before the call keeps the loads inside the window and in front of the fence. That is why every example in the JDK documentation reads into locals, and I treat it as non-negotiable in review.

"How much faster is it really, and how would you benchmark that honestly?"

On a read-dominated microbenchmark with many threads, optimistic reads can be several times faster than a ReentrantReadWriteLock read, because the read lock's compare-and-swap makes all readers contend on one cache line while the optimistic path writes nothing.

With one or two threads the difference is small, tens of nanoseconds.

To measure honestly I use JMH, the Java Microbenchmark Harness, with a @Group benchmark that runs a configurable number of reader threads and one occasional writer, because a benchmark with no writer flatters the optimistic path since validation never fails.

I report throughput at 1, 4, 16, and 32 threads, and the validation failure rate. If the writer runs more than a few percent of the time, optimistic reads fall back constantly and lose their advantage, which is the honest limit of the technique.

"What does the non-reentrancy footgun look like in real code?"

It looks like a self-deadlock inside a method that calls a helper. Suppose getTotal() takes the read lock and calls getItems(), which also takes the read lock. With ReentrantReadWriteLock that is fine.

With StampedLock the second readLock() will block if a writer is queued. StampedLock lets a waiting writer stop new readers to avoid starvation.

The writer is waiting for the first read lock to be released, which never happens.

self-deadlock traceruns offline
getTotal():  readLock() -> stamp S1          (reader count 1)
  writer W:  writeLock() queues behind S1   (waits for the reader to leave)
  getItems(): readLock() -> parks           ✗ blocked behind queued W, W waits for S1: deadlock

It also bites with the write lock directly: a write-locked method calling another write-locked method blocks forever, immediately. The dump shows one thread parked in StampedLock.acquireRead or acquireWrite holding a stamp from the same lock higher in the stack.

The defense is to keep StampedLock usage in a single small class with no nested calls.

Q200. "What does a fair lock actually cost, and when is fairness worth paying for?"

Reveal answer

Strong answer A fair lock grants ownership strictly first-come-first-served through its wait queue. The cost comes from banning barging — a thread grabbing a just-released lock without queueing.

Barging is efficient because the barging thread is already running on a core, while the queued thread at the head must be woken by the scheduler, which is a context switch costing microseconds.

Fair mode forces that wake-up on every contended handoff, so under contention throughput can drop by an order of magnitude versus non-fair. That is exactly why non-fair is the default for both ReentrantLock and synchronized-style monitors.

Fairness is worth it when I have observed starvation — some thread waiting unboundedly while others cycle through the lock — or when per-request latency predictability genuinely matters more than aggregate throughput.

That is rare; usually redesigning to hold the lock for less time beats making the lock fair.

Picture it The same hand-over of a lock under non-fair and fair mode, side by side, and a table of which acquisition calls actually respect the fairness flag.

The setup: a fair lock and the two ways of asking for it without waiting.

FairLockDemo.javaruns offline
ReentrantLock fair = new ReentrantLock(true);   // first-come-first-served

fair.lock();                         // honours the queue
fair.tryLock();                      // ❌ TRAP: barges even on a fair lock
fair.tryLock(0, TimeUnit.SECONDS);   // ✅ FIX: honours fairness (declares InterruptedException)

Make the invisible visible: the hand-over at successive moments, with T2 already parked in the queue when T1 unlocks.

lock hand-over, non-fair versus fairruns offline
moment  non-fair                                   fair
t0      owner T1, queue [T2 parked]               owner T1, queue [T2 parked]
t1      T1 unlock(): free, T2 is unparked         same
t2      T3 arrives, already running on a core     T3 arrives, sees T2 queued ahead
t3      T3 CAS 0->1 succeeds  ✓ (barging)         T3 enqueues behind T2 and parks
t4      T2 wakes, finds it taken, parks  ✗        T2 wakes (context switch), CAS succeeds  ✓
cost    no wake-up on the hand-over path          a wake-up of T2 on every contended hand-over

What you see: which calls respect the flag, per the ReentrantLock contract.

Does the call honour fairness on a fair lock?
CallRespects queue order?
lock()Works: queues like everyone else
tryLock()Silently unfair: takes a free lock even if threads are queued
tryLock(0, TimeUnit.SECONDS)Works: goes through the fair queue, returns false if not next
tryLock(5, TimeUnit.SECONDS)Works: queued wait with a timeout

Why: barging avoids the wake-up latency, and the specification deliberately lets the untimed tryLock() trade fairness for immediacy.

Land it Fairness trades a large slice of throughput for a guarantee against starvation — buy it only when starvation is a measured problem, not a theoretical one.

Likely follow-ups
"How would you detect starvation rather than assume it?"

By measuring lock wait time per thread, not just average throughput. I wrap acquisition with a timer that records how long each lock() call waited and tag it by the acquiring thread's pool name, then look at the p99 and the maximum, not the mean.

Starvation appears as a fat tail: most waits are microseconds, but a few threads wait seconds.

A JFR recording with jdk.ThreadPark events shows the same thing per thread.

lock wait per acquisitionruns offline
# illustrative output
pool=report-worker   waits: p50=0.01 ms   p99=0.4 ms   max=2300 ms   <- fat tail: starvation
pool=api-worker      waits: p50=0.01 ms   p99=0.3 ms   max=1.1 ms

The clincher is ReentrantLock.getQueueLength() and hasQueuedThread(t) sampled periodically; a thread that stays in the queue across many samples while the lock changes hands is being barged past.

Only when I see that pattern do I turn on fairness, and I keep the timer so I can show the tail shrank.

"Does tryLock() respect fairness?"

No, and that is a well-known trap. The no-argument tryLock() barges: it grabs the lock if it is free even when other threads are queued, regardless of the fair setting, because the specification says it is a barging acquisition.

So a fair lock plus a hot loop of tryLock() is not fair at all. If I want a timed acquisition that honors fairness, I use tryLock(0, TimeUnit.SECONDS), which goes through the fair queue and returns immediately if it cannot acquire in order.

The same distinction exists for Semaphore.tryAcquire(). In review, whenever I see a fair lock, I check every acquisition site, because one barging tryLock() in a hot path silently undoes the guarantee the fairness flag was bought for.

"Where does fairness matter in the standard library, and is synchronized ever fair?"

synchronized is never fair; the monitor implementation deliberately allows barging and even prefers the running thread, so a starving thread waiting on a monitor has no recourse except the unfairness eventually working out statistically.

In the library, ReentrantLock, ReentrantReadWriteLock, and Semaphore take a fairness boolean, and ArrayBlockingQueue exposes it too, since it is built on a ReentrantLock.

The one place I routinely turn it on is a Semaphore used as a bulkhead in front of a slow dependency, because there the cost is dwarfed by the call it guards and I want callers served in arrival order rather than having a few unlucky requests time out repeatedly.

Every other case starts non-fair and stays that way until a measurement argues otherwise.

"If fairness is too expensive, what redesigns remove the starvation instead?"

The redesigns all shrink the hold time or the sharing. Shrinking hold time: move IO and allocation out of the critical section so the lock is held for microseconds, which makes barging harmless because the lock is free almost always.

Reducing sharing: shard the state by key into 16 or 64 independent locks so contention drops by that factor, which is how ConcurrentHashMap and LongAdder approach it.

Changing the primitive: a read-write lock if the starving threads are readers, or a lock-free structure if the operation is a single compare-and-swap.

Changing the shape: replace the lock with a single-writer queue where one thread owns the state and others submit requests, which makes ordering explicit and fair by construction. Any of these usually beats a fair lock on both throughput and latency.

Q201 · Scenario. "Outage at peak: every request thread is blocked waiting on one ReentrantLock, and the owning thread is sitting idle back in the pool, nowhere near that code. What happened?"

Reveal answer

Strong answer This is the leaked-lock outage, and the dump you describe is its signature.

  1. In the thread dump, the waiters show parking to wait for a ReentrantLock, and the "Locked ownable synchronizers" section names the owner — a thread that is alive but idle, with no stack frames anywhere near the locking code. A dead or busy owner would mean a different bug; an idle owner means the thread finished its task while still holding the lock.
  2. That can only happen with an explicit lock:
    • The difference: synchronized releases the monitor automatically when the block exits. ReentrantLock releases only when someone calls unlock().
    • The bug: some code path acquired the lock and then returned early, or threw, before reaching the unlock line.
    • The result: the task ended and the worker went back to the pool. The lock is now held forever by a thread that will never release it, and every subsequent acquirer parks permanently.
  3. Code review then hunts for the two shapes of the bug: an early return between lock() and unlock(), or an unlock() that is not inside finally. Immediate mitigation, unfortunately, is a restart — there is no way to force-release another thread's lock.

The fix and the rule: lock() on its own line immediately before try, unlock() in finally, and nothing that can throw between the two. Prevention: a static-analysis rule for unstructured unlock, and a team preference for synchronized wherever the extra features of ReentrantLock are not actually used.

Picture it The lock state (owner, hold count, wait queue) at successive moments of the outage, and the thread-dump lines that show an idle owner holding the lock.

The setup: a request handler with two ways out that skip the unlock.

Handler.javaruns offline
private final ReentrantLock lock = new ReentrantLock();

void handle(Request r) {
    lock.lock();                      // ❌ TRAP: the unlock below is not guaranteed
    if (r.isCached()) return;         // early return: lock still held
    process(r);                       // may throw: lock still held
    lock.unlock();
}

The trace: the lock state after each event.

lock state over timeruns offline
moment  event                                   owner               holdCount  wait queue
t0      request 41 calls handle(), takes lock   exec-42             1          -
t1      request 41 hits the cache, returns      exec-42 (now idle)  1          -     ✗ never unlocked
t2      request 42 calls lock()                 exec-42 (idle)      1          [exec-7]
t3      more requests arrive                    exec-42 (idle)      1          [exec-7, exec-9, ...]
t4      every request thread parked             exec-42 (idle)      1          all of them

What you see: a dump taken with jcmd PID Thread.print -l: the waiters name the lock, and the idle pool thread owns it.

thread dump excerptruns offline
# illustrative output
"http-nio-8080-exec-7" ... WAITING (parking)
        - parking to wait for  <0x00000007a1c3e480> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
        at com.example.Handler.handle(Handler.java:5)

"http-nio-8080-exec-42" ... WAITING (parking)
        at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java)   <- idle in the pool
   Locked ownable synchronizers:
        - <0x00000007a1c3e480> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)   <- same lock

Why: the lock records its owner in a plain field, and nothing releases it when the task that took it finishes.

The fix: lock() on its own line directly before try, and the unlock in finally.

HandlerFixed.javaruns offline
void handle(Request r) {
    lock.lock();                      // ✅ FIX: lock() immediately before try
    try {
        if (r.isCached()) return;     // finally still runs
        process(r);
    } finally {
        lock.unlock();                // the only release mechanism that exists
    }
}

What you see now: the same lock state after every request has finished.

lock state over timeruns offline
moment  event                              owner  holdCount  wait queue
t1      request 41 returns early           -      0          -     ✓ finally released it
t4      requests 42.. run one at a time    -      0          -     ✓

Land it Explicit locks trade automatic release for features — so every lock() must be structurally paired with a finally unlock(), or one early return takes down the service.

Likely follow-ups
"Restarting loses evidence. Before you restart, how do you prove which code path leaked the lock?"

I take the dump with jcmd PID Thread.print -l, because the -l flag prints the "Locked ownable synchronizers" section that names which thread owns each ReentrantLock. That gives me the owner thread's name, say http-nio-8080-exec-42.

Then I search the request logs for the last request that thread served, using the thread name that most logging patterns print. That request's path is my suspect.

I also enable JFR for a minute and look at jdk.JavaMonitorEnter and jdk.ThreadPark events, which record the lock class and the parking site, so I know exactly which lock object this is.

Only after I have the owner name, the last request, and the lock class do I restart.

If the service is one of many pods, I drain this pod from the load balancer instead of killing it, so the frozen state is preserved for a heap dump later.

"Why can't the JVM just release the lock when the thread finishes its task?"

Because the JVM has no idea that the task is finished. A ReentrantLock is an ordinary Java object built on AbstractQueuedSynchronizer; it records the owner thread and a hold count in plain fields. Nothing ties it to the lifetime of a Runnable.

The pool thread that ran the task is still alive, so from the lock's point of view the owner is perfectly healthy and might unlock at any moment.

Contrast that with synchronized, where the monitor is tied to a bytecode block: the JVM emits a monitorexit on every exit path, including exceptional exits, so release is structural.

Java 21 and later still make no attempt to release explicit locks on task completion, and a pool cannot do it either, because it does not know which locks a task took.

That is exactly why the finally block is not optional style; it is the only release mechanism that exists.

"What if the hold count was greater than one — does the same bug apply?"

Yes, and it is sneakier. A reentrant lock counts holds: if a method locks, calls another method that locks again, and both unlock, the count goes two, one, zero.

If the inner method unlocks in finally but the outer one leaks on an early return, the count ends at one and the lock is still held.

hold count over timeruns offline
outer lock()               holdCount=1
  inner lock()             holdCount=2
  inner unlock() (finally) holdCount=1
outer returns early        holdCount=1   ✗ still owned; getHoldCount() should print 0 here

In the dump, the owner shows as holding the lock, and there is no clue that it was acquired twice. I would check this by calling getHoldCount() in a debug log at the end of the request in a test environment, expecting zero.

A neater prevention is to never let a method both take the lock and call other code that may take it; keep the locked region small and leaf-level, so hold counts are always exactly one and the pairing is easy to audit by eye.

"How would you make this class of bug impossible in a greenfield design?"

Three moves. First, wrap the lock in a helper that takes a lambda: withLock(lock, () -> ...) does lock, try, run, finally unlock, so callers can never forget the release.

Second, prefer synchronized unless I genuinely need tryLock with a timeout, interruptible acquisition, fairness, or multiple conditions. As of Aug 2026, with JDK 24 and later no longer pinning virtual threads inside synchronized blocks, the old "use ReentrantLock for Loom" reason has largely gone away.

Third, add a static analysis rule; Error Prone and SpotBugs both flag an unlock() that is not inside a finally, and I make it a build failure.

On top of that I add a metric: a gauge on lock.getQueueLength() for any lock on a hot path, alerting when waiters stay above zero for more than a few seconds.

Q202. "Explain compare-and-swap in plain words, and how AtomicInteger.incrementAndGet actually works."

Reveal answer

Strong answer CAS — compare-and-swap — is a single instruction the CPU (central processing unit) executes atomically. In plain words it says: "if this memory location still holds the value I expect, replace it with my new value; either way, tell me whether I succeeded."

On x86 hardware it is the lock cmpxchg instruction. incrementAndGet is an optimistic retry loop built on it: read the current value, compute current plus one, then CAS from the old value to the new.

If another thread incremented in between, my expected value no longer matches, the CAS fails, and I simply loop — re-read, re-add, retry. No thread ever blocks and the scheduler is never involved; losers just try again, which under low contention almost never happens.

The atomic classes also give the same visibility guarantees as a volatile variable, so the updated value is seen by all threads.

Picture it Two threads incrementing the same counter: the plain read-modify-write loses an update, and the CAS retry loop shows the loser trying again.

The setup: two threads each add 100,000 to a shared counter, first as a plain int.

Counter.javaruns offline
static int count = 0;                       // ❌ TRAP: count++ is read, add, write
static final AtomicInteger atomic = new AtomicInteger();

Runnable r = () -> { for (int i = 0; i < 100_000; i++) { count++; atomic.incrementAndGet(); } };
// run r on two threads, join both, print count and atomic

What you see: the plain counter is short; the atomic one is exact.

consoleruns offline
# illustrative output
plain  count = 138204     <- expected 200000
atomic count = 200000

Why: two threads can read the same value, both add one, and both write the same result, so one increment vanishes.

The trace: the CAS retry loop from the code block under Going deeper, with two threads and the counter at 5.

thread interleavingruns offline
step  thread A                          thread B                          memory value
1     prev = get() -> 5                                                    5
2                                        prev = get() -> 5                 5
3                                        next = 6; CAS(5 -> 6)  ✓          6
4     next = 6; CAS(5 -> 6)  ✗ (value is now 6, not 5)                    6
5     loop: prev = get() -> 6                                              6
6     next = 7; CAS(6 -> 7)  ✓                                             7   <- both increments counted

What you see now: the failed CAS in step 4 is the whole story: A noticed the change and redid its work, so nothing was lost and nobody blocked.

Going deeper As of Aug 2026 the atomic classes no longer loop in Java at all for the plain increment.

AtomicInteger.incrementAndGet calls Unsafe.getAndAddInt, which the JIT compiler recognises as an intrinsic and compiles straight to lock xadd on x86, a single fetch-and-add instruction with no retry loop.

The CAS retry loop still exists for the general case, such as updateAndGet with an arbitrary lambda, and for getAndAddInt on the interpreter path.

On ARM64 the same call becomes an ldadd instruction when the LSE extension is present, or a load-exclusive, store-exclusive loop on older cores.

The lock prefix is what makes the operation atomic across cores. It holds the cache line in the exclusive state for the duration.

It also acts as a full memory fence, which is why atomics give you volatile-strength visibility for free.

compare-and-swap, and what incrementAndGet really doesruns offline
// CAS is one atomic hardware instruction: "if this address still holds the
// value I expect, replace it; otherwise tell me it changed."
// x86: LOCK CMPXCHG.  AArch64: LDXR/STXR pair.

// incrementAndGet is a retry loop around it:
public final int incrementAndGet() {
    int prev, next;
    do {
        prev = get();                       // read the current value
        next = prev + 1;                    // compute the new one
    } while (!compareAndSet(prev, next));   // publish it ONLY if nothing changed
    return next;
}

// Result: under low contention, one iteration, ~20 cycles, no context switch, no lock.
// ❌ TRAP: under high contention, many failed iterations. Every failure is wasted work
// AND a cache-line invalidation for every other core -> throughput can fall
// BELOW a lock, because a lock at least parks the losers instead of spinning.
// That is exactly why LongAdder exists (Q204).

// THE ABA PROBLEM (Q203): CAS compares the VALUE, not the history.
//   Thread 1 reads head = A
//   Thread 2 pops A, pops B, pushes A back    -> head is A again, list changed
//   Thread 1's CAS(A -> ...) SUCCEEDS, and links to a node that was removed.
// For a value counter ABA is harmless. For a lock-free stack of NODES it is a
// corruption bug.
// ✅ FIX: a versioned reference:
AtomicStampedReference<Node> head = new AtomicStampedReference<>(null, 0);
head.compareAndSet(expectedRef, newRef, expectedStamp, expectedStamp + 1);

ABA is the reason hand-rolled lock-free data structures are so hard. The CAS succeeds and the code is wrong, with no exception and no obvious symptom — which is why the honest answer to "should we write one" is almost always to use java.util.concurrent instead.

Land it CAS replaces "lock, change, unlock" with "attempt, and retry if someone beat me" — optimism that wins whenever contention is the exception rather than the rule.

Likely follow-ups
"What happens to CAS throughput as you add threads, and why?"

It gets worse, not better, past a small number of threads. Every CAS needs the cache line holding the variable in the exclusive state on the core that executes it.

With sixteen cores hammering one AtomicLong, that 64-byte line bounces between cores on every operation, and each bounce costs on the order of 50 to 100 nanoseconds of coherence traffic.

Meanwhile any thread whose CAS fails has to re-read and retry, so under contention a large share of the work is wasted attempts.

In a simple benchmark, a single thread can do a few hundred million increments a second, and sixteen threads on one counter often do fewer total operations than one thread.

That is the whole reason LongAdder exists: it spreads the counter over multiple cache lines so each core mostly touches its own.

"Is CAS lock-free, wait-free, or neither?"

A CAS loop is lock-free but not wait-free. Lock-free means the system as a whole always makes progress: if my CAS fails, it failed because someone else's succeeded, so at least one thread advanced.

Wait-free is stronger, meaning every individual thread finishes in a bounded number of steps, and a CAS loop cannot promise that, because an unlucky thread could in theory lose every race forever.

In practice starvation is not a real concern for counters, but it matters for the guarantee you claim in a design review. The single-instruction fetch-and-add that the JIT emits for a plain increment is wait-free, since there is no retry.

Lock-free also has a practical benefit beyond speed: a thread that is descheduled by the operating system mid-operation does not block anyone, whereas a thread preempted while holding a lock stalls every waiter.

"How would you build your own CAS on a field without using the Atomic classes?"

I would use a VarHandle, which since JDK 9 is the supported replacement for sun.misc.Unsafe and for the older AtomicIntegerFieldUpdater.

I declare the field volatile int state, obtain the handle once in a static initializer with MethodHandles.lookup().findVarHandle(MyClass.class, "state", int.class), and then call STATE.compareAndSet(this, expected, next) in a loop.

The advantage over a separate AtomicInteger object is memory: one int in the owning object rather than an extra 16-byte object and a pointer per instance, which matters when there are millions of instances, and it is exactly how ConcurrentHashMap and AbstractQueuedSynchronizer are written internally.

VarHandle also gives me the weaker access modes, such as getAcquire and setRelease, when I want to shave the cost of a full fence.

"When would you deliberately not use CAS and take a lock instead?"

When the critical section touches more than one variable, or does anything that must not be retried.

CAS protects a single word, so a state change that must update two fields together cannot be expressed as one CAS unless I pack both into one immutable object and CAS the reference, which is fine for small state and terrible for large.

I also avoid CAS loops when the work inside the loop is expensive, because losing the race means throwing that work away; a lock serialises but never wastes.

And I take a lock when I need to wait for a condition, because a CAS loop cannot block; it can only spin, and spinning burns a core.

The honest rule: CAS for counters, flags, single-reference publication and small immutable state; a lock for multi-field invariants and for anything that needs to wait.

Q203 · Scenario. "A team built a lock-free stack using AtomicReference and compare-and-swap on the head pointer. Under heavy load with node reuse, it occasionally corrupts. What is the classic cause?"

Reveal answer

Strong answer This is the ABA problem, and it lives in the gap between what CAS checks and what we mean.

  1. CAS only verifies that the value is still what I read earlier. In plain words, it asks "does this look unchanged?" — not "did nothing happen here?"
  2. The failing interleaving: my thread reads head A and A's next pointer, planning to CAS the head to next. Before my CAS runs, another thread pops A, pops or pushes other nodes, and then pushes A back — the head went A to B and back to A. Because the team reuses node objects, the very same reference is on top again.
  3. My CAS now succeeds — the head "looks" like the A I saw — but the stack underneath was rebuilt, and the next pointer I captured earlier is stale. Installing it silently drops or resurrects nodes: intermittent corruption that only appears under load, exactly as described.

There are two fixes:

  • Version the reference: AtomicStampedReference pairs the reference with an integer stamp, a version counter bumped on every change. A recycled A carries a new stamp, so the stale CAS fails as it should.
  • Stop reusing nodes: with fresh allocations, GC (garbage collection) ensures a reachable old reference cannot be reincarnated. That is why ABA bites far less in idiomatic Java than in C, and why an object pool quietly reintroduces it.

Picture it A stack of three nodes before and after the ABA interleaving, then the same interleaving with a version stamp, step by step.

The setup: a lock-free (Treiber) stack whose pop CASes the head, with nodes recycled through a pool.

Stack.javaruns offline
final AtomicReference<Node> head = new AtomicReference<>();

Node pop() {
    Node oldHead, next;
    do {
        oldHead = head.get();
        if (oldHead == null) return null;
        next = oldHead.next;                         // captured BEFORE the CAS
    } while (!head.compareAndSet(oldHead, next));    // ❌ TRAP: compares identity only
    return oldHead;
}

Make the invisible visible: the stack at the moment thread 1 reads, and when its CAS runs.

memory pictureruns offline
stack when T1 reads                 stack when T1's CAS runs (after T2's work)
head -> A -> B -> C                 head -> A -> C          B was popped and handed to a consumer
T1 holds: oldHead=A, next=B         T1 CAS(head, A, B): head is A again, so it SUCCEEDS  ✗
                                    result: head -> B -> C   B is back on the stack, though a consumer owns it

The trace: one line per step, first with the plain reference and then with a stamp.

thread interleavingruns offline
step  actor  action                                   plain reference         AtomicStampedReference
1     T1     read head=A, next=B                      head=A                  (A, stamp 0)
2     T2     pop A                                    head=B                  (B, 1)
3     T2     pop B (consumer keeps it)                head=C                  (C, 2)
4     T2     push A back (node reused, A.next=C)      head=A                  (A, 3)
5     T1     CAS expects A, installs B                ✗ SUCCEEDS, B resurrected   ✓ FAILS (stamp 0 != 3), T1 retries

What you see: no exception: a consumer and the stack both hold node B, and later pops hand B out twice.

consoleruns offline
# illustrative output
popped: [A, B, C]  then later  popped: [B, C]   <- B and C delivered twice

The fix: read the stamp with the reference and bump it on every update.

StackFixed.javaruns offline
final AtomicStampedReference<Node> head = new AtomicStampedReference<>(null, 0);

Node pop() {
    int[] stamp = new int[1];
    Node oldHead, next;
    do {
        oldHead = head.get(stamp);                   // reference and stamp together
        if (oldHead == null) return null;
        next = oldHead.next;
    } while (!head.compareAndSet(oldHead, next, stamp[0], stamp[0] + 1));   // ✅ FIX
    return oldHead;
}

Land it CAS checks identity, not history — when values can be recycled, you must version them, which is exactly what AtomicStampedReference exists for.

Likely follow-ups
"Why does ordinary garbage collection make ABA rare in Java, and what exactly reintroduces it?"

In Java a reference I hold keeps the object alive. While my thread still has a local variable pointing at node A, the collector cannot reclaim A, so no other thread can allocate a fresh object at the same address that would compare equal by identity.

A brand new node pushed onto the stack is always a different reference from my stale A, so my CAS correctly fails.

What reintroduces ABA is any scheme that hands the same object back into circulation: an explicit object pool, a free list, a recycled buffer, or an entity cache keyed by ID that returns the same instance.

Then A really can be popped, reused, and pushed again as the same reference. So my first review question for any lock-free structure is "does anything recycle these nodes?" If the answer is no, the JVM's memory management is doing the version stamping for me.

"What does AtomicStampedReference cost, and is there a cheaper alternative?"

It costs an allocation per successful update, because the reference and the stamp are stored together in an immutable pair object, and a CAS replaces the whole pair.

Under heavy churn that means garbage on every push and pop, which is the same allocation pressure the team was trying to avoid by reusing nodes.

The cheaper alternative is to put the version counter inside the node itself and CAS a packed long, or to accept allocation and stop reusing nodes at all; the JVM's young-generation collector handles short-lived nodes cheaply, typically a few nanoseconds per allocation.

There is also AtomicMarkableReference, a one-bit variant used for logical deletion in lock-free lists. My honest recommendation is usually to stop hand-rolling: ConcurrentLinkedDeque is a tested lock-free structure that already handles these cases.

"The stamp fix went in, and corruption still happens. What next?"

Then ABA was not the only bug, and I would stop reasoning by intuition and use a tool.

I extract the stack into a jcstress test, which is OpenJDK's harness that runs a few lines of concurrent code across millions of interleavings and reports every outcome seen. Two candidate causes remain.

First, the stamp wraps: an int stamp bumps four billion times and can, in theory, match a stale value again, which is a real problem only at absurd rates.

Second, a publication race in the node itself: the pusher writes node.next as a plain field and CASes the head, and a reader on another core sees the new head before the write to next, because a plain write has no ordering guarantee relative to the CAS. Making next volatile, or using a VarHandle release store, fixes that.

"How do you test a lock-free structure so that this is caught before production?"

Ordinary unit tests will never catch it; they run one interleaving. I write a jcstress test that pushes and pops with node reuse from several actor threads, declares the expected outcomes, and runs for a few minutes on a multi-core box.

jcstress forces the interesting interleavings by running the actors in tight loops with randomised delays.

I also run the structure under a stress harness with a CountDownLatch start gun and a checksum: every thread records what it pushed and popped, and at the end the multiset of pushed values must equal the multiset of popped values plus what remains.

A single lost or duplicated node fails the assertion.

stress harness failureruns offline
# illustrative output
pushed   = {1 .. 1000}
popped   = {1 .. 999}, remaining = {}      // ✗ value 417 vanished
AssertionError: pushed multiset != popped + remaining

Finally I run the whole suite with -XX:+UseParallelGC and also with a small heap to change allocation timing, because ABA-style races are timing sensitive.

Q204. "LongAdder versus AtomicLong — when do you use which, and what do you give up?"

Reveal answer

Strong answer With AtomicLong, every thread CASes the same single memory word.

Under heavy contention — dozens of threads incrementing a hot counter — most CAS attempts fail and retry, and the cache line holding that word ping-pongs between cores, so throughput actually degrades as you add threads.

LongAdder fixes this with striping: it spreads the total across multiple internal cells, each thread hashes to its own cell and increments there with almost no contention, and sum() adds the cells up on demand. Writes scale nearly linearly.

What I give up is read precision: sum() is not an atomic snapshot — increments landing during the sum may or may not be included — and there is no compareAndSet on the total.

That trade is perfect for metrics counters like requests served, where the value is monotonically climbing and an instantaneous read being off by a handful is meaningless; it is wrong when logic branches on an exact current value.

Picture it The memory behind one hot AtomicLong versus a LongAdder with a base and padded cells, and what sum() reads while writers keep adding.

The setup: sixteen threads incrementing one hot counter.

HotCounter.javaruns offline
static final AtomicLong hits = new AtomicLong();   // ❌ TRAP: one word, one cache line, 16 cores

void onRequest() { hits.incrementAndGet(); }     // CAS loop on the same word

Make the invisible visible: where each thread writes in both designs.

memory pictureruns offline
AtomicLong                         LongAdder (after contention appears)
 T1 T2 T3 T4 ... T16                T1      T2      T3      T4 ...
  \  \  |  /     /                  |       |       |       |
   [ value: 8,401,337 ]              [base 0] [cell0] [cell1] [cell2] [cell3]
   one 64-byte line bounces          each cell on its own padded cache line (@Contended)
   between 16 cores                  sum() = base + cell0 + cell1 + cell2 + cell3

The trace: a sum() call that overlaps with writers.

thread interleavingruns offline
step  reader: sum()            writer on cell1          running value
1     read base      -> 0                              base 0, cell0 5, cell1 7
2     read cell0     -> 5
3                                  cell1 += 1  -> 8    cell1 not read yet: this increment will be INCLUDED
4     read cell1     -> 8                              included
5                                  cell0 += 1  -> 6    cell0 already read: this increment is MISSED
6     sum returns 0+5+8 = 13                           true total now 14; 13 lies between the start total (12) and the end total (14)

What you see: throughput of the same loop as threads are added.

JMH-style throughput, AtomicLongruns offline
# illustrative output
Benchmark            threads   ops/us
AtomicLongBench           1      110
AtomicLongBench           4       40
AtomicLongBench          16       20   <- adding threads made it slower

Why: every CAS needs the one cache line exclusively, so the line ping-pongs and failed CASes are retried.

The fix: a LongAdder for a number that is reported, not decided on.

HotCounterFixed.javaruns offline
static final LongAdder hits = new LongAdder();    // ✅ FIX: striped cells

void onRequest() { hits.increment(); }
long report()    { return hits.sum(); }          // approximate snapshot, fine for a metric

What you see now: the same benchmark layout.

JMH-style throughput, LongAdderruns offline
# illustrative output
Benchmark            threads   ops/us
LongAdderBench            1      105   <- no gap at one thread
LongAdderBench            4      390
LongAdderBench           16     1400   <- scales with threads

Land it Write-heavy, read-occasionally, precision-tolerant — that is LongAdder; the moment you need an exact read or CAS on the total, you are back to AtomicLong.

Likely follow-ups
"How does LongAdder decide how many cells to use, and what stops false sharing between them?"

It starts with no cells at all and a single base field, so an uncontended adder is as cheap as an AtomicLong.

Only when a CAS on the base fails does it create a cells table.

The table starts at two entries and doubles on further contention, capped at the number of CPUs.

Each thread is routed to a cell by a per-thread probe value stored in Thread.threadLocalRandomProbe, and if a thread keeps colliding, the probe is rehashed so the thread moves to a different cell.

The false-sharing problem, where two cells on the same 64-byte cache line would still bounce between cores, is solved by annotating the cell class with @jdk.internal.vm.annotation.Contended, which makes the JVM pad each cell to its own cache line.

That padding is why a fully expanded adder on a 32-core box costs a couple of kilobytes, which is fine for a metric and wasteful for a per-object counter.

"What does sum() actually guarantee, and how would that bite in a rate limiter?"

sum() reads the base and every cell one after another, with no lock and no snapshot. If increments land on a cell it has already read, they are missed; if they land on one it has not reached yet, they are included.

So the result is any value between the true total at the start of the call and the true total at the end. For a metric that is fine.

For a rate limiter it is not: a check like "if sum() is below 1000 then allow" can let several threads through at once, because each reads a slightly stale total and none of them can atomically reserve their slot.

A limiter needs a single CAS on the value, which means AtomicLong, or better a proper token-bucket implementation such as Bucket4j.

rate limiter raceruns offline
limit = 1000, sum() = 999 for threads T1 and T2 at the same moment
T1: sum() < 1000 -> allow, add(1)     ✓
T2: sum() < 1000 -> allow, add(1)     ✗ total is now 1001; neither could reserve a slot atomically

The rule I state: LongAdder is for numbers you report, AtomicLong is for numbers you decide on.

"How would you verify that AtomicLong contention is actually the bottleneck rather than guessing?"

I would profile before swapping. With async-profiler in CPU mode, contended CAS shows up as time inside Unsafe.getAndAddLong or the intrinsic frame, wide in the flame graph and spread across many request stacks.

A stronger signal is hardware counters: asprof -e cache-misses attributes cache-line traffic to the frame, and a hot counter lights up.

Then I write a JMH benchmark with @Threads(16) comparing the two classes on the same box, expecting a roughly ten-fold throughput gap under contention and no gap at one thread. Finally I confirm in production by watching CPU per request drop after the change.

Without that chain of evidence I might be optimising a counter that is incremented a hundred times a second, where the difference is unmeasurable.

"Are there other striped classes, and when would you use LongAccumulator?"

Yes, the same striping lives in LongAccumulator and DoubleAdder. LongAccumulator takes a binary operator and an identity, so new LongAccumulator(Long::max, Long.MIN_VALUE) tracks a running maximum with the same per-cell contention relief; each cell holds a partial maximum and get() folds them.

The operator must be commutative and associative, because cells are combined in an unspecified order, so max, min, sum and bitwise-or work, and subtraction does not. I use it for "largest payload seen" or "highest queue depth this minute" style gauges.

The same design is also inside ConcurrentHashMap, whose size counter is a private copy of the adder logic, which is why size() on a busy map is an estimate.

Q205. "What does volatile give you that AtomicInteger doesn't — and the other way around?"

Reveal answer

Strong answer volatile gives visibility and ordering only: a write to a volatile field is guaranteed to be seen by subsequent reads from any thread, with no stale cached values.

What it does not give is atomicity of compound operations — count++ on a volatile is still three separate steps, read, add, write, and two threads can interleave those and lose an update.

AtomicInteger includes the same visibility guarantees and adds atomic read-modify-write on top: incrementAndGet, compareAndSet, getAndUpdate. Each is an indivisible operation backed by CAS.

So the choice is by write pattern:

  • One writer, many readers: a shutdown flag or a swapped-in config snapshot is a clean volatile.
  • Many writers: a value that several threads modify concurrently needs an atomic.

There is nothing an atomic "costs" over volatile for plain reads and writes; it simply carries the extra operations for when you need them.

Picture it Two threads running count++ on a volatile field, step by step, and a table of which common write patterns each tool handles.

The setup: a hit counter declared volatile, incremented from two threads.

VolatileCounter.javaruns offline
static volatile int count = 0;      // ❌ TRAP: visible, but count++ is still three steps
static final AtomicInteger safe = new AtomicInteger();

void hit() { count++; safe.incrementAndGet(); }

Make the invisible visible: what the compiler turns count++ into.

what the compiler generatesruns offline
int tmp = count;     // 1. read   (volatile read: sees the latest value)
tmp = tmp + 1;       // 2. add    (private to this thread)
count = tmp;         // 3. write  (volatile write: published, but may overwrite a newer value)

The trace: two threads interleave those three steps.

thread interleavingruns offline
step  thread A            thread B            count
1     read  -> 0                              0
2                        read  -> 0           0
3     write 1                                 1
4                        write 1              1   ✗ two increments, count went up by one

What you see: the volatile counter loses updates; the atomic one does not.

consoleruns offline
# illustrative output (2 threads x 100000 hits)
volatile count = 151337     <- expected 200000
atomic   safe  = 200000     ✓

Why: volatile makes each single read and write visible, but nothing makes the three steps one unit.

Which tool fits which write pattern
PatternvolatileAtomicInteger
running = false from one thread, read by manyWorksWorks (more than needed)
count++ from many threadsSilently wrong: lost updatesWorks
if (x == 0) x = 1 from many threadsSilently wrong: both may pass the checkWorks with compareAndSet(0, 1)
Swap in a new immutable config objectWorksWorks (AtomicReference)

Land it Volatile solves "do others see my write?"; atomics additionally solve "can two of us modify it without losing an update?" — pick by whether the variable has one writer or many.

Likely follow-ups
"Is a volatile long or double atomic? Where does that rule come from?"

Yes. The Java Language Specification, section 17.7, allows a plain non-volatile long or double to be written as two separate 32-bit halves, so a reader could in theory see the top half of one write and the bottom half of another.

Declaring the field volatile removes that permission and requires a single atomic 64-bit read and write.

On every 64-bit HotSpot build the plain write is already atomic in practice, so the tearing only ever happened on old 32-bit JVMs, but the specification still only promises it for volatile.

Note that this is atomicity of a single read or a single write, not of a read-modify-write: volatileLong++ is still three steps and still loses updates. For that I still need AtomicLong or a VarHandle compare-and-set.

"Does volatile prevent the compiler from reordering other, non-volatile writes?"

Partly, and the direction matters. A volatile write has release semantics: every write before it in program order, volatile or not, must be visible to any thread that later reads that volatile and sees the new value.

A volatile read has acquire semantics: no read or write after it may be moved before it.

This is the happens-before edge, and it is the reason the classic pattern of filling an object and then setting a volatile ready flag works: the reader that sees ready == true is guaranteed to see the filled fields.

What volatile does not do is order two unrelated volatile writes on different threads with respect to each other, and it does not turn a sequence of several writes into a transaction; another thread can observe them one at a time.

If I need the multi-field state to appear all at once, I publish an immutable object through one volatile reference.

"When would you use VarHandle access modes instead of volatile, and what would you gain?"

When I have measured that a full fence is too expensive on a hot path. Volatile on x86 makes writes emit a locked instruction or a fence, costing roughly 20 to 40 cycles, and on ARM64 it emits full barriers.

A VarHandle lets me pick a weaker mode: setRelease plus getAcquire gives me the one-way ordering that publication needs without the total ordering across all volatile accesses, and setOpaque only guarantees the write eventually becomes visible with no ordering at all, which suits a progress counter read by a monitoring thread.

The gain is real in tight loops, a few nanoseconds per access, and invisible almost everywhere else.

I state the honest boundary: I use these modes only in library-style code, with a jcstress test proving the weaker ordering is still correct, because a mistake here is a race that reproduces once a week.

"Why is AtomicReference plus an immutable snapshot often better than several volatile fields?"

Because it gives me consistency across fields, which volatile fields cannot. If a configuration has a host and a port in two volatile fields, a reader can see the new host with the old port during a reload.

torn configurationruns offline
reload thread:  host = "db2";     port = 5433;
reader thread:             reads host="db2", port=5432   ✗ a pair that never existed

If instead I build an immutable Config record and store it in one AtomicReference, every reader sees either the whole old config or the whole new one.

It also enables safe compound updates: ref.updateAndGet(c -> c.withRetries(c.retries() + 1)) retries the CAS until it wins, so two concurrent updaters never lose each other's change.

The price is an allocation per update and the rule that the snapshot really is immutable, which records make easy to guarantee. This is the pattern I reach for by default whenever shared state has more than one field.

Q206. "CountDownLatch versus CyclicBarrier — and where would you actually use each in a concurrency test?"

Reveal answer

Strong answer The difference is who waits for whom, and whether the gate reopens.

A CountDownLatch is a one-shot countdown:

  • Workers call countDown() and continue without waiting.
  • Dependents call await() and block until the count hits zero. One group is waiting on events from another.
  • One shot: once at zero the latch is spent forever.

A CyclicBarrier is peers waiting for peers:

  1. Arrive: N parties each call await() and block.
  2. Trip: when the Nth arrives, all are released together, optionally after a barrier action runs.
  3. Reset: the barrier resets for the next round.

Concrete test harness: to hammer a class with true simultaneity, I create a start latch of one — every worker awaits it, the main thread calls countDown() once to fire all workers at the same instant — plus a done latch of N that main awaits before asserting.

A barrier fits a multi-round simulation where every thread must finish round k before any begins round k+1.

Picture it The counts of a start-gun latch and a done latch at successive moments, one barrier round, and a table comparing the two.

The setup: a test harness with a start latch of one and a done latch of three.

RaceHarness.javaruns offline
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done  = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
    new Thread(() -> {
        start.await();                 // all workers park here (InterruptedException handling omitted)
        work();                        // ❌ TRAP: if this throws, the next line never runs
        done.countDown();
    }, "worker-" + i).start();
}
start.countDown();                     // fire all workers
done.await();                          // ❌ TRAP: waits forever if a worker died

The trace: the latch counts after each event when all workers succeed.

latch counts over timeruns offline
moment  event                           start  done  workers
t0      3 workers call start.await()    1      3     W0 W1 W2 parked
t1      main: start.countDown()         0      3     all released together
t2      W0 finishes, done.countDown()   0      2
t3      W1 finishes                     0      1
t4      W2 finishes                     0      0     main's done.await() returns  ✓

Make the invisible visible: one barrier round with three peers: the barrier resets, the latch never does.

barrier roundruns offline
round 1:  W0 await() [1/3 waiting]  W1 await() [2/3]  W2 await() [3/3] -> trips, all released  ✓
          barrier resets to 0/3 waiting
round 2:  W0 await() [1/3 waiting] ...                              (a latch at zero cannot do this)

What you see: what happens when one worker throws before countDown().

consoleruns offline
# illustrative output
worker-1: java.lang.IllegalStateException at RaceHarness.work(...)
[build hangs]   "main" WAITING at java.util.concurrent.CountDownLatch.await   <- done is stuck at 1

The fix: count down in finally, record the failure, and wait with a timeout.

RaceHarnessFixed.javaruns offline
AtomicReference<Throwable> failure = new AtomicReference<>();
// in each worker:
try { work(); }
catch (Throwable t) { failure.compareAndSet(null, t); }
finally { done.countDown(); }                         // ✅ FIX: always counts down

// in main:
assertTrue(done.await(10, TimeUnit.SECONDS), "workers did not finish");   // ✅ FIX: bounded wait
assertNull(failure.get());

What you see now: a clear failure instead of a hang.

consoleruns offline
# illustrative output
AssertionError: worker-1 failed: java.lang.IllegalStateException   <- test fails in milliseconds
CountDownLatch versus CyclicBarrier
QuestionCountDownLatchCyclicBarrier
Who waits for whom?Dependents wait for workersPeers wait for each other
Reusable?No: spent at zeroYes: resets after each trip
If one party never arrivesInfinite wait (use a timeout)Waiters time out or break: BrokenBarrierException
Typical test useStart gun and done signalMulti-round simulation

Land it Latch is one-shot and asymmetric — waiters versus counters; barrier is reusable and symmetric — peers releasing each other — and the test-harness start-gun is the latch's signature use.

Likely follow-ups
"What happens if one worker throws before calling countDown, and how do you keep the test from hanging forever?"

The count never reaches zero and the awaiting thread blocks forever, which turns one failing worker into a hung build. Two fixes.

First, every worker calls countDown() in a finally block, so the latch is released whether the task succeeded or threw, and the failure is recorded separately in an AtomicReference<Throwable> or a concurrent list that the main thread asserts on afterward.

Second, the main thread never uses the plain await(); it uses await(10, TimeUnit.SECONDS) and asserts the boolean it returns, so a stuck worker fails the test with a clear message instead of hanging.

I also name the worker threads, so if the timeout fires, the thread dump JUnit prints names which ones did not arrive. The same finally-countDown rule applies to a barrier, where a missing arrival stalls every peer.

"What does a CyclicBarrier do when one party fails or is interrupted?"

It breaks. If any waiting thread is interrupted, times out, or the barrier is reset, every other thread currently waiting gets a BrokenBarrierException, and every later await() fails immediately until someone calls reset().

That is deliberate: a barrier is a promise that all parties will arrive, and once that promise cannot be kept, waiting any longer would be a silent hang.

barrier breakingruns offline
W0 await()  -> interrupted: throws InterruptedException, barrier is now broken
W1 await()  -> throws BrokenBarrierException     (was already waiting)
W2 await()  -> throws BrokenBarrierException     (arrives later, fails immediately)
# every later await() fails the same way until reset() is called

So in a multi-round simulation I catch BrokenBarrierException at each await, record which round broke, and abort the run rather than reset and continue, because the data from a half-completed round is unreliable.

In contrast, a latch cannot break; a missing countDown is just an infinite wait, which is exactly why I always pair latch waits with a timeout.

"Is a start latch really simultaneous? How close together do the threads actually start?"

Not perfectly. When the main thread counts down to zero, the latch unparks the waiting threads one at a time, and the operating system schedules them onto cores over the next few microseconds to a few hundred microseconds depending on core count and load.

So the first few workers are running before the last one has been unparked. For most race hunting that window is small enough, because the interesting operations take longer than that.

When I need tighter alignment I have each worker spin on a volatile flag for the last stretch instead of parking, which shrinks the skew to nanoseconds at the cost of a burning core per thread, and I make sure the worker count does not exceed the core count so every thread really is runnable at once.

jcstress does essentially this internally, which is why it finds interleavings a latch harness misses.

"What would you use instead of these in Java 21 code?"

For the "wait for all subtasks" case, structured concurrency. A StructuredTaskScope forks subtasks and join() waits for all of them, with cancellation of the rest if one fails, which replaces the done latch and also handles the error propagation a latch ignores.

For the start gun I still use a latch, because nothing else expresses "release everyone at once" more clearly. For a simple one-shot "result is ready" signal I use a CompletableFuture, since it carries the value and the exception, not just the count.

As of Aug 2026 structured concurrency is still a preview API in JDK 25, so in production code I use it only where the team has agreed to enable preview features, and otherwise a latch with a timeout remains my everyday tool.

Q207 · Scenario. "A fragile downstream service falls over if we send it more than 20 concurrent calls. How do you enforce that limit inside your service?"

Reveal answer

Strong answer This is the textbook job for a Semaphore — a counter of permits where acquire() takes one or blocks until one is free, and release() returns it. It is not a lock: there is no owner, it simply bounds how many threads are inside a section at once.

  1. Create new Semaphore(20) next to the client, acquire before every call, and release in finally — without the finally, a thrown exception leaks a permit and the effective limit silently ratchets down toward zero.
  2. Decide the waiting policy explicitly. Blocking acquire() queues callers, which protects the downstream but lets latency pile up in my service. tryAcquire(50, TimeUnit.MILLISECONDS) fails fast so I can return a fallback or a 503 — usually the right choice in a request path, because bounded failure beats unbounded queueing.
  3. Add a gauge on availablePermits() so saturation is visible before it becomes an incident.
  4. Mention the equivalents: a dedicated 20-thread pool for that client achieves the same bound by construction, and resilience4j's semaphore bulkhead is this exact pattern productized, with metrics included.

Picture it The permit count of a small semaphore (two permits) at successive moments, including the moment one exception leaks a permit forever.

The setup: a downstream call guarded by a semaphore, with the release placed after the call.

Downstream.javaruns offline
private final Semaphore permits = new Semaphore(20);

Response call(Request r) throws Exception {
    permits.acquire();
    Response resp = client.send(r);     // ❌ TRAP: if this throws, the release below is skipped
    permits.release();
    return resp;
}

The trace: the state of a two-permit semaphore as callers come and go, then the failing call.

permit state over timeruns offline
moment  event                                  availablePermits  waiting
t0      Semaphore(2) created                   2                 -
t1      A acquire()                            1                 -
t2      B acquire()                            0                 -
t3      C acquire() parks                      0                 [C]
t4      A release(), C wakes and takes it      0                 -
t5      B's send() throws, release skipped     0                 -     ✗ one permit lost for good
t6      C release()                            1                 -     the limit is now 1, not 2

What you see: a gauge on availablePermits() that ratchets toward zero while the downstream is healthy.

gauge over hoursruns offline
# illustrative output
09:00  availablePermits = 20     idle
12:00  availablePermits = 17     idle      <- should read 20 when no call is in flight
15:00  availablePermits = 9      idle
18:00  availablePermits = 0      every caller parks

Why: a semaphore has no owner, so nothing returns a permit on behalf of a thread that skipped the release.

The fix: release in finally, and fail fast instead of queuing without bound.

DownstreamFixed.javaruns offline
Response call(Request r) throws Exception {
    if (!permits.tryAcquire(50, TimeUnit.MILLISECONDS)) {
        throw new BusyException();                   // map to a 503 or a fallback
    }
    try {
        return client.send(r);
    } finally {
        permits.release();                           // ✅ FIX: runs on every exit path
    }
}

What you see now: the same gauge at idle.

gauge over hoursruns offline
# illustrative output
09:00  availablePermits = 20     idle
18:00  availablePermits = 20     idle      ✓ back to the limit whenever no call is in flight

Land it A semaphore is concurrency-limiting in one object — the senior details are the finally-release, the deliberate choice between waiting and failing fast, and a metric on remaining permits.

Likely follow-ups
"You added the semaphore and the downstream still fell over. What did you miss?"

The most common miss is that the bound is per instance and the downstream is shared.

per-instance limitruns offline
12 pods x 20 permits = up to 240 concurrent calls
downstream limit      = 20                          ✗ twelve times over, with every semaphore "working"

Twelve pods each allowing twenty means up to 240 concurrent calls, which is twelve times the limit.

The fix is either to divide the budget, so each pod gets one or two permits, or to move the limit to a shared point: the downstream's own gateway, a sidecar, or a Redis-backed limiter.

The second miss is retries: a request that fails after the semaphore is released and is retried by a layer above adds load the permit count never saw.

The third is a permit leak, where an exception path skips the release; I check with a gauge on availablePermits(), which drifts toward zero over hours if permits are leaking.

And I confirm the downstream counts concurrency the same way I do; if it counts open connections, my connection pool size is the real limit, not my semaphore.

"Should you use a fair semaphore here?"

Usually no, and I would say why.

A fair semaphore, created with new Semaphore(20, true), hands permits out in strict arrival order, which means every acquisition goes through the wait queue even when a permit is free, costing a park and unpark cycle and measurably lower throughput.

The unfair default lets a newly arriving thread grab a permit that just became free, which is faster and only unfair in the sense that a long-waiting thread can be overtaken. For a downstream limiter that overtaking is harmless, because all callers are equivalent requests.

I would turn fairness on only if I could show a thread starving in a dump, that is, a waiter that stays parked on the semaphore across three dumps while others cycle through.

In practice, with fail-fast tryAcquire and a short timeout, starvation is bounded by the timeout anyway.

"How does this compare with Resilience4j's Bulkhead, and which would you actually ship?"

Resilience4j's semaphore Bulkhead is the same Semaphore wrapped with the operational pieces I would otherwise write by hand: a maxConcurrentCalls setting, a maxWaitDuration that is the tryAcquire timeout, a BulkheadFullException that I can map to a 503, Micrometer metrics for available and max concurrent calls, and event listeners for logging.

It also composes with a circuit breaker and a retry in a defined order. So in a Spring Boot service I ship the bulkhead, configured in properties rather than code, because the metrics and the standard exception come free and a new engineer recognises it.

I would hand-roll the semaphore only in a library with no framework dependency, or when I need a permit count that changes at runtime, which I can do with release(n) and reducePermits(n) on a subclass but not with the standard bulkhead configuration.

"What does the semaphore cost the caller when the downstream is healthy?"

Almost nothing. An uncontended acquire is a single CAS on the permit count, tens of nanoseconds, and release is another CAS plus a check for waiters.

The cost appears only when the permits are exhausted: the twenty-first caller parks, which is a system call and a context switch of a few microseconds, and then waits up to the timeout.

The real cost is not CPU but latency accounting, so I make the wait time visible: a timer around the acquire, exported as a histogram, so that I can see the moment the limiter becomes the bottleneck rather than the downstream.

If p99 acquire wait climbs above a few milliseconds I know that either the downstream got slower, so twenty calls take longer to drain, or traffic grew, and either way the conversation with the owning team starts with a number.

Q208. "What is a Phaser, and when would you honestly use one?"

Reveal answer

Strong answer A Phaser is the generalization of latch and barrier, with one distinguishing power: dynamic parties.

Threads can register() and arriveAndDeregister() while the phaser is live, so the number of participants can change between phases. A CyclicBarrier's party count is fixed at construction.

Each phase, participants call arriveAndAwaitAdvance(); when all registered parties have arrived, everyone advances to the next numbered phase together.

My honest answer is that in nine years I have reached for it approximately never: it fits multi-stage computations where workers join and leave between stages — an elastic fork-join-style pipeline — and almost everything else is served more readably by a latch, a barrier, or an executor.

I would rather say that plainly than pretend it is an everyday tool; knowing the boundary of a tool's usefulness is part of knowing the tool.

Picture it The phase number, registered parties and unarrived parties of one phaser at successive moments as three readers leave and two transformers wait.

The setup: three readers and two transformers share one phaser; readers leave after stage 0, transformers wait for it to finish.

Pipeline.javaruns offline
Phaser phaser = new Phaser(5);                    // 3 readers + 2 transformers registered

// reader (done for good after stage 0)
read();
phaser.arriveAndDeregister();                     // arrives and drops out of later phases

// transformer
phaser.arriveAndAwaitAdvance();                   // blocks until all 5 have arrived
transform();                                      // now in phase 1

The trace: the phaser state after each arrival.

phaser state over timeruns offline
moment  event                              phase  registered  unarrived
t0      new Phaser(5)                      0      5           5
t1      R1 arriveAndDeregister()           0      4           4
t2      R2 arriveAndDeregister()           0      3           3
t3      R3 arriveAndDeregister()           0      2           2
t4      T1 arriveAndAwaitAdvance()         0      2           1     T1 parks
t5      T2 arriveAndAwaitAdvance()         1      2           2     last arrival: advance, T1 and T2 released  ✓
# a CyclicBarrier(5) could not shrink to 2 parties between rounds

What you see: what a reader that throws before deregistering leaves behind.

thread dump excerptruns offline
# illustrative output (frame names abridged)
"transformer-1" WAITING at java.util.concurrent.Phaser.internalAwaitAdvance
"transformer-2" WAITING at java.util.concurrent.Phaser.internalAwaitAdvance
# phaser.getUnarrivedParties() == 1   <- the reader that died; phase stays at 0 forever

The fix: deregister in finally and wait with a timeout.

PipelineFixed.javaruns offline
try { read(); }
finally { phaser.arriveAndDeregister(); }          // ✅ FIX: a dying reader still leaves

int phase = phaser.arrive();                       // transformer arrives without blocking
phaser.awaitAdvanceInterruptibly(phase, 30, TimeUnit.SECONDS);   // TimeoutException if stuck

What you see now: unarrived parties drop to zero and the phase advances.

consoleruns offline
# illustrative output
getPhase() = 1   getRegisteredParties() = 2   getUnarrivedParties() = 2   ✓

Land it Phaser is latch-plus-barrier with a variable roster — know it exists for the rare dynamic-parties case, and reach for the simpler coordinators first.

Likely follow-ups
"Give me a concrete case where a Phaser is clearly the right tool."

A staged data migration where the number of workers changes between stages. Stage one is extraction with, say, eight readers; stage two is transformation with the readers gone and four transformers plus the loaders registered; stage three is loading.

Every stage must finish completely before the next starts, because the transformers need the full extracted set.

With a CyclicBarrier I would need a separate barrier per stage with the right party count each time, and a worker that finishes early would have to keep awaiting barriers it has no part in.

With a Phaser, each worker calls register() when it joins and arriveAndDeregister() when it is done for good, and the phase number tells everyone which stage they are in.

I also override onAdvance to log stage completion and to return true, terminating the phaser, when no parties remain.

"What does a Phaser cost compared with a barrier, and how does it scale to many parties?"

A single phaser is slightly more expensive than a barrier per arrival, because it packs the phase number, the registered count and the unarrived count into one long and updates it with CAS, and every arrival contends on that one word.

With a few dozen parties that is fine; with thousands of parties arriving at the same moment the CAS contention becomes visible.

The class solves that with tiering: phasers can be built into a tree by passing a parent phaser to the constructor, so groups of workers arrive at a child, and only the child arrives at the parent.

The JDK documentation suggests this above roughly a few hundred parties. In practice I have never needed the tree, and if I found myself building one I would ask whether the problem is really a fork-join computation, which ForkJoinPool handles with less ceremony.

"How do you avoid a Phaser hanging forever when a worker dies?"

The same discipline as a latch: deregistration in a finally block, so a worker that throws still calls arriveAndDeregister() and the remaining parties are not stuck waiting for a ghost.

For waiting I use awaitAdvanceInterruptibly(phase, timeout, unit) rather than the plain arriveAndAwaitAdvance(), so a stall becomes a TimeoutException that I can log with the phase number and the unarrived count from getUnarrivedParties().

In a dump, a stuck phaser shows every party parked in Phaser.internalAwaitAdvance, and the diagnosis is to find the party that never arrived; naming the worker threads by stage and index makes the missing one obvious.

And I call forceTermination() from a supervisor if the job is being cancelled, which wakes every waiter immediately.

Drill · Concurrent collections & virtual threads

Modern ConcurrentHashMap internals, the compound-atomicity traps that thread-safe collections do not save you from, and the Loom questions every current senior loop now asks.

Q209. "How does ConcurrentHashMap achieve thread safety in modern Java? Is it still segment locking?"

Reveal answer

The real test Saying "sixteen segments" dates your knowledge to Java 7 — the interviewer is checking which decade you learned this in.

Strong answer No — segments were removed in Java 8. The modern design locks at the level of a single bucket, and often not at all. Inserting into an empty bin is a pure CAS on the table slot: no lock is taken anywhere.

Inserting into a non-empty bin synchronizes on that bin's first node only, so two threads contend only when they hit the very same bucket — with a decent hash spread, effectively never.

Reads take no locks at all; they ride on volatile reads of the node fields.

Two refinements complete the picture:

  • Tree bins: a bin that grows past 8 entries in a large table is converted to a red-black tree. That caps worst-case lookup at O(log n) even under a hash-collision attack.
  • Cooperative resize: threads that arrive during a resize help transfer bins instead of waiting behind a single resizer.

Picture it One ConcurrentHashMap table drawn as numbered bins with four threads at one instant, then the same four threads against a Collections.synchronizedMap that has a single lock.

The setup: three writers and one reader on a map with eight bins; two of the writers hash to the same bin.

BinsDemo.javaruns offline
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(8);
// Thread A: map.put("kA", 1);    // lands in an EMPTY bin
// Thread B: map.put("k21", 2);   // lands in a NON-EMPTY bin
// Thread C: map.put("k29", 3);   // lands in the SAME bin as B
// Thread D: map.get("k10");      // reads a third bin

Make the invisible visible: the table at one instant, one line per bin; the asterisk marks the node whose monitor is held.

ConcurrentHashMap binsruns offline
table[] length 8
 bin 0 | null
 bin 1 | null                      <- A: CAS(null -> [kA]) succeeds  ✓ no lock taken anywhere
 bin 2 | [k2] -> [k10]             <- D: get walks the chain with volatile reads  ✓ no lock
 bin 3 | null
 bin 4 | [k5]* -> [k13]            <- B: synchronized on head [k5], appends [k21]  ✓ owns the bin
       |                           <- C: put hashes to bin 4 too: BLOCKED on [k5]'s monitor  ✗ waits for B
 bin 5 | null
 bin 6 | [k7]                      (idle: a put here would lock only [k7])
 bin 7 | null

Make the invisible visible: the same four threads on a synchronized wrapper: one lock guards every bin.

Collections.synchronizedMapruns offline
Collections.synchronizedMap(new HashMap<>())
 mutex (one monitor)   owner: B (put in progress)      wait queue: A, C, D
 table[] bins 0..7     untouched by anyone but B       <- A, D wait too, though their bins are free  ✗

What you see: the thread dump line for thread C, and a table comparing what each design locks.

thread dump excerptruns offline
# illustrative output
"writer-C" ... BLOCKED (on object monitor)
   java.lang.Thread.State: BLOCKED (on object monitor)
        at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java)
        - waiting to lock <0x000000076c0a1d50> (a java.util.concurrent.ConcurrentHashMap$Node)
What each design locks
OperationConcurrentHashMapCollections.synchronizedMap
put into an empty binCAS on the slot, no lockWaits for the single mutex
put into a non-empty binLocks only that bin's head nodeWaits for the single mutex
getNo lock (volatile reads)Waits for the single mutex
IterationWeakly consistent, never ConcurrentModificationExceptionCaller must synchronize on the map manually
Two writers on different binsRun in parallelRun one after the other

Why: the lock sits at bin granularity (or is skipped), so contention needs two threads on the same bin, which a decent hash makes rare.

Going deeper Two internals an interviewer may push on.

First, the exact treeification rule: a bin is converted to a red-black tree only when it holds more than 8 nodes and the table already has at least 64 buckets; below 64 buckets the map resizes instead, because spreading is cheaper than treeing.

A tree bin shrinks back to a list when it drops to 6 nodes.

Second, resize coordination lives in the sizeCtl field. It is negative while a resize is in progress, and it encodes how many threads are helping.

A writer that finds a ForwardingNode in its bucket knows that bucket has already moved, calls helpTransfer, and takes a stride of buckets to migrate before retrying its own operation.

Readers never wait: a get that hits a forwarding node simply follows it into the new table.

resize in progressruns offline
old table, bin 3:  [ForwardingNode -> nextTable]
writer put(k) -> sees ForwardingNode -> helpTransfer(): migrates a stride of bins, then retries the put
reader get(k) -> sees ForwardingNode -> searches nextTable instead (never blocks)

The consequence for production is that a resize on a 10-million-entry map does not stall writers, but it does briefly double memory, so I pre-size hot maps with new ConcurrentHashMap<>(expectedSize).

Land it The current answer is "CAS for empty bins, per-bin synchronized otherwise, lock-free reads" — bucket-level granularity, which is why it scales where the old segment design plateaued.

Likely follow-ups
"Why does the map use synchronized on the bin node rather than a ReentrantLock, given the usual advice?"

Because of memory and because the critical section is tiny. A ReentrantLock is a separate object of around 40 bytes plus its queue; a map with a million bins would spend tens of megabytes on locks that are almost never contended.

A synchronized block on the first node in the bin costs nothing until contention actually happens, since the monitor lives in the object header.

The hold time is a few dozen nanoseconds, just a pointer walk and a link, so lock features like timeouts and fairness are irrelevant. Doug Lea's comments in the source say exactly this.

And since JDK 24, with JEP 491, blocking inside synchronized no longer pins virtual threads, so the one modern reason to avoid synchronized in library code, Loom compatibility, has disappeared as of Aug 2026.

"What are the null rules, and why does the map forbid null values when HashMap allows them?"

ConcurrentHashMap rejects both null keys and null values with a NullPointerException. The reason is ambiguity under concurrency. In a HashMap, get(k) returning null could mean "absent" or "mapped to null", and you disambiguate by calling containsKey(k) afterward.

null rulesruns offline
map.put("k", null);    // throws NullPointerException
map.put(null, 1);     // throws NullPointerException
map.get("k");         // null therefore always means: absent

In a concurrent map that two-step check is meaningless, because another thread can remove or insert the key between the two calls, so the map would have no way to give a consistent answer.

Forbidding null values makes "null means absent" an unambiguous single-call answer, which is what putIfAbsent and computeIfAbsent rely on. This bites people who store Optional-like "not found" results; the fix is a sentinel object or, better, caching an Optional.empty() instance.

"How would you verify that hash spread is good enough that bins are not contended in production?"

Two measurements. First, contention: a JFR recording with the profile settings emits jdk.JavaMonitorEnter events for any monitor wait over the threshold, defaulting to 20 milliseconds but tunable down to 1, and if the monitor class is a ConcurrentHashMap$Node I have bin contention.

In a healthy map those events do not exist.

Second, distribution: in a heap dump, MAT's OQL can count nodes per bin, or I use a quick reflective check in a test to measure the longest chain; anything above a handful means a bad hashCode, typically one that returns a constant or ignores the fields that vary.

The classic failure is a key class whose hashCode is derived from one low-cardinality field, so a million entries land in a few bins that all treeify; lookups stay O(log n) but every write to those bins now contends.

"When would ConcurrentHashMap be the wrong choice, and what would you use instead?"

Three cases. When I need ordered iteration or range queries, I use ConcurrentSkipListMap, which is lock-free and sorted, at the cost of O(log n) instead of O(1) lookups.

When I need an eviction policy, expiry, or bounded size, I use Caffeine, which is built on a concurrent map but adds the admission and eviction machinery that a bare map lacks; hand-rolling eviction on a ConcurrentHashMap is a well-known source of leaks.

And when the map is written once at startup and only read afterward, an immutable Map.copyOf is faster and smaller, because it has no CAS, no volatile reads and no resize logic.

The map is the right default for a read-mostly, write-sometimes keyed cache with no eviction, and the wrong default the moment I find myself writing a background thread to trim it.

Q210 · Scenario. "Your metrics thread logs map.size() on a busy ConcurrentHashMap and the numbers occasionally look impossible; an iterator taken during a write burst misses new entries. Is the map broken?"

Reveal answer

Strong answer The map is fine — both behaviors are its documented contract, and understanding why is the point.

  1. size() under concurrent writes is an estimate. The count is kept in striped cells, LongAdder-style, precisely so that writers on different cores do not contend on one counter; summing those cells while writers keep incrementing them cannot yield an exact instantaneous total — an exact answer would require freezing all writers, which is the very thing the map refuses to do.
  2. Iterators are weakly consistent: they never throw ConcurrentModificationException, they reflect the map roughly as of the moment they were created, they may or may not show later insertions, and they are guaranteed never to return the same element twice. So an entry added mid-iteration being absent is expected, not lost.
  3. My check is therefore to verify semantics rather than hunt corruption: if the "impossible" numbers are within write-burst jitter, this is working as designed.

If the business genuinely needs exact counts, I keep my own LongAdder incremented on successful insert and decremented on remove, or I take snapshots during a quiesced window. The design lesson to say out loud: ConcurrentHashMap deliberately trades exact global views for never blocking readers and writers against each other.

Picture it The counter cells behind size(), a size() call overlapping two writers, and an iterator walking bins while an insert lands behind it.

The setup: a metrics thread logging size() while writer threads insert and remove.

SizeProbe.javaruns offline
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
// writers: map.put(id, ...) and map.remove(id) in bursts
// metrics thread, every 100 ms:
log.info("size={}", map.size());          // ❌ TRAP: treating an estimate as an exact snapshot
for (var e : map.entrySet()) { /* iterator is weakly consistent */ }

Make the invisible visible: the fields that hold the count.

memory pictureruns offline
ConcurrentHashMap
 baseCount        = 4990                   updated by CAS when there is no contention
 counterCells[]   = [ cell0:  6 | cell1: -2 | cell2:  3 | cell3:  1 ]   each cell padded to its own cache line
 size()           = baseCount + sum(cells) = 4990 + 8 = 4998      (a cell can be negative after removes)

The trace: size() reads the fields one after another while two writers change them.

thread interleavingruns offline
step  size() reads              writers                          true total after the step
0                                                              4998
1     baseCount -> 4990
2     cell0 -> 6
3                               X: put   (cell0 6 -> 7)        4999
4                               Y: remove (cell2 3 -> 2)       4998
5     cell1 -> -2, cell2 -> 2, cell3 -> 1
6     returns 4990+6-2+2+1 = 4997      ✗ a count that never existed (true totals were 4998, 4999, 4998)

What you see: sampled sizes during a burst, then after the writers stop.

consoleruns offline
# illustrative output
size=4997   size=5003   size=4999        <- during the burst: estimates
size=5000                                 <- after writers are quiet: exact

Make the invisible visible: the iterator is a one-pass walk over the bins, so an insert behind it is not seen and an insert ahead of it is.

weakly consistent iterationruns offline
iterator walks bin 0 -> 7                  state when iterator() was created: keys in bins 2, 4
 bin 0 1 2 3 4 5 6 7
         ^ passed bin 2
 put(k) lands in bin 1 (behind the iterator)  -> not shown   (allowed)
 put(k) lands in bin 6 (ahead of it)          -> shown       (allowed)
 never: the same element twice, never ConcurrentModificationException

The fix: when logic needs an exact count, keep your own counter in the code that mutates the map.

ExactCount.javaruns offline
LongAdder count = new LongAdder();                 // updated only where entries change
if (map.putIfAbsent(id, v) == null) count.increment();      // ✅ FIX: count on successful insert
if (map.remove(id) != null)         count.decrement();      // and on successful remove

Land it Approximate size and weakly consistent iteration are the purchase price of a map that never stops the world — design monitoring around the contract instead of fighting it.

Likely follow-ups
"What does mappingCount() add over size(), and is it any more accurate?"

mappingCount() returns a long instead of an int, so it does not saturate at about 2.1 billion entries, and the Javadoc says it should be preferred for that reason. It is not more accurate.

Both call the same internal sumCount(), which adds the base counter and the per-cell counters without any snapshot, so they carry exactly the same jitter under concurrent writes. The practical difference is only relevant for enormous maps.

I mention it in an interview to show I have read the API rather than to change behaviour.

If someone needs a stable count for display, the honest answer is a separate LongAdder maintained in the same code that inserts and removes, or sampling the estimate and smoothing it, not switching between these two methods.

"The iterator missed an entry that was inserted before the iteration began. Is that possible?"

No, and if it truly happened I would look for a different bug. The weakly consistent guarantee is that the iterator reflects every element that existed when the iterator was created, and may or may not reflect later changes.

An insertion that completed before iterator() was called, in the happens-before sense, will be visited.

The likely explanation for the report is one of two things: the insert had not actually completed when the iterator was created, because the "before" was a wall-clock impression rather than a synchronization edge; or the entry was inserted and then removed or replaced during the iteration, and the iterator skipped it because removal is visible immediately.

I would check by adding a timestamp to the log line at insert and at iterator creation, which usually shows they were a few microseconds apart in the wrong order.

log excerptruns offline
# illustrative output
12:00:00.000398  iterator() created
12:00:00.000412  insert key=77 done          <- the "before" was a wall-clock impression, the insert finished 14 us later
"How would you take a consistent snapshot of the map when you truly need one?"

Only by stopping the writers or copying under an external lock, and I would push back on the requirement first.

If the writers can be paused, a ReadWriteLock around the map where writers take the read side and the snapshot takes the write side works, because the write lock waits for all in-flight writers to finish and then blocks new ones for the duration of the copy.

A copy of a million entries takes tens of milliseconds, which is a real stall. The cheaper approach for reporting is to accept a weakly consistent copy, new HashMap<>(map), and label the output as approximate.

And for things like "total balance across accounts", the right fix is often to not derive the total from the map at all but maintain it in one LongAdder updated by the same code path that mutates entries.

"What is the cost of calling size() on a hot map from a metrics thread every second?"

Small but not zero. size() walks the counter cells, which is at most one per CPU, so a few dozen volatile reads, roughly a microsecond even on a large box.

The real cost is not the read but what it does to writers: reading a cell pulls its cache line into the shared state on the metrics core, so the next writer on that cell pays a coherence miss to get it back exclusive.

At once a second that is noise. At a million times a second, say a size check on every request, it is a measurable slowdown on the writers, which is the same false-sharing tax an AtomicLong pays.

So I sample size from a scheduled thread at a fixed rate, never inline in the request path, and I definitely never use size() as a guard for admission control.

Q211 · Scenario. "Two threads both check containsKey and then put, and you get duplicate expensive initializations with one object leaked — on a ConcurrentHashMap. Isn't it thread-safe?"

Reveal answer

Strong answer It is thread-safe per operation: each call is atomic. But my code strung two operations into a sequence, and no collection can make my sequence atomic.

The race, step by step:

  1. Check: both threads call containsKey and both see the key absent.
  2. Create: both run the expensive creation.
  3. Act: the second put overwrites the first, orphaning a connection or cache entry that someone may already hold.

This is a check-then-act race, and the fix is to collapse the sequence into the map's single atomic method:

check-then-act-fix.java
// ❌ TRAP: the world can change between the check and the put
if (!cache.containsKey(key)) {
    cache.put(key, expensiveCreate(key));   // both threads reach this line
}

// ✅ FIX: atomic, at most one invocation of the function per key
Connection c = cache.computeIfAbsent(key, k -> expensiveCreate(k));

computeIfAbsent guarantees the mapping function runs at most once per absent key. Other threads asking for the same key briefly wait and then receive the same instance.

The family covers the other shapes too:

  • putIfAbsent: when the value is cheap to pre-build.
  • merge and compute: for atomic read-modify-write, like counters.

The reviewable rule: on a concurrent map, any if-absent-then-put or get-modify-put written as separate calls is a bug.

Picture it The same two threads and the same key, one row per step: first with containsKey plus put (duplicate work visible), then with computeIfAbsent, followed by a table of which compound operations are atomic.

The setup: the broken and the fixed code are the two snippets in the Strong answer above; the key is absent and expensiveCreate opens a connection.

The trace: the check-then-act interleaving, with the map contents after each step.

thread interleaving: containsKey + putruns offline
step  thread A                              thread B                              map
1     containsKey(k) -> false                                                    {}
2                                              containsKey(k) -> false           {}
3     expensiveCreate(k) -> conn#1  (work)                                       {}
4                                              expensiveCreate(k) -> conn#2      {}      <- DUPLICATE work  ✗
5     put(k, conn#1)                                                             {k: conn#1}
6                                              put(k, conn#2)  overwrites        {k: conn#2}  ✗ conn#1 orphaned, never closed

What you see: the counters after both threads finish.

consoleruns offline
# illustrative output
created=2  stored=1  leaked=1          <- one connection nobody can close

The fix: the same two threads with computeIfAbsent.

thread interleaving: computeIfAbsentruns offline
step  thread A                              thread B                              map
1     computeIfAbsent(k, f): locks the bin                                       {}
2                                              computeIfAbsent(k, f): waits      {}
3     f(k) runs ONCE -> conn#1; stored                                           {k: conn#1}
4     bin unlocked
5                                              sees k present, returns conn#1    {k: conn#1}  ✓ f never ran for B

What you see now: the same counters.

consoleruns offline
# illustrative output
created=1  stored=1  leaked=0          ✓
Which compound operations are atomic on ConcurrentHashMap
CodeOutcomeCatch
containsKey then putSilently wrong: duplicate work, last write winsTwo separate calls, no atomic unit
get, then put if nullSilently wrongSame race as above
putIfAbsent(k, v)Works: atomic, returns the previous valueThe value is built before the call, so a loser's value is wasted and must be closed
computeIfAbsent(k, f)Works: f runs at most once per absent keyf runs under the bin lock: keep it short, never touch the map
merge(k, v, f)Works: atomic read-modify-writeReturning null from f removes the entry
compute(k, f)Works: atomic read-modify-writef runs under the bin lock; a null result removes the entry

Land it Thread safety of individual operations never composes — atomicity across a check and an act must come from a single method the map itself provides.

Likely follow-ups
"What if the expensive creation can fail — what does computeIfAbsent do with an exception, and how do you cache the failure?"

If the mapping function throws, computeIfAbsent propagates the exception and leaves the map unchanged; no entry is stored, and the bin lock is released. That is usually what I want for a transient failure, because the next caller retries the creation.

The problem is a downstream that is down: every caller now retries the expensive creation and each one fails after a timeout, which is a stampede of failures.

exception in the mapping functionruns offline
map.computeIfAbsent("k", x -> { throw new IllegalStateException("down"); });   // propagates
map.containsKey("k");     // false: nothing stored, bin lock released, the next caller retries

If I want to remember the failure I store a value that carries the outcome, for example a CompletableFuture that completed exceptionally, or a small result record with a timestamp, and give failed entries a short lifetime.

Caffeine does this properly with AsyncLoadingCache, which caches the future and by default evicts a failed one immediately while still collapsing concurrent callers onto a single attempt.

"Does the fix still hold if the map is a plain HashMap wrapped in Collections.synchronizedMap?"

Yes, but only by accident of implementation.

A synchronized wrapper locks the whole map for every method call, and the default Map.computeIfAbsent implementation runs the function inside that lock, so at most one creation per key happens; the cost is that every other operation on the map, for any key, blocks for the whole creation.

With a five-second creation that is a service stall. On ConcurrentHashMap only the one bin is locked, so unrelated keys keep flowing.

I would also note the older Collections.synchronizedMap trap: iteration is not covered by the wrapper, so any loop over it needs manual synchronization on the map object, which is a common ConcurrentModificationException in production. Given that, I replace the wrapper with ConcurrentHashMap and lose nothing.

"How do you handle the leaked object that the losing thread already created?"

With computeIfAbsent there is no loser; only one thread creates. But if I am stuck with putIfAbsent because the value must be built first, I write it as existing = map.putIfAbsent(key, created); if (existing != null) { created.close(); return existing; }.

The losing thread checks the return value, which is the winner's instance, closes its own creation, and uses the winner's. The important point is that putIfAbsent returns the previous value, so the loser learns it lost.

The same pattern appears with ConcurrentMap.put races generally: whoever writes second must read the return value.

I add a review rule that ignoring the return value of putIfAbsent on a resource-bearing value is a bug, and a metric on how often the losing branch runs, because a high count means the object is expensive enough to deserve computeIfAbsent.

"Under what load does computeIfAbsent itself become a problem?"

When the mapping function is slow and many distinct keys hash to the same bin, or when a key is read extremely often.

The first case: the function runs under the bin lock, so a five-second remote call for key A blocks a get on unrelated key B if they share a bin, which is rare with a good hash but happens.

The second case is subtler: the JDK 8 implementation took the bin lock even when the key was already present, so a hot key saw contention on pure reads; JDK 9 and later check for an existing mapping first without locking, so plain hits are lock-free now.

For a slow loader I still prefer to store a CompletableFuture as the value, which makes the lock hold a few nanoseconds, and callers wait on the future outside the map. That is exactly how Caffeine's async cache is built.

Q212 · Scenario. "A service hangs, and the stuck thread's stack is inside ConcurrentHashMap.computeIfAbsent — whose mapping function, it turns out, writes to the same map. What is happening?"

Reveal answer

Strong answer The mapping function is re-entering the map that is mid-operation, which the contract explicitly forbids.

  1. computeIfAbsent holds the lock on the target bin while my function runs. If the function then inserts into or computes on the same map, it may need that same bin — the thread deadlocks against its own held lock, or interleaves with another thread doing the mirror image and they deadlock pairwise. The Javadoc is blunt: the mapping function "must not attempt to update any other mappings of this map," and the computation "should be short and simple."
  2. Newer JDK (Java Development Kit) releases detect the direct case and throw IllegalStateException: Recursive update — a loud failure that is strictly better than the silent hang, but the code is wrong either way. The classic demo is recursive memoization, a Fibonacci function caching into the very map it recurses through.
  3. Diagnosis is exactly what the scenario gives: a thread dump showing the thread parked inside computeIfAbsent, then reading the lambda it was passed.

The fix is to keep the mapping function pure. There are two ways:

  • Compute outside, then insert: compute the value fully outside the map, letting the recursion resolve first, then insert with putIfAbsent. The price is a rare duplicate computation.
  • Use another structure: restructure so the recursive lookups hit a different structure.

Prevention: a review rule that lambdas passed to compute-family methods touch nothing but their arguments.

Picture it Which bin lock the thread already holds when the recursive call re-enters the map, and the exception or dump it produces.

The setup: a recursive Fibonacci that memoizes into the very map it recurses through.

Memo.javaruns offline
private final Map<Integer, Long> memo = new ConcurrentHashMap<>();

long fib(int n) {
    if (n < 2) return n;
    return memo.computeIfAbsent(n, k -> fib(k - 1) + fib(k - 2));   // ❌ TRAP: the lambda re-enters memo
}

The trace: one thread calling fib(3), with the lock it holds at each step.

call traceruns offline
step  call                                       state
1     fib(3) -> memo.computeIfAbsent(3, f)       bin of key 3 locked, f starts running
2       f -> fib(2) -> memo.computeIfAbsent(2, f)  updates the SAME map while that bin is still locked
3         key 2 in the same bin as key 3?          needs the lock this thread already holds  ✗ stuck or "Recursive update"
4         key 2 in a different bin?                happens to proceed, but the contract is still broken  ✗

What you see: on current JDKs the direct case fails loudly.

consoleruns offline
# illustrative output
Exception in thread "main" java.lang.IllegalStateException: Recursive update
        at java.base/java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java)
        at Memo.fib(Memo.java:5)

Why: the function runs while the bin is locked, so touching the same map from inside it re-enters a lock that is already held.

The fix: compute outside the map and insert the result afterwards.

MemoFixed.javaruns offline
long fib(int n) {
    if (n < 2) return n;
    Long hit = memo.get(n);
    if (hit != null) return hit;
    long v = fib(n - 1) + fib(n - 2);       // ✅ FIX: recursion finishes before any map write
    memo.putIfAbsent(n, v);                 // a rare duplicate computation is the price
    return v;
}

What you see now: the same call completes.

consoleruns offline
# illustrative output
fib(50) = 12586269025        ✓ no exception, no hang

Land it computeIfAbsent runs your code while holding a bin lock — feed it a function that re-enters the same map and you have built a deadlock into a one-liner.

Likely follow-ups
"Which JDK versions throw 'Recursive update', and why is it not detected every time?"

The detection arrived in JDK 9 as part of JDK-8062841.

It catches the case where the mapping function modifies the same bin that computeIfAbsent is currently holding, because the thread finds a reservation node in the bin it is trying to update and knows it placed that node itself.

It does not catch a write to a different bin, because that write simply succeeds.

It also does not catch the two-thread cycle where thread A holds bin 1 and wants bin 2, while thread B holds bin 2 and wants bin 1. That is a plain deadlock between two monitors, which jstack reports under "Found one Java-level deadlock".

jstack deadlock reportruns offline
# illustrative output
Found one Java-level deadlock:
"T1": waiting to lock monitor 0x00007f1c (object 0x000000076b, a java.util.concurrent.ConcurrentHashMap$Node),
  which is held by "T2"
"T2": waiting to lock monitor 0x00007f2d (object 0x000000076c, a java.util.concurrent.ConcurrentHashMap$Node),
  which is held by "T1"

So the exception is a convenience for the simplest recursion, and as of Aug 2026 the contract remains: the function must not touch the map at all.

I test that rule by running the memoiser under jcstress or a simple multi-threaded loop with a small map, where bin collisions are common.

"How do you write a correct concurrent memoiser for a recursive function like Fibonacci?"

I separate the lookup from the computation. The map stores CompletableFuture<Long> values. For key n, I call map.get(n); if present I join it.

If absent I create a new future, try putIfAbsent(n, future), and if I won, I compute the value by recursively calling the same memoiser for n-1 and n-2, which does its own gets and puts on other keys, and then complete the future.

The recursion never runs inside a compute method, so no bin lock is ever held across it, and concurrent callers for the same n wait on the same future instead of duplicating work.

This is the pattern from Java Concurrency in Practice, and it is essentially what ConcurrentHashMap.computeIfAbsent tries to give you in one call, but it works for reentrant computations. The one cost is a future allocation per new key.

"The fix went in and the service still hangs in computeIfAbsent occasionally. What now?"

Then the lambda is doing something blocking that is not a map write.

I take three dumps and read the frames below computeIfAbsent: if I see a socket read, the function calls a remote service under the bin lock, and any caller sharing that bin waits for the network.

If I see park on a lock or a future, the function waits on something another thread holds, and that thread may be waiting on this bin, which is a deadlock spanning the map and an unrelated lock.

Either way the rule is the same: the mapping function must be pure and fast.

I move the expensive work out by caching a CompletableFuture as the value, so the lock holds only for the allocation, and I add a JFR jdk.JavaMonitorEnter check with the threshold lowered to a millisecond to confirm bin-lock waits have gone to zero.

Q213 · Scenario. "Someone used CopyOnWriteArrayList for a list that takes hundreds of updates a second, and CPU plus garbage-collection time went through the roof. What went wrong, and where is that class actually right?"

Reveal answer

Strong answer The name is the mechanism: every single mutation copies the entire backing array.

  1. An allocation profiler makes it obvious — Arrays.copyOf called from the list's add and remove dominating allocations. At hundreds of writes per second on, say, a 100,000-element list, the service is copying hundreds of megabytes per second just to mutate a list, and the collector is drowning in short-lived arrays.
  2. The design intent explains the price: readers and iterators work on an immutable snapshot, so reads take no locks ever and iterators never throw ConcurrentModificationException — an iterator simply walks the array that existed when it was created. Reads were made free by making every write O(n) in time and allocation.
  3. So the class is right where writes are rare and reads dominate massively: listener and observer registries that change a handful of times over a process lifetime but are iterated on every event, or configuration lists rewritten only at deploy time.

For a hot write path the replacement depends on semantics: ConcurrentLinkedQueue for producer-consumer hand-off, a ConcurrentHashMap-keyed structure for keyed access, or a plain list under a lock if throughput allows. The interview point is stating the trade explicitly rather than treating "concurrent" in the name as a blanket endorsement.

Picture it The backing array before and after one add while a reader is mid-iteration, and the copy cost in numbers for a 10,000-element list.

The setup: a listener list that is updated hundreds of times a second.

Listeners.javaruns offline
private final List<Listener> listeners = new CopyOnWriteArrayList<>();

void subscribe(Listener l) { listeners.add(l); }     // ❌ TRAP: every add copies the whole array
void publish(Event e)      { for (Listener l : listeners) l.on(e); }

Make the invisible visible: the array reference and a reader's iterator around a single add(X).

memory pictureruns offline
BEFORE add(X)                                   AFTER add(X)
list.array -> [ A | B | C | ... ]   array #1    list.array -> [ A | B | C | ... | X ]   array #2 (new, n+1 slots)
reader R: iterator -> array #1 (cursor at B)     reader R: iterator -> array #1 (unchanged, never sees X)
                                                 array #1 stays alive until R finishes, then becomes garbage

The trace: the cost of those copies at hundreds of writes per second (4 bytes per reference with compressed oops).

Allocation per second caused by add() on a copy-on-write list
List sizeWrites per secondAllocated per writeAllocated per secondElement copies per second
10,000100about 40 KBabout 4 MB1,000,000
10,000300about 40 KBabout 12 MB3,000,000
10,000500about 40 KBabout 20 MB5,000,000
100,000500about 400 KBabout 200 MB50,000,000

What you see: a young collection about every second in the GC log, with almost nothing surviving.

GC logruns offline
# illustrative output
[31.201s][info][gc] GC(212) Pause Young (Normal) (G1 Evacuation Pause) 614M->9M(1024M) 3.1ms
[32.119s][info][gc] GC(213) Pause Young (Normal) (G1 Evacuation Pause) 612M->9M(1024M) 3.0ms
# 600 MB freed each time, 9 MB survives: short-lived array churn

Why: every mutation allocates a new array and copies all n references, so writes are O(n) in time and allocation.

The fix: a set with lock-free reads and O(1) updates, when order does not matter.

ListenersFixed.javaruns offline
private final Set<Listener> listeners = ConcurrentHashMap.newKeySet();   // ✅ FIX: no array copy per write

void subscribe(Listener l)   { listeners.add(l); }
void unsubscribe(Listener l) { listeners.remove(l); }

What you see now: the same GC log.

GC logruns offline
# illustrative output
[41.830s][info][gc] GC(40) Pause Young (Normal) (G1 Evacuation Pause) 702M->11M(1024M) 2.8ms
[58.114s][info][gc] GC(41) Pause Young (Normal) (G1 Evacuation Pause) 705M->11M(1024M) 2.9ms
# a collection every ~16 s instead of every ~1 s

Land it Copy-on-write buys wait-free reads by charging a full array copy per write — a bargain for listener lists, a disaster for anything written hundreds of times a second.

Likely follow-ups
"Give me the arithmetic: at what write rate and list size does copy-on-write become unacceptable?"

Each write allocates a new array of n references, 4 bytes each with compressed oops, plus a copy of the old contents.

For n of 10,000 that is 40 kilobytes per write; at 500 writes per second that is 20 megabytes per second of allocation just for the list, which the young generation collector handles but which adds a collection every few seconds on a small heap.

At n of 100,000 and the same rate it is 200 megabytes per second, which is enough to trigger near-constant young collections and to push arrays straight into the old generation when they exceed the region size in G1, causing humongous allocations.

My threshold in practice: if writes per second multiplied by list size exceeds about a million element-copies per second, I replace the structure. Below that, copy-on-write is often fine and I leave it alone.

"What replaces it for a listener registry that genuinely does change frequently?"

It depends on the read pattern.

If readers iterate the whole list on every event, and writes are frequent, a ConcurrentHashMap.newKeySet() gives me lock-free reads and cheap O(1) add and remove, with a weakly consistent iterator that never throws; ordering is lost, which for listeners rarely matters.

If order matters, a ConcurrentLinkedQueue keeps insertion order with lock-free add and iteration, and removal is O(n) but cheap.

If I need a stable snapshot per event so that a listener removed mid-dispatch still gets that event, I keep copy-on-write but batch the writes: buffer registrations for a short window and apply them as one copy.

The wrong answer is Collections.synchronizedList, which serialises every read against every write and forces manual locking around iteration.

"Why does the iterator never throw ConcurrentModificationException, and what does that cost readers?"

The iterator captures a reference to the array that existed when it was created and walks that array; it never looks at the list again. Writers never mutate that array; they create a new one and swap the volatile reference.

So the iterator's view is frozen and cannot be invalidated, which is why there is nothing to detect and no exception.

The cost to readers is staleness: an element added after the iterator was created is not seen, and an element removed is still visited.

So a listener that unsubscribes during dispatch may still receive the current event.

stale iteratorruns offline
Iterator<Listener> it = listeners.iterator();   // snapshot: array #1
listeners.remove(l);                            // array #2 is built without l
it.next();                                      // Result: can still return l  (stale view)
it.remove();                                    // throws UnsupportedOperationException

The iterator also does not support remove(), which throws UnsupportedOperationException. The memory cost is that a long-running iteration pins the old array until it finishes, so a slow reader on a large list keeps two copies alive.

"How would you confirm this diagnosis rather than assume it from the class name?"

With an allocation profile, not a CPU profile.

In JFR I look at the jdk.ObjectAllocationSample events, which since JDK 16 sample allocations cheaply, grouped by top frame; a copy-on-write problem shows Arrays.copyOf called from CopyOnWriteArrayList.add or remove at the top of the allocation ranking, with the total bytes matching the rate I estimated.

With async-profiler, -e alloc gives the same picture as a flame graph. I also check the GC log for the collection frequency and the size of surviving objects; if young collections happen every second and almost nothing survives, the allocation is short-lived churn, which fits.

Then I swap the structure in a canary and watch the allocation rate and GC count drop, which is the proof.

Q214. "Compare ArrayBlockingQueue, LinkedBlockingQueue, and SynchronousQueue — which one backs which executor, and why? And what is DelayQueue for?"

Reveal answer

Strong answer All are BlockingQueue implementations: put blocks when full and take blocks when empty. They differ in structure and bound.

ArrayBlockingQueue is a fixed array, always bounded, with one lock shared by both ends. It is simple and predictable.

LinkedBlockingQueue uses linked nodes. It is optionally bounded but unbounded by default, and it holds separate locks for put and take so producers and consumers do not contend.

It backs newFixedThreadPool, and its unbounded default is exactly the out-of-memory trap from earlier.

SynchronousQueue has zero capacity. It is a pure handoff where every put waits for a matching take.

It backs newCachedThreadPool, and that is why cached pools spawn threads. The queue can never absorb a task, so every submission either meets a free worker instantly or triggers thread creation.

DelayQueue holds elements that only become takeable after their individual delay expires — the natural engine for retry-with-backoff schedulers and expiry sweeps, and ScheduledThreadPoolExecutor runs on the same idea internally.

Picture it The same producer and consumer against the three queues drawn side by side, the circular array's indices moving step by step, and an outcome table.

The setup: one producer calling put and one consumer calling take, with only the queue changed.

QueueDemo.javaruns offline
BlockingQueue<Task> q = new ArrayBlockingQueue<>(4);   // or new LinkedBlockingQueue<>(4), or new SynchronousQueue<>()

// producer P:  q.put(task);          // blocks when there is no room
// consumer C:  Task t = q.take();    // blocks when there is nothing to take

Make the invisible visible: the three structures with P and C attached.

ArrayBlockingQueueruns offline
ArrayBlockingQueue (capacity 4): ONE lock, circular array
 items[ 0 | 1 | 2 | 3 ]    count, takeIndex, putIndex
 P put() --> lock --> items[putIndex]    C take() --> same lock --> items[takeIndex]
 P and C contend on the one lock even when the queue is half full
LinkedBlockingQueueruns offline
LinkedBlockingQueue (capacity 4): TWO locks, linked nodes, AtomicInteger count
 head --> [dummy] --> [a] --> [b] --> [c] <-- last
 C take() holds takeLock (works at head)          P put() holds putLock (works at last)
 P and C run in parallel; every element costs a node allocation
SynchronousQueueruns offline
SynchronousQueue: NO storage (size() is always 0)
 P put(x) --waits--> [ meet ] <--waits-- C take()      x passes straight from P to C
 if C is not waiting, P blocks; offer(x) returns false at once

The trace: the circular array of capacity 4 as P puts and C takes.

ArrayBlockingQueue indicesruns offline
event        items[0..3]         takeIndex  putIndex  count
start        _ _ _ _             0          0         0
put a,b,c    a b c _             0          3         3
take -> a    _ b c _             1          3         2
put d        _ b c d             1          0 (wrap)  3
put e        e b c d             1          1         4  (full)
put f        P blocks until C takes: never overwrites

What you see: how each queue behaves when the producer outruns the consumer, and which executor factory uses it.

Comparing the queues
QueueBounded?Blocks when...Used by
ArrayBlockingQueueAlways (fixed array), one lockput when full, take when emptyNo standard Executors factory; chosen by hand for a ThreadPoolExecutor
LinkedBlockingQueueOptional; default Integer.MAX_VALUE, two locksput only if a bound was set and it is fullnewFixedThreadPool, newSingleThreadExecutor
SynchronousQueueCapacity zero, no storageput until a consumer is waitingnewCachedThreadPool
DelayQueueUnboundedtake until the head's delay has expiredNot by a factory; ScheduledThreadPoolExecutor uses its own internal delayed queue on the same idea

Why: the queue decides the overload behaviour: buffer in place, buffer without bound, or refuse and force a decision now.

Land it Choosing the queue is choosing the executor's overload behavior — buffer in place, buffer without bound, or refuse to buffer and force a decision now.

Likely follow-ups
"Why does a bounded queue in front of ThreadPoolExecutor prevent the maximum pool size from ever being used?"

Because of the executor's submission order: it first fills the pool up to corePoolSize, then offers the task to the queue, and only if the queue refuses does it create threads up to maximumPoolSize.

An unbounded LinkedBlockingQueue never refuses, so the pool stays at core size forever and the queue grows without limit, which is the out-of-memory trap.

A bounded queue does refuse when full, so extra threads appear only after the queue fills.

That means a burst first waits in the queue and only then gets more workers, the opposite of what most people expect.

submission orderruns offline
# corePoolSize=2, maximumPoolSize=4, queue=ArrayBlockingQueue(2)
task1 -> new thread (core 1/2)      task2 -> new thread (core 2/2)
task3 -> queued (1/2)               task4 -> queued (2/2)
task5 -> queue full, new thread (3/4)   task6 -> new thread (4/4)
task7 -> RejectedExecutionException (default AbortPolicy)

If I want threads to scale before the queue is used, I set core equal to max and use the queue purely as a buffer, or I use a SynchronousQueue so that every submission beyond the busy workers creates a thread immediately, with the maximum as the hard cap.

"What is the practical difference between the one-lock and two-lock designs under load?"

ArrayBlockingQueue has a single ReentrantLock protecting both ends, so a producer and a consumer contend even when the queue is half full; with many producers and many consumers that lock becomes a hot spot and the throughput ceiling is a few million operations per second.

LinkedBlockingQueue has separate put and take locks and an atomic count, so producers contend only with producers and consumers with consumers, roughly doubling throughput in a balanced pipeline. The price is a node allocation per element, which is garbage.

For a single-producer, single-consumer pipeline neither lock is contended and the array version wins on memory and cache locality.

If I actually need more than a few million handoffs per second I leave both behind for a lock-free ring buffer such as the LMAX Disruptor or JCTools queues.

"Why does newCachedThreadPool use a SynchronousQueue, and what goes wrong with it under a burst?"

A cached pool has core size zero and maximum Integer.MAX_VALUE. If it used a buffering queue, every task would be queued and no threads would be created, because the executor only adds threads when the queue refuses.

A SynchronousQueue refuses whenever no consumer is waiting, so each submission that finds no idle thread creates a new one, which is the intended elasticity.

Under a burst that elasticity becomes the failure: ten thousand submissions in a second create ten thousand platform threads, each with a megabyte of stack, and the process dies with "unable to create new native thread" or is killed by the container for memory.

The failure looks like this:

consoleruns offline
# illustrative output
java.lang.OutOfMemoryError: unable to create new native thread

So I never use the cached pool for anything driven by external traffic; it is fine for a handful of internal tasks. For elastic request handling I use virtual threads instead, where creating ten thousand is cheap.

"How does DelayQueue order its elements, and what does that cost for a retry scheduler with a million entries?"

It is a PriorityQueue ordered by the Delayed.getDelay() value, with a single lock and a condition, and take() parks until the head's delay reaches zero. Insert and remove are O(log n), so a million entries cost about twenty comparisons per operation, which is fine.

The costs that hurt are elsewhere: the whole queue lives on the heap, so a million retry records is hundreds of megabytes; it is not persistent, so a restart loses every pending retry; and it is single-node, so a fleet of twelve pods each has its own schedule.

That is why for real retry scheduling I use a persistent store, a table with a next_attempt_at column polled by a worker or a broker with delayed delivery, and keep DelayQueue for in-process housekeeping such as expiring entries in a local cache.

Q215. "What exactly is a virtual thread?"

Reveal answer

Strong answer A virtual thread is a java.lang.Thread scheduled by the Java runtime instead of the operating system. Its stack lives on the heap in small, growable chunks rather than as a fixed megabyte-scale reservation.

To run, it is mounted on a carrier — a real platform thread from an internal ForkJoinPool sized roughly to the core count.

The magic is at blocking points. When a virtual thread blocks on a socket read, a sleep, or most locks, the runtime unmounts it:

  1. Park: the virtual thread's stack state moves to the heap.
  2. Hand over: the carrier is given to another runnable virtual thread.

Blocking therefore stops costing an operating-system thread. A parked virtual thread costs roughly kilobytes of heap.

Crucially the programming model is unchanged:

  • It is the same Thread API.
  • It is ordinary blocking code.
  • ThreadLocal still works.
  • Stack traces in the debugger are real.

It is not a callback or reactive rewrite.

Picture it Two carriers and four virtual threads at successive moments, showing a virtual thread unmounting at sleep and coming back on a different carrier.

The setup: a virtual thread that prints which thread it is, sleeps, and prints again.

MountDemo.javaruns offline
Thread.ofVirtual().name("v1").start(() -> {
    System.out.println("before: " + Thread.currentThread());
    Thread.sleep(100);                    // blocking point: the runtime unmounts here (checked exception handling omitted)
    System.out.println("after:  " + Thread.currentThread());
}).join();

Make the invisible visible: which virtual thread sits on which carrier, and where its frames live, at each moment.

mount and unmount over timeruns offline
moment  carrier C1            carrier C2            heap
t0      runs V1               runs V2               -
t1      V1 sleep(): unmounted runs V2               V1's frames copied into a stack chunk
t2      runs V3               runs V2               V1 chunk parked, costs kilobytes, no OS thread
t3      runs V3               V2 blocks; C2 picks   V1's sleep ended: V1 is runnable again
                              V1 up and remounts it V1's frames copied back onto C2

What you see: the carrier name can change across the blocking call.

consoleruns offline
# illustrative output
before: VirtualThread[#21,v1]/runnable@ForkJoinPool-1-worker-1
after:  VirtualThread[#21,v1]/runnable@ForkJoinPool-1-worker-2     <- same virtual thread, different carrier

Why: the thread identity lives on the heap, and a carrier is only borrowed while the virtual thread is actually running.

Platform thread versus virtual thread
PropertyPlatform threadVirtual thread
Scheduled byThe operating systemThe Java runtime (ForkJoinPool of carriers)
StackFixed reservation, megabyte scaleHeap chunks that grow with real depth
While blocked on I/O or sleepHolds an OS threadUnmounted: holds no carrier
Daemon?ConfigurableAlways

Land it A virtual thread makes blocking nearly free by unmounting at the block point — you keep simple blocking code and gain the scalability people used to rewrite into async frameworks to get.

Likely follow-ups
"What is the carrier pool actually, and can you tune it?"

It is a ForkJoinPool in FIFO mode owned by the virtual thread scheduler, distinct from the common pool. Its parallelism defaults to the number of available processors, which inside a container is the CPU quota the JVM detects.

Three system properties tune it: jdk.virtualThreadScheduler.parallelism sets the number of carriers, jdk.virtualThreadScheduler.maxPoolSize caps how many extra carriers can be added temporarily to compensate for pinned threads, defaulting to 256, and jdk.virtualThreadScheduler.minRunnable keeps a minimum number of carriers unparked.

As of Aug 2026 there is no supported way to supply a custom scheduler; that has been discussed for a future release but is not in JDK 25.

In practice I leave the defaults alone and only raise parallelism if I have measured that CPU-bound sections between blocking calls are starving the carriers.

scheduler propertiesruns offline
java -Djdk.virtualThreadScheduler.parallelism=8 \
     -Djdk.virtualThreadScheduler.maxPoolSize=256 \
     -jar app.jar        # parallelism defaults to the CPU count, maxPoolSize to 256
"What happens to a virtual thread's stack when it unmounts, and what does that cost?"

The runtime copies the frames that belong to the virtual thread from the carrier's native stack into a heap object called a stack chunk, and on remount copies them back.

The copy is lazy and proportional to depth: a virtual thread blocked inside a shallow request handler moves a few hundred bytes, while one blocked twenty frames deep in a framework moves a few kilobytes.

The unmount plus remount pair costs on the order of a microsecond, which is comparable to a platform thread context switch but done without a kernel transition.

The heap cost is the chunk itself, so a hundred thousand parked virtual threads with shallow stacks consume on the order of a hundred megabytes, and those chunks are ordinary garbage-collected objects.

That is the whole memory story: stacks stop being a fixed reservation and become heap sized by real usage.

"Does a virtual thread ever get preempted, and what breaks if it never yields?"

No. As of JDK 25 the scheduler is cooperative: a virtual thread runs on its carrier until it blocks, yields with Thread.yield(), or finishes. There is no time slice.

So a virtual thread that runs a tight CPU loop for ten seconds holds its carrier for ten seconds, and with eight carriers, eight such loops stall every other virtual thread in the process, including ones that just need a microsecond to finish a request.

That is the mechanism behind "virtual threads do not help CPU-bound work", and it is also why I keep CPU-heavy tasks on a separate platform thread pool.

I would detect it with a JFR recording where jdk.VirtualThreadPinned is silent but carrier threads show long RUNNABLE stretches in one method.

"Are virtual threads daemon threads, and what does that mean for shutdown?"

Yes, always. A virtual thread is a daemon thread and cannot be changed.

So the JVM will exit when the last non-daemon platform thread ends, even if a million virtual threads are mid-request.

daemon surpriseruns offline
Thread.ofVirtual().start(() -> sleepFiveSeconds());
// main returns here
// Result: the JVM exits at once; the virtual thread never finishes its work

With a platform pool, the pool's non-daemon workers kept the process alive until shutdown finished; with virtual threads I have to hold the process open explicitly.

In a Spring Boot service the main thread and the server's acceptor are non-daemon, so it is not an issue, but in a standalone job that submits work to newVirtualThreadPerTaskExecutor() I must call close() on the executor, which waits for all tasks, or the program exits with work unfinished.

I mention it because it is the single most common surprise in a first Loom migration of a batch tool.

Q216 · Scenario. "A teammate migrated to virtual threads but ran them through a fixed pool of 200 'to be safe'. Requests still queue at 200 concurrent. What do you tell them?"

Reveal answer

Strong answer I would tell them, gently, that pooling virtual threads is an anti-pattern — and walk through why.

  1. Pooling exists to amortize the cost of something expensive to create. A platform thread costs a millisecond and a megabyte, so we reuse them. A virtual thread costs about a microsecond and roughly a kilobyte — there is nothing to amortize, so the right pattern is one fresh virtual thread per task, discarded afterward: Executors.newVirtualThreadPerTaskExecutor().
  2. The cap undoes the migration. Capping them at 200 reinstates the exact ceiling the migration was meant to remove.
    • With virtual threads, a hundred thousand concurrent requests blocked on downstream calls is simply a hundred thousand parked virtual threads: modest heap, no scheduler strain.
    • With 200 pooled threads of any kind you get 200-way concurrency forever.
  3. Then the caveat that shows seniority: the instinct behind "to be safe" is legitimate. Some resources genuinely must be bounded, like database connections or a fragile downstream.
    • The bound belongs on the resource, not on the threads: a Semaphore of 20 around the downstream call, a properly sized connection pool.
    • Limit each scarce resource at its own edge and let thread count float with demand.

Picture it 1,000 simultaneous requests that each wait 200 ms on a downstream, run through a pool of 200 virtual threads and through one virtual thread per task, with the arithmetic.

The setup: a fixed pool of 200 whose threads happen to be virtual.

PoolOfVirtual.javaruns offline
ExecutorService pool = Executors.newFixedThreadPool(200, Thread.ofVirtual().factory());   // ❌ TRAP: a 200-way cap again
for (Request r : thousandRequests) pool.submit(() -> handle(r));      // each handle() waits 200 ms

The trace: the pool admits 200 tasks at a time; the rest sit in the executor's queue.

timelineruns offline
pool of 200:      t=0 ms     200 running, 800 queued
                  t=200 ms   wave 1 done, 200 running, 600 queued
                  t=400 / 600 / 800 ms   waves 2, 3, 4
                  t=1000 ms  wave 5 done: the last request took 1000 ms   ✗
one per task:     t=0 ms     1000 parked virtual threads, 0 queued
                  t=200 ms   all done: the last request took 200 ms   ✓

What you see: the arithmetic for 1,000 requests of 200 ms each.

Latency of the last request
SetupWaves neededLast request finishes
Fixed pool of 200 virtual threads1000 / 200 = 55 x 200 ms = 1000 ms
newVirtualThreadPerTaskExecutor()1200 ms

Why: a pool exists to amortize expensive creation, and a virtual thread has nothing to amortize, so the pool only adds a ceiling.

The fix: one virtual thread per task, with the real bound on the scarce resource.

PerTaskWithBulkhead.javaruns offline
ExecutorService exec = Executors.newVirtualThreadPerTaskExecutor();   // ✅ FIX: no thread cap
Semaphore downstream = new Semaphore(20);                             // the fragile resource, bounded at its own edge

Response call(Request r) throws Exception {
    downstream.acquire();
    try { return client.send(r); } finally { downstream.release(); }
}

What you see now: the cap moved from "threads" to "calls into the downstream".

timelineruns offline
# only the downstream call is limited to 20 at once; parsing, mapping and other work run unbounded
t=0 ms     1000 virtual threads started, 20 inside the downstream call, 980 parked on the semaphore  ✓

Land it With virtual threads you stop rationing threads and start rationing the actual scarce resources — semaphores at the bottlenecks, unbounded cheap threads everywhere else.

Likely follow-ups
"If threads are unbounded, what stops a traffic spike from taking down the whole service?"

Bounds on the resources that matter, plus a concurrency limit at the door. Threads are no longer the scarce resource, but heap, database connections, downstream capacity and CPU still are.

So I put a Semaphore or a Resilience4j bulkhead around each downstream call, size the connection pool to the database, and put a request-level concurrency limiter at the server: Tomcat's server.tomcat.threads.max stops meaning much with virtual threads, so I use an explicit limit such as a filter that takes a permit and returns 503 when none is free.

The sizing comes from Little's law: acceptable concurrent requests equals target throughput times target latency.

Little's lawruns offline
concurrent requests = throughput x latency = 500 req/s x 0.2 s = 100 in flight

A spike beyond that is shed fast instead of accepted and then timed out.

That is the honest version: virtual threads remove one artificial bound and force me to state the real ones.

"How does Spring Boot switch to virtual threads, and what actually changes underneath?"

spring.threads.virtual.enabled=true, available since Spring Boot 3.2 on JDK 21.

application.propertiesruns offline
spring.threads.virtual.enabled=true

It makes Tomcat's executor create a virtual thread per request instead of using its bounded worker pool, switches the @Async executor and the scheduled task executor to virtual threads, and does the same for Kafka listeners and a few other integrations.

What does not change is anything below the framework: HikariCP still has a maximum pool size, so more than that many requests still wait for a connection; a JDBC driver that blocks inside synchronized still pins on JDK 21, which JDK 24 fixed; and RestTemplate or RestClient still enforce their own connection pool limits.

I turn the flag on in a canary, watch the connection acquire wait and pinned events, and expect the visible effect to be more concurrency at the same latency, not lower latency.

"Is there ever a reason to limit virtual thread count directly?"

Rarely, and the honest reason is memory, not scheduling. Each parked virtual thread costs its stack chunk plus whatever objects the request holds, so if a request retains a megabyte of buffers, a million in-flight requests is a terabyte.

A semaphore around the request as a whole, which is effectively a thread count limit, is then a memory bound in disguise. The cleaner statement is that I bound in-flight work, and virtual threads happen to be one per unit of work.

The other reason is a downstream that counts open connections rather than requests; there the bound belongs on the client connection pool.

I would never write a fixed pool of virtual threads, because it combines the queuing of a pool with none of the reuse benefit, but a Semaphore around task submission is legitimate.

"What would you monitor after the migration to know it worked?"

Four things. First, the JFR events jdk.VirtualThreadPinned and jdk.VirtualThreadSubmitFailed, both of which should be near zero. Second, the count of live virtual threads, which I get from jcmd PID Thread.dump_to_file -format=json or from a Micrometer gauge if the framework exposes it; it should track in-flight requests.

Third, the resource waits that were previously hidden behind the thread cap: HikariCP pending connections and bulkhead rejections, which now show the true demand.

Fourth, heap and GC: more in-flight requests means more live objects, so I expect old-generation occupancy to rise a little and want to know by how much.

If pinned is zero, connection waits are flat, and throughput per pod rises under load test, the migration paid off.

Q217 · Scenario. "You moved a JDBC-heavy service to virtual threads and throughput collapsed under load instead of improving. Walk me through the diagnosis."

Reveal answer

Strong answer Collapse under load after a Loom migration points straight at pinning, and I would run the investigation in this order:

  1. State the hypothesis.
    • Pinning: when a virtual thread blocks while inside a synchronized block or method (or a native call), the runtime cannot unmount it. It pins its carrier thread.
    • Why it collapses: there are only about as many carriers as cores, so a handful of threads blocking while pinned occupies the entire scheduler, and every other virtual thread in the process starves.
    • Why JDBC: JDBC (Java Database Connectivity) is the classic trigger, because many drivers and connection pools historically wrapped their socket operations in synchronized.
  2. Confirm it with the purpose-built tools: run with -Djdk.tracePinnedThreads=full, which prints a stack trace whenever a virtual thread parks while pinned, or record with JFR — Java Flight Recorder — and look for jdk.VirtualThreadPinned events. Either will name the exact synchronized frame, typically deep in the driver or pool.
  3. Fix in order of preference:
    1. Upgrade the driver and connection pool to versions that replaced synchronized with ReentrantLock, which does not pin because the runtime can unmount through it.
    2. If it is our own code, narrow the synchronized region so no blocking call sits inside it, or switch that region to ReentrantLock.
    3. As a stopgap, route the offending calls to a small platform-thread executor.
  4. Add the currency note: as of recent JDKs — JDK 24's JEP 491 — blocking inside synchronized no longer pins at all, so I would first check which version we run; on older long-term-support releases the problem is fully live.

Prevention: watch jdk.VirtualThreadPinned in performance tests before every migration.

Picture it A 4-core box with 4 carriers, each held by a virtual thread blocked inside synchronized, at successive moments, plus the diagnostic output and the fix.

The setup: a data-access method that blocks on the socket while holding a monitor, on a JDK where that pins (JDK 21 to 23).

Dao.javaruns offline
private final Object lock = new Object();

List<Row> query(String sql) {
    synchronized (lock) {                 // ❌ TRAP: blocking inside synchronized pins the carrier
        return jdbc.query(sql);           // the socket read happens inside the monitor
    }
}

Make the invisible visible: carriers and the queue of runnable virtual threads at three moments.

carriers over timeruns offline
moment  C1        C2        C3        C4        runnable queue
t0      V1 runs   V2 runs   V3 runs   V4 runs   V5 V6 V7 ...
t1      V1 pinned V2 pinned V3 pinned V4 pinned V5 V6 V7 V8 V9 ...   each is blocked in query(), carrier idle
t2      (same)    (same)    (same)    (same)    queue keeps growing: throughput collapses  ✗
# the scheduler may add compensating carriers up to maxPoolSize (256), so the effect is a collapse, not a total freeze

What you see: the pinning trace on JDK 21 (the property below); on JDK 24 and later use the JFR event instead.

-Djdk.tracePinnedThreads=full outputruns offline
# illustrative output (abridged)
Thread[#29,ForkJoinPool-1-worker-1,5,CarrierThreads]
    java.base/java.lang.VirtualThread$VThreadContinuation.onPinned(VirtualThread.java)
    ...
    com.example.Dao.query(Dao.java:5) <== monitors:1      <- the synchronized frame that pins

Why: a virtual thread inside a monitor cannot be unmounted on those JDKs, so its carrier waits with it.

The fix: a ReentrantLock, which the runtime can unmount through.

DaoFixed.javaruns offline
private final ReentrantLock lock = new ReentrantLock();

List<Row> query(String sql) {
    lock.lock();
    try { return jdbc.query(sql); }       // ✅ FIX: blocking here unmounts the virtual thread
    finally { lock.unlock(); }
}

What you see now: the pinned-event check after the fix.

consoleruns offline
$ jfr print --events jdk.VirtualThreadPinned recording.jfr
$                                         <- prints nothing: no pinning ✓

Going deeper Two details date this answer.

As of Aug 2026, the -Djdk.tracePinnedThreads property was removed in JDK 24 along with the synchronized pinning it diagnosed; on JDK 24 and 25 the supported way to see pinning is the JFR event jdk.VirtualThreadPinned, which now also records the reason and the carrier.

The remaining pinning cases on JDK 25 are native frames on the stack, a class initializer in progress, and blocking inside a Object.wait in a native method; none of these is common in application code, but JNI-based drivers and some native crypto libraries can still trigger them.

Also the cap: while a virtual thread is pinned and blocked, the scheduler temporarily adds a carrier, up to jdk.virtualThreadScheduler.maxPoolSize (256 by default), which is why the collapse is a slowdown rather than a total freeze.

A quick verification after the fix is to run the load test with -XX:StartFlightRecording and check that jfr print --events jdk.VirtualThreadPinned recording.jfr prints nothing.

Land it Pinning turns a million cheap threads back into eight expensive ones — trace it with tracePinnedThreads or JFR, fix the synchronized-around-blocking, and know whether your JDK is new enough to have retired the problem.

Likely follow-ups
"You upgraded the driver and the pool, pinning events are gone, and throughput still didn't improve. What next?"

Then the bottleneck was never the threads. I look at the database connection pool first: with 200 platform threads and a pool of 20, only 20 requests were ever in the database at once, and that is still true with a million virtual threads.

HikariCP's hikaricp_connections_pending and the acquire timer will show requests queuing for connections.

pool arithmeticruns offline
200 platform threads, pool of 20 -> 20 requests in the database at once
1,000,000 virtual threads, pool of 20 -> still 20 in the database; the rest wait for a connection

The fix is to size the pool to what the database can serve, which for a 16-core Postgres is around 30 to 40 active connections in total across the fleet, and to reduce time per connection by shortening transactions.

If the pool is not the wait, I check CPU: a JDBC-heavy service often spends most of its CPU in result-set mapping and JSON, and virtual threads add nothing there. The load test should show where the new wait moved to; it always moves somewhere.

"What is the difference between pinning and a virtual thread that is simply CPU-bound on its carrier?"

Pinning is a blocked virtual thread that cannot unmount, so the carrier sits idle waiting. A CPU-bound virtual thread is a running one that holds the carrier because it never blocks, so the carrier is busy.

Both starve other virtual threads, but the evidence differs: pinning produces jdk.VirtualThreadPinned events and shows carriers in a blocked or waiting state with the virtual thread's frames on top; CPU-bound shows carriers RUNNABLE at 100% in top -H with the same application frame across dumps and no pinned events.

The fixes also differ: pinning is fixed by removing the blocking-inside-synchronized or native frame, or by upgrading to JDK 24 or later; CPU hogging is fixed by moving that work to a dedicated platform pool or by breaking it into chunks with Thread.yield() between them, which is a code smell but sometimes necessary.

"How would you check in advance whether your dependencies are Loom-friendly?"

Three checks before migration.

First, a static one: search the dependency jars for synchronized around I/O, which the jdeps tool cannot do but a quick decompile or the project's Loom compatibility notes can; the major drivers, HikariCP, the Postgres and MySQL JDBC drivers, Apache HttpClient 5 and Netty, all published fixes between 2023 and 2024.

Second, a dynamic one: run the integration test suite on JDK 21 with -Djdk.tracePinnedThreads=full, or on JDK 24 and later with JFR and jdk.VirtualThreadPinned enabled at a low threshold, and read every stack it prints.

Third, a load test with the migration flag on, comparing throughput at fixed latency against the platform-thread baseline. If any step shows pinning inside a library I cannot change, I isolate those calls on a small platform pool until the library catches up.

"What would you do differently on JDK 25 versus JDK 21 for this migration?"

On JDK 25 I would skip most of the synchronized worry, because JEP 491 in JDK 24 made monitors unmount cleanly, and I would spend the effort on the resource bounds instead.

I would use ScopedValue, final since JDK 25, for request context in place of ThreadLocal, which removes the per-thread copy cost. I would still avoid structured concurrency in production code because it remains preview in JDK 25.

On JDK 21 I would treat every synchronized-around-I/O as a blocker, upgrade drivers first, and keep the tracing property on in staging. On both versions the monitoring is the same: pinned events, connection pool waits, and live virtual thread count.

The honest summary is that JDK 21 is where Loom is usable and JDK 24 is where it stopped needing a checklist.

Q218. "When do virtual threads NOT help?"

Reveal answer

Strong answer They do not help CPU-bound work at all.

Virtual threads multiplex onto roughly one carrier per core, so total computation is still capped by the cores.

A million virtual threads crunching numbers is the same hardware doing the same arithmetic, with extra scheduling overhead on top.

For computation, a platform pool sized to cores or a parallel stream remains the right tool.

Second, they do not make any individual request faster. A call that takes 200 milliseconds still takes 200 milliseconds.

The win is in how many such waits can be in flight concurrently, so a low-concurrency service gains nothing.

Third, a system already built thread-per-core around event loops, like a tuned Netty stack, has already solved the blocking problem another way.

The honest framing: virtual threads make waiting cheap, and only workloads dominated by waiting benefit.

Picture it One task of each kind drawn as a timeline of CPU and waiting, and the throughput arithmetic on an 8-core box for each thread model.

The setup: two workloads: a pure computation, and a request that mostly waits on a downstream.

Workloads.javaruns offline
Runnable crunch = () -> burnCpu(100);                       // 100 ms of arithmetic, never blocks
Runnable waiter = () -> { callDownstream(); parse(); };     // 200 ms blocked, then 5 ms of CPU

Make the invisible visible: where each task spends its time and what the carrier is doing meanwhile.

task timelinesruns offline
crunch:  [=========== CPU 100 ms ===========]          carrier is busy the whole time: nothing to unmount
waiter:  [..][ ......... wait 200 ms (unmounted) ......... ][=]
          CPU                carrier free for others            CPU

What you see: capacity per second on 8 cores (throughput = threads / time per task, capped by CPU).

Throughput by thread model
WorkloadPlatform pool of 8Platform pool of 200Virtual threads
crunch, 100 ms CPU80 / s80 / s (8 cores are the limit)80 / s (8 cores are the limit, plus overhead)
waiter, 200 ms wait + 5 ms CPUabout 39 / s (8 / 0.205)about 975 / s (200 / 0.205)up to 1,600 / s (8 cores / 0.005 s), with about 330 in flight
waiter at 10 requests / s2 in flight: fine2 in flight: fine2 in flight: fine, nothing gained

Why: virtual threads remove the thread count as the limit, and when the limit is the cores or the request rate, there is nothing left to gain.

The fix: for computation, size the pool to the cores.

CpuPool.javaruns offline
ExecutorService cpu = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());   // ✅ FIX for CPU-bound work
// waiting-bound work: Executors.newVirtualThreadPerTaskExecutor()

Land it Virtual threads buy cheap waiting, not cheap computing — if your threads are busy rather than blocked, nothing changes except overhead.

Likely follow-ups
"How much overhead do virtual threads add to a CPU-bound task, and how would you measure it?"

For a task that never blocks, almost none once it is running; the cost is at creation and at the mount, roughly a microsecond, and the scheduler's queue operations.

The measurable overhead appears when there are many more virtual threads than carriers all doing CPU work: each unmount and remount around a yield copies stack frames, and the scheduler's work-stealing adds cache misses.

In a JMH benchmark comparing a fixed platform pool of core-count threads against a virtual thread per task on a pure compute loop, I expect the virtual version to be within a few percent when tasks are long, and noticeably slower when tasks are tiny, because creation cost dominates.

The right measurement is throughput at saturation, not latency, and I would run it on the target container's CPU quota, since the carrier count follows that quota.

"Would you use virtual threads for a parallel stream over a big collection?"

No. Parallel streams run on the ForkJoinPool common pool, which is sized to the core count, and that is the correct shape for CPU-bound splitting. Virtual threads add nothing to arithmetic and cannot be plugged into a parallel stream anyway.

The case where I do combine them is a stream whose per-element work blocks, such as calling a remote service for each of a thousand items.

There a parallel stream is wrong because it ties up the common pool. The right shape is a virtual thread per item submitted to newVirtualThreadPerTaskExecutor(), with a semaphore limiting how many remote calls are in flight.

compute versus waitruns offline
long total = data.parallelStream().mapToLong(Work::cpu).sum();           // compute per element

try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {             // waiting per element
    for (Item i : items) ex.submit(() -> callRemote(i));                 // close() waits for all tasks
}

So the rule is: compute per element goes to the parallel stream, waiting per element goes to virtual threads, and mixing the two means separating the phases.

"Does a service on Netty or WebFlux gain anything by adding virtual threads?"

Very little on the hot path, because the event loop already avoids blocking threads. Where they help is in the escape hatches: the places where reactive code has to call a blocking library, which today go through Schedulers.boundedElastic(), a pool of platform threads.

Swapping that scheduler for a virtual-thread-backed one, which Reactor supports since 3.6 via Schedulers.boundedElastic() when virtual threads are enabled, makes those blocking calls cheap and removes the pool's cap.

The larger strategic point I would make is that for a new service on JDK 21 or later I would not choose a reactive stack at all, because virtual threads give the scalability with ordinary blocking code and readable stack traces, and I would keep WebFlux only where the reactive streams model itself is the value, such as backpressured streaming.

"What about a service with only ten requests per second — should it migrate?"

There is no throughput reason to.

Little's lawruns offline
concurrent requests = 10 req/s x 0.2 s = 2 in flight

At ten requests a second with 200 millisecond latency, Little's law gives two concurrent requests. A pool of 200 platform threads is 99% idle, and virtual threads change nothing a user could see.

I would still consider migrating for two secondary reasons: memory, since each idle platform thread reserves stack that a small container pays for, and consistency, since one threading model across the fleet is easier to reason about.

But I would not spend migration and testing time on it ahead of a service that is actually queuing on its thread pool.

The interview answer is that virtual threads are a scalability tool, and a service with no scalability problem gets no benefit and some risk.

Q219 · Scenario. "Memory ballooned after the move to virtual threads, and the heap dump shows huge retained size under ThreadLocal maps. Explain and fix."

Reveal answer

Strong answer ThreadLocal cost scales with thread count, and the migration multiplied the thread count by orders of magnitude.

  1. The arithmetic first: each thread holds its own private copy of every thread-local value. A 20-kilobyte cached buffer per thread was 4 megabytes across a 200-thread pool — invisible. Across a million virtual threads it is 20 gigabytes. Nothing leaked; a pattern priced for hundreds of threads was reused at a scale it was never priced for.
  2. The heap dump confirms it: retained size hanging off each thread's thread-local map, with the offending value type named — typically pooled buffers, cached formatters like SimpleDateFormat, or per-thread scratch objects.
  3. Note the second, quieter loss: those caches existed to amortize creation cost across many tasks on a long-lived pooled thread. Virtual threads are born and die with a single task, so the cache never gets a second hit — the pattern is now all cost, no benefit.

Fixes, in order: delete per-thread caching where the object is cheap or immutable — DateTimeFormatter is thread-safe and shareable, unlike the old SimpleDateFormat; pool the genuinely expensive resource itself explicitly instead of hiding a copy per thread; and for passing request context, note the platform's direction — ScopedValue, finalized in recent JDKs, binds an immutable value to a scope and shares it with child threads rather than copying per thread, designed precisely for the million-thread world.

Land it ThreadLocal multiplies its footprint by thread count — a pattern that was cheap at 200 threads is a heap-sized bill at a million, and ScopedValue is the replacement built for that scale.

Likely follow-ups
"How does ScopedValue actually differ from ThreadLocal in mechanism, not just intent?"

A ThreadLocal is a mutable map entry per thread: any code can call set at any time, the value lives until remove is called or the thread dies, and child threads created with InheritableThreadLocal get a copy.

A ScopedValue is bound only for the dynamic extent of a ScopedValue.where(KEY, value).run(() -> ...) call; inside that call KEY.get() returns the value, outside it throws NoSuchElementException, and it cannot be reassigned, only rebound in a nested scope.

There is no per-thread map to leak and no remove to forget; the binding is unwound when the scope exits, like a stack frame. Child virtual threads forked inside a StructuredTaskScope see the parent's bindings by reference, not by copy.

As of Aug 2026 it is final in JDK 25 via JEP 506.

"You cannot rewrite the framework code that uses ThreadLocal. What do you do in the meantime?"

Two mitigations that need no framework change. First, make the per-thread values small or shared: if the thread-local holds a buffer, shrink it or replace it with a bounded pool of buffers borrowed and returned per request, so a million threads share a few hundred buffers.

Second, cap in-flight requests with a semaphore so that the number of live virtual threads, and therefore the number of thread-local copies, is bounded by a number I chose from memory arithmetic.

I also check whether the thread-local is actually needed on virtual threads; Spring's RequestContextHolder and MDC values are cheap, and the expensive ones are almost always caches such as SimpleDateFormat or Jackson buffers that I can replace with thread-safe shared instances.

And I verify with a heap dump histogram that the retained size under ThreadLocalMap drops after each change.

"Why did the ThreadLocal values survive at all, given virtual threads die after one task?"

Because the dump was taken while the threads were alive, and at a million in-flight requests the sum is enormous even if each thread lives for two hundred milliseconds.

The thread-local map is reachable from the thread object, so it is only collectable when the virtual thread finishes and nothing else references it.

There is also a second, longer-lived trap: if the code stores a thread-local on a carrier thread rather than the virtual thread, for example by calling a library that caches on the current thread during a pinned native section, the value stays for the carrier's lifetime and is shared across every virtual thread that mounts there, which is both a leak and a correctness bug.

In a heap dump the carrier case shows the retained values hanging off ForkJoinWorkerThread instances rather than VirtualThread instances, which is how I tell the two apart.

"How would you propagate logging MDC context to virtual threads correctly?"

The MDC in SLF4J and Logback is a ThreadLocal map, so a child thread starts empty. With a thread-per-request model that was fine because the request thread set it once.

With virtual threads spawned per subtask I have to copy it: capture MDC.getCopyOfContextMap() before forking and call MDC.setContextMap at the start of the child, then clear it in finally.

Spring Boot 3.2 and later do this automatically through Micrometer's context propagation when spring.threads.virtual.enabled is on and the observation API is in use. Longer term, Logback and Log4j are moving toward ScopedValue-based context where the value is visible to forked children for free.

Until then the copy is a couple of lines in a task decorator, and I test it with a log assertion that the request ID appears on a line written from inside a forked subtask.

Q220. "What is structured concurrency, in plain words?"

Reveal answer

Strong answer Structured concurrency treats a group of concurrent subtasks the way a code block treats statements: they start inside a scope, and the scope does not exit until every one of them has completed or been cancelled.

Today an ExecutorService allows a submitted task to outlive the method that submitted it — a thread quietly leaks past its context, and no stack trace connects it back.

With StructuredTaskScope — the API arriving through recent JDK previews, JEP 505 — I open a scope, fork the subtasks, and join; the policy object decides the semantics, so a shutdown-on-failure scope cancels all remaining siblings the moment one fails, and the parent rethrows the failure with the parent-child relationship visible in thread dumps.

The plain-words payoff: concurrency gets the shape of a function call — one entry, one exit, errors that propagate upward, and no orphaned threads running on after everyone forgot them.

Going deeper The API changed shape across previews, and an interviewer current as of Aug 2026 will expect the JDK 25 form.

The scope is now opened with a static factory rather than a constructor, and the policy is a Joiner: StructuredTaskScope.open() with no arguments fails on the first subtask failure, Joiner.anySuccessfulResultOrThrow() returns the first success and cancels the rest, and Joiner.allSuccessfulOrThrow() collects every result.

Subtasks are forked with scope.fork(callable), which returns a Subtask, and scope.join() both waits and applies the joiner's policy, throwing FailedException wrapping the cause. Every subtask runs on a fresh virtual thread by default.

The scope must be closed on the thread that opened it, so it lives in a try-with-resources block, and closing a scope with unfinished subtasks interrupts them.

Because it is still a preview in JDK 25, compiling requires --enable-preview, which is why teams on the LTS mostly wait.

Land it It does for fork-and-join what structured programming did for goto — concurrent work becomes a block you can reason about, cancel as a unit, and never leak.

Likely follow-ups
"How is this better than CompletableFuture.allOf, which also waits for everything?"

Three ways. Cancellation: with allOf, when one future fails the others keep running to completion and their threads stay busy; the scope interrupts the siblings immediately, so a failed profile lookup does not leave the orders call burning a downstream for two more seconds.

Lifetime: a future can be completed by anyone, anywhere, and the task can outlive the method; a scope guarantees every subtask is finished or cancelled by the time the try block exits, so no thread leaks.

Observability: a thread dump in JSON from jcmd Thread.dump_to_file shows the parent-child tree of the scope, whereas futures give unrelated pool threads with no link to the request.

What CompletableFuture still does better is composition of asynchronous callbacks without a waiting thread, which matters in a reactive design but not in a virtual-thread one.

"What happens if one subtask ignores interruption?"

Then the scope's cancellation is only a request, and join() returns only after the joiner is satisfied, but close() still waits for that stubborn subtask to finish.

A subtask that loops on CPU without checking Thread.interrupted(), or that blocks in a call that does not respond to interrupt such as an old socket read without a timeout, will hold the scope open.

So the discipline is the same as with any cancellation in Java: blocking calls need timeouts, and long loops need an interrupt check.

In practice I would put a deadline on the scope itself, joinUntil(Instant) in the preview API, so the parent throws a timeout and a monitoring alert tells me a subtask is not honouring cancellation, which is then a bug to fix in that subtask rather than in the scope.

"Would you use it in production today, given it's still preview?"

Not in a shared library or a long-lived service on the LTS, and I would say so plainly.

Preview APIs can change between releases, require --enable-preview at compile and run time, and bind the deployment to the exact feature version, so a JDK 25 preview class file refuses to run on JDK 26.

For an internal tool that the team rebuilds on every JDK bump, it is fine and a good way to learn the model.

In production on JDK 21 or 25 I get most of the benefit by hand: a virtual-thread executor per request in a try-with-resources block, futures submitted to it, and a helper that cancels the rest on first failure.

That is a dozen lines, and it migrates to StructuredTaskScope almost mechanically once it goes final.

"How does structured concurrency interact with ScopedValue?"

They were designed together. A ScopedValue bound in the parent is visible in every subtask forked inside a StructuredTaskScope opened within that binding, without copying, because the subtask's lifetime is guaranteed to be nested inside the parent's binding.

That guarantee is exactly what an unstructured executor cannot give: a task submitted to a pool might run after the parent's scope has exited, so a scoped value would be dangling, which is why ScopedValue deliberately does not propagate into plain executor tasks.

The combination gives me a request ID, a tenant, or a deadline available in every subtask with no thread-local copying and no leak, and it is the intended replacement for the InheritableThreadLocal pattern.

I would mention that Spring's request context is expected to move onto this in a future major release.

08 · Production debuggingDebugging Threads & JVMs in Production — Q221–Q260

This is the section where nine years of experience either shows or does not. When a service melts at 2am, the interviewer does not want theory — they want a calm, ordered procedure: which command you type first, what its output means, and how each observation decides the next step. Most questions here are scenarios; answer them as a numbered sequence of moves, naming real tools and real flags, and always finish with the fix and the prevention.

Drill · Thread dumps — the core skill

Whether you can capture a thread dump under pressure, read the lock chains inside it by hand, and tell a genuinely stuck thread from a healthy idle one.

Q221. "Your Java service is misbehaving in production right now. What are all the ways you can capture a thread dump, and which do you reach for first?"

Reveal answer

The real test Have you actually done this on a live box, or only read about it.

Strong answer A thread dump is a plain-text snapshot of every thread inside the JVM — the Java Virtual Machine, the process running your code — showing each thread's name, its state, and the stack of method calls it is in at that instant. I have five ways to get one:

  • jcmd PID Thread.print — my first choice. jcmd is the JDK's modern all-purpose diagnostic tool, and the PID — the process id — comes from ps or top.
  • jstack PID — the older dedicated tool; same output.
  • kill -3 PID — sends the SIGQUIT signal, which the JVM catches and answers by printing a dump to its own standard output, not to my terminal, and it does not stop the process. This is the fallback when no JDK tools are installed; I read the dump from the application log or container output.
  • Spring Boot's /actuator/threaddump endpoint over HTTP, when it is exposed.
  • Java Flight Recorder — the JVM's built-in low-overhead event recorder — which can capture thread activity continuously.

One trap worth naming: the attach-based tools must run as the same operating-system user as the JVM, or they refuse to connect.

Land it jcmd when the tools exist, kill -3 when the box is bare — and whichever I use, I take three dumps, never one.

Likely follow-ups
"What does taking a dump cost the running service, and can it make an outage worse?"

A dump requires a safepoint: the JVM asks every thread to stop at its next safepoint poll, waits until all have stopped, walks every stack, prints, and releases.

For a few hundred threads that is typically 10 to 50 milliseconds of total pause, so every in-flight request gets that added to its latency.

It gets expensive with thousands of threads, or with a thread stuck in a long native call or a counted loop without a poll, where the time-to-safepoint itself can be hundreds of milliseconds.

On a service that is already failing this is acceptable, and on a healthy service it is a small blip. What I avoid is a script taking dumps every second on an autoscaled fleet, which turns diagnostic pauses into a latency regression.

Three dumps ten seconds apart during an incident is the right dose.

"jcmd says 'Unable to open socket file' or 'well-known file is not secure'. What's wrong?"

That is the attach mechanism refusing. jcmd connects through a Unix socket in /tmp/.java_pid<PID>, created when the JVM receives an attach request.

The "not secure" message means the socket file belongs to a different user, so I am not running as the JVM's user; the fix is sudo -u appuser jcmd.

"Unable to open socket file" usually means the JVM cannot create the file: /tmp differs between my shell and the JVM, which is common in containers with private tmp, or the JVM was started with -XX:+DisableAttachMechanism, or the process is in a different PID namespace so my PID does not match.

In Kubernetes the answer is a debug container sharing the process namespace, and if attach is disabled the fallback is kill -3, which needs no socket.

"What extra information do jcmd's flags add over the basic dump?"

jcmd PID Thread.print -l adds the "Locked ownable synchronizers" section, which lists which thread owns each ReentrantLock and other java.util.concurrent locks; without -l those locks are invisible, and a lock leak looks like threads parked for no reason.

-e adds extended information such as CPU time and allocated bytes per thread, which lets me sort threads by CPU consumption without top -H.

Since JDK 21, jcmd PID Thread.dump_to_file -format=json /path writes a structured dump that includes virtual threads grouped by their scope, which Thread.print and jstack both omit.

So my full incident command on a modern JDK is two calls: the classic print with -l -e for lock ownership and CPU, and the JSON dump for the virtual thread population.

"How do you make sure the dump you took during the incident does not get lost?"

By writing it somewhere that survives the pod.

With kill -3 the dump goes to the JVM's standard output, which in Kubernetes lands in the container log; those logs are kept only until the pod is deleted or rotates, so I copy them out immediately with kubectl logs POD --since=5m > dump.txt.

With jcmd I redirect to a file on a mounted volume, not to the container's writable layer.

I also put the dump into the incident ticket right away, along with the exact time and the pod name, because the value of a dump is in correlating it with metrics later.

And the durable fix is always-on Flight Recorder writing to a persistent volume, so the record exists even if nobody ran a command during the outage.

Q222. "Why do experienced engineers take three thread dumps five to ten seconds apart instead of just one?"

Reveal answer

Strong answer Because a single dump is a photograph, and the problems I am hunting are movies.

A thread photographed inside a database read might have been there for two milliseconds or for twenty minutes — one snapshot cannot tell those apart, and the two mean completely different things.

With three dumps spaced a few seconds apart I compare thread by thread, matched on name: a thread sitting in the exact same stack frame in all three dumps is stuck, and that frame is my suspect; threads whose stacks changed between dumps are doing work and can be ignored.

The spacing also turns counts into trends — if the number of blocked threads is 40, then 90, then 150 across the three dumps, the service is actively draining toward a full stall rather than sitting in a bad but stable state.

Land it One dump shows state; three dumps show motion, and it is the absence of motion that convicts a thread.

Likely follow-ups
"How do you actually diff three dumps quickly, rather than reading them side by side?"

I script it. Each thread's entry starts with a quoted name, so I extract name plus top three frames from each dump with a short awk or a tool like FastThread or IBM TMDA, then join on the name.

A one-liner that works on a bare box: for each dump, print the thread name and the first at line on one row, sort, then comm -12 the three outputs to list threads whose top frame is identical across all three.

That list is my suspect set, and it is usually a handful of threads out of hundreds. Pool threads idling in getTask will also match, so I filter out frames in java.util.concurrent and Unsafe.park under pool plumbing.

What remains is threads stuck in application code, and those get read by hand.

"Why ten seconds apart and not one second or one minute?"

Because the interval must be longer than a normal request and shorter than the incident.

A request that takes 200 milliseconds will have changed its stack completely within ten seconds, so a thread still in the same frame is genuinely stuck rather than caught twice in one slow call.

One second apart would be too close; a legitimately slow database query of two seconds would look stuck.

One minute apart would be too far in an active incident where the service may be restarted or the load balancer may drain the pod before the third dump.

If the service's slowest legitimate operation is a 30-second report, I stretch the interval to a minute so that report does not count as stuck. The principle is that the spacing is set by the slowest healthy operation, not by a fixed rule.

"Three dumps show nothing stuck, yet the service is slow. What does that tell you?"

It tells me that no single thread is the problem, and I should stop reading dumps.

Threads that keep moving mean the work is progressing, just slower than it should, which points to a shared resource: garbage collection pauses that stop everyone equally, CPU throttling from a container quota, a saturated connection pool where threads spend a little time waiting on every request, or a downstream that is slow on every call rather than hung.

Each of those has its own evidence: the GC log, the cgroup's cpu.stat throttled counters, HikariCP pending and acquire time, and the downstream latency histogram.

So a clean set of dumps is a real finding: it eliminates the deadlock and the stuck-thread family and sends me to the metrics for a distributed slowdown. The junior mistake is taking a fourth and fifth dump hoping to catch something.

Q223. "You open a thread dump. Walk me through what each part of a thread's entry means, and how you trace lock ownership by hand."

Reveal answer

The real test Can you read the raw text without a tool doing it for you.

Strong answer Each entry starts with a header line: the thread's name in quotes, whether it is a daemon, its priorities, tid — the JVM's internal address for the thread — and nid, the native thread id in hexadecimal, which is the id the operating system knows this thread by; that nid is how I join a dump against top output later.

The next line is java.lang.Thread.State: RUNNABLE means executing or ready to execute, BLOCKED means waiting to enter a monitor — the built-in lock every Java object carries — WAITING and TIMED_WAITING mean the thread parked itself deliberately. Then comes the stack, newest frame first.

Woven between frames are the lock annotations, and they are the gold: - locked <0x000000076ab62208> means this thread currently holds that object's monitor, while - waiting to lock <0x000000076ab62208> means it is blocked wanting it.

To trace ownership I copy the hex address a blocked thread is waiting on, search the whole dump for locked followed by that same address, and that finds the owner.

I then read the owner's stack; if the owner is itself waiting on a different address, I repeat.

I am building the lock-dependency chain by hand, and the thread at the end of that chain — the one holding a lock while doing something slow — is the root cause.

Land it The skill is not reading one thread; it is chasing one hex address across two hundred threads to find who everyone is really waiting for.

Likely follow-ups
"What does 'waiting on' versus 'waiting to lock' versus 'parking to wait for' mean in the annotations?"

They are three different waits. waiting to lock <addr> is a BLOCKED thread trying to enter a synchronized block whose monitor another thread holds; the owner is the thread whose stack shows locked <addr>.

waiting on <addr> is a thread inside Object.wait(); it already held that monitor, released it, and is asleep until someone calls notify, so nobody is blocking it, it is waiting for a signal.

parking to wait for <addr> is a thread in LockSupport.park, which is what every java.util.concurrent primitive uses; the object named is the lock, latch, future or queue, and to find who holds a ReentrantLock I need the -l flag's "Locked ownable synchronizers" section, because the owner's own stack carries no locked line for it.

"How can two threads both show 'locked' the same address in one dump?"

In a legitimate dump they cannot both own the same monitor, but there are two ways to see it.

First, reentrancy: a single thread that entered the same synchronized object in two nested frames shows locked twice in its own stack, once per frame, which is fine.

Second, the dump is not atomic in the way people assume: the JVM stops all threads at a safepoint, so ownership is consistent, but the waiting on annotation for a thread in Object.wait() is printed alongside a locked line from the frame that entered the monitor before waiting, even though the wait released it.

So a thread in wait() appears to hold a monitor that another thread genuinely holds. The rule I apply: a locked line above a waiting on for the same address is historical, not current.

"What is the difference between the '#N' number, tid, and nid, and which one do you actually use?"

The #N after the name is the JVM's sequential thread number, assigned at creation, so a very high number in a long-running process is a hint that threads are being created constantly.

The tid is the address of the JVM's internal JavaThread structure; it is unique within the process and useful only for matching entries within tooling.

The nid is the native thread id in hex, which is the Linux thread id the kernel uses, and that is the one I use, because it joins the dump to top -H, to /proc/PID/task/TID, and to perf output.

Since JDK 21 the header also shows cpu= and elapsed= with the -e flag, giving CPU seconds per thread directly, so on a modern JDK I sometimes skip top -H and sort by that field.

"How do you know if a RUNNABLE thread is really running or just sitting in native code?"

By the top frame and by CPU. If the top frame is a Java method, it was executing bytecode at the safepoint and is genuinely busy.

If it is marked (Native Method) such as socketRead0, SocketDispatcher.read0, FileDispatcherImpl.read0 or Inet6AddressImpl.lookupAllHostAddr, the thread is inside the kernel and almost certainly sleeping on I/O, and RUNNABLE is only the JVM's bookkeeping.

The confirmation is CPU: top -H shows the native-waiting thread at zero percent, or the cpu= field in a JDK 21 dump barely moves between two dumps.

One subtlety: Unsafe.park is also native but the state is reported as WAITING, so it never fools anyone; the native reads are the ones that lie.

Q224 · Scenario. "Your API stops responding. CPU is nearly idle. A thread dump shows 190 of the 200 Tomcat request threads BLOCKED. Here is an excerpt — walk me through the full diagnosis and your fix."

Reveal answer

The real test The classic senior scenario: an outage with idle CPU, solved purely by reading the dump.

Strong answer Tomcat's http-nio threads are the worker pool that serves HTTP requests; if they are all blocked, the service is down no matter how healthy everything else looks. The excerpt:

thread-dump-excerpt.txt
"http-nio-8080-exec-113" #241 daemon prio=5 os_prio=0 nid=0x4e2f waiting for monitor entry
   java.lang.Thread.State: BLOCKED (on object monitor)
        at com.shop.cache.PriceCache.get(PriceCache.java:41)
        - waiting to lock <0x000000076ab62208> (a com.shop.cache.PriceCache)
        at com.shop.web.PriceController.price(PriceController.java:28)

"http-nio-8080-exec-7" #35 daemon prio=5 os_prio=0 nid=0x4d80 runnable
   java.lang.Thread.State: RUNNABLE
        at java.net.SocketInputStream.socketRead0(Native Method)
        at com.shop.pricing.PricingClient.fetchAll(PricingClient.java:77)
        at com.shop.cache.PriceCache.rebuild(PriceCache.java:88)
        - locked <0x000000076ab62208> (a com.shop.cache.PriceCache)
  1. I take three dumps ten seconds apart. In all three, roughly 190 threads are BLOCKED, and every one is waiting to lock the same address, 0x000000076ab62208. One monitor is strangling the whole pool.
  2. I search for locked <0x000000076ab62208> and find exactly one holder: exec-7, sitting inside PriceCache.rebuild, which is making a network call — socketRead0 — while holding the lock.
  3. So the story is: the cache's get and rebuild are both synchronized on the cache object; a rebuild was triggered, the pricing service it calls is slow, and for the entire duration of that remote call every request needing a price queues on one monitor. The pool drains, and the service looks dead while the CPU does nothing.

The immediate mitigation is fixing or failing fast the slow pricing call. The real fix is a rule: never perform I/O while holding a lock. Rebuild into a fresh map outside any lock and publish it by swapping a single volatile reference, or serve the stale value while one background thread refreshes. Prevention: a strict timeout on the pricing call, and a code-review habit of checking what runs inside every synchronized block.

Land it Idle CPU plus mass BLOCKED means a lock convoy — find the one holder, and the bug is always what it is doing while holding.

Likely follow-ups
"You fixed the timeout on the pricing call and the same shape came back a week later. What did you miss?"

The timeout shortened the hold time but did not remove I/O from the lock. A two-second timeout still means every request queues behind the rebuild for two seconds, and if the rebuild is retried on failure the lock is held again immediately.

I would also check whether other methods synchronize on the same cache object; a get that is synchronized for no reason, just to read a map, makes every read wait on every rebuild.

The durable fix has three parts: reads are lock-free against a volatile reference to an immutable map; the rebuild runs on one dedicated background thread on a schedule, never on a request thread; and if a rebuild fails, the old map stays in place and a metric records the staleness.

I verify it with a load test where the pricing service is stalled with Toxiproxy and the p99 of the price endpoint does not move.

"Why does the CPU stay idle here, and what would the dashboard have shown before the dump?"

Because blocked threads consume no CPU: a thread waiting to enter a monitor is parked in the kernel, and the one holder is itself asleep in a socket read. So the CPU graph drops, not rises, which is the counterintuitive signature of a lock convoy.

Before the dump, the dashboards would have shown request throughput collapsing while CPU fell toward zero, Tomcat's busy thread gauge climbing to its maximum of 200, the pricing client's latency histogram spiking, and, if I had it, the JFR jdk.JavaMonitorBlocked event count exploding with one monitor class.

The combination of maximum busy threads and minimum CPU is the tell; a busy service has both high. That is why "Tomcat threads busy" belongs on the main dashboard, because it distinguishes "working hard" from "waiting hard" without a dump.

"Would a ReadWriteLock have fixed this?"

Only partly. A ReentrantReadWriteLock would let the 190 readers proceed concurrently while no rebuild is in progress, but during the rebuild the writer holds the write lock across the network call, and every reader still waits for the whole duration.

So it moves the problem from "always serialised" to "frozen during rebuilds", which is still an outage whenever the pricing service is slow. It also introduces the write-starvation question, because a steady stream of readers can keep a writer waiting.

The real fix is to not hold any lock during I/O: build the new map on the side, then swap a single reference, which needs no lock at all for readers and a tiny critical section, or none, for the writer. Copy-on-write publication beats any lock granularity here.

"What prevention would you add so this never reaches production again?"

A code review rule with tooling behind it.

First, a static check: an ArchUnit or Error Prone rule that flags any synchronized block or method whose body calls a class in the HTTP client, JDBC, or file I/O packages, which catches the pattern at pull request time.

Second, a runtime check: JFR's jdk.JavaMonitorEnter event with the threshold lowered to 10 milliseconds in staging, alerting on any monitor held longer than that, since a healthy critical section is microseconds.

Third, a load test with a deliberately slowed dependency, using Toxiproxy latency toxics, as a required step before shipping any new remote call. Fourth, a mandatory timeout on every client, enforced by a shared client factory so nobody constructs a client without one. Each layer catches what the previous one misses.

Q225 · Scenario. "A different outage: the dump shows all 200 worker threads RUNNABLE, every one of them inside socketRead0. The team says 'the app is busy'. Are they right?"

Reveal answer

The real test Do you know that RUNNABLE lies about network I/O.

Strong answer They are wrong, and the state name is the trap. The JVM reports RUNNABLE for any thread executing code, including native code — code outside Java, in the operating system's libraries.

A thread inside socketRead0 has asked the kernel to read bytes from a network socket; the kernel has put it to sleep until data arrives, but from the JVM's point of view it is still "running" that native call.

So 200 threads RUNNABLE in socketRead0 means 200 threads asleep waiting on the network, with the CPU idle. My steps:

  1. Confirm with two more dumps: the same threads sit in the same read across all three — they are not busy, they are stuck.
  2. Read down each stack to find which client and which destination — the frames name the class, and usually the downstream service, that the read belongs to.
  3. Check that downstream's latency and error dashboards; it is degraded or hung.
  4. Ask the killer question: why are we waiting forever? Because no read timeout was configured — the default on several older clients, including HttpURLConnection, is zero, meaning infinite.

The fix is a connect timeout and a read timeout on that client, sized against the downstream's normal worst case, so a sick dependency costs seconds, not the whole thread pool. Prevention is making timeouts a mandatory code-review item for every remote call.

Land it RUNNABLE in a native socket read is a waiting thread wearing a busy costume — the state line describes the JVM's bookkeeping, not reality.

Likely follow-ups
"Which frame do you see for modern clients, since socketRead0 is the old blocking socket?"

Since JDK 13 the classic java.net.Socket is implemented on NIO underneath, so a blocking read shows as sun.nio.ch.SocketDispatcher.read0 or sun.nio.ch.NioSocketImpl.read rather than SocketInputStream.socketRead0; the meaning is identical.

The JDK HttpClient and Netty-based clients block differently: with those the request thread usually parks in a future, CompletableFuture.get or HttpClientImpl.send, and the actual socket wait is on a selector thread in EPoll.wait.

So the signature for a hung dependency changes to 200 request threads in WAITING on a future, with the selector thread RUNNABLE in epoll. Same disease, different frames.

On virtual threads, a blocked read unmounts, so the carriers look idle and the evidence is only in the JSON dump's virtual thread list, which is another reason to take that dump.

"You added a read timeout and the pool still drained. Why?"

Because a timeout bounds each call, not the total. If the downstream responds in exactly the timeout, say five seconds, and I get 100 requests a second, Little's law says 500 threads are needed to hold them, so a 200-thread pool still drains, just slower.

The timeout has to be set against the dependency's healthy p99 plus a small margin, not against a generous worst case.

The second reason is that the read timeout is a per-read idle limit, not a total request limit: a downstream that drips one byte every four seconds never trips a five-second read timeout, and the request runs for minutes.

For that I need a total deadline, which the JDK HttpClient gives with timeout(Duration) and Apache HttpClient 5 gives with responseTimeout. Third, the retries above the client may be multiplying the calls; a bulkhead caps the damage regardless.

"How would you tell the difference between a downstream that is hung and a network that is black-holing packets?"

By where the connection attempt fails. If connections are established quickly but reads hang, the TCP handshake succeeds, so packets are flowing and the downstream process is accepting but not answering; that is an application hang or overload on their side.

If even the connect stalls, the SYN packets get no reply, which is a black hole: a firewall, a dead host with no reset, or a broken route.

On the box, ss -tan dst HOST shows the state: many sockets in ESTABLISHED with a full receive queue of zero means we are waiting for them; many in SYN-SENT means the network. A tcpdump for a few seconds confirms whether any bytes arrive.

The distinction matters because the fix differs: their on-call for a hung service, the network team for a black hole.

"What timeout values would you actually set, and how do you justify them?"

From the dependency's own latency histogram, which I would pull for the last month. Connect timeout is short and fixed, one second, because a handshake to a healthy host on the same network takes milliseconds and anything longer means the host is unreachable.

Read timeout is the dependency's p99.9 plus about 50% margin, so if their p99.9 is 800 milliseconds I set 1.2 seconds.

Total request deadline is set from my own budget: if my endpoint promises 2 seconds and this call is one of three, it gets no more than a second.

I write the numbers and the reasoning into the client configuration as a comment, and I put an alert on the timeout count, because a rising timeout rate is the dependency's latency drifting up toward my limit, which is a conversation to have before it becomes an outage.

Q226. "jstack printed a section titled 'Found one Java-level deadlock'. Read it to me — what does it contain, and why is the fix almost always lock ordering?"

Reveal answer

Strong answer The JVM runs a deadlock detector when you take a dump, and when it finds a cycle it prints this section: for each thread involved, its name, the monitor it currently holds, and the monitor it is waiting for.

Read aloud it sounds like: "Thread-A holds 0x...62208 and waits for 0x...59b10; Thread-B holds 0x...59b10 and waits for 0x...62208" — a closed circle, which is the definition of deadlock.

Below that it prints both stacks so you can see the two code paths that acquired the locks in opposite orders.

That opposite order is the whole disease: a cycle can only form if some path takes A then B while another takes B then A. So the durable fix is a single global acquisition order — every path takes A before B, always — because with one order, no cycle is geometrically possible.

The alternative when ordering is impractical is tryLock with a timeout, which turns a permanent deadlock into a retryable failure. One caveat I would add: this detector only sees JVM-level locks — monitors and java.util.concurrent locks.

A cycle that passes through an external resource, like a database row lock, is invisible to it.

reading a jstack deadlock sectionruns offline
Found one Java-level deadlock:
=============================
"pool-1-thread-1":
  waiting to lock monitor 0x00007f8e4c006e08 (object 0x000000076ab5e158, a com.acme.Account),
  which is held by "pool-1-thread-2"
"pool-1-thread-2":
  waiting to lock monitor 0x00007f8e4c009318 (object 0x000000076ab5e190, a com.acme.Account),
  which is held by "pool-1-thread-1"

Java stack information for the threads listed above:
===================================================
"pool-1-thread-1":
        at com.acme.Bank.transfer(Bank.java:42)
        - waiting to lock <0x000000076ab5e158> (a com.acme.Account)
        - locked <0x000000076ab5e190> (a com.acme.Account)     <- already holds B
"pool-1-thread-2":
        at com.acme.Bank.transfer(Bank.java:42)
        - waiting to lock <0x000000076ab5e158> ... 
        - locked <0x000000076ab5e158> (a com.acme.Account)     <- already holds A

// HOW TO READ IT:
//  - "locked <id>"             = this thread HOLDS that monitor
//  - "waiting to lock <id>"    = it is blocked trying to acquire it
//  - the object ids (0x...76ab5e158) are what you match between threads
//  - BOTH threads are at Bank.java:42 -> the SAME method, acquiring two
//    locks in opposite orders. That is the whole diagnosis.

// THE FIX is lock ORDERING: always acquire in a globally consistent order,
// here by account id, so a cycle is impossible.
Account first  = a.id() < b.id() ? a : b;
Account second = a.id() < b.id() ? b : a;
synchronized (first) { synchronized (second) { ... } }

// Note jstack only finds deadlocks on MONITORS and java.util.concurrent locks.
// A deadlock on a database row, a semaphore, or a thread pool waiting on
// itself will NOT appear here — the section will simply be absent.

The last note matters during an incident. "No deadlock found" does not mean there is no deadlock; it means there is no monitor deadlock, and pool starvation or a database lock cycle produces exactly the same frozen service with a clean jstack.

Land it The report hands you the cycle; the fix is destroying the possibility of a cycle with one agreed order, not restarting the service faster.

Likely follow-ups
"How do you enforce a global lock order in a large codebase where locks are created dynamically?"

When the locks are per-entity, such as one lock per account, I cannot list them in advance, so I order by a stable key.

For a transfer between accounts A and B, both paths lock the account with the smaller ID first; if the IDs are equal it is the same account and one lock suffices.

When there is no natural key, I use System.identityHashCode of the lock objects and break ties with a global tie-breaker lock, which is the pattern from Java Concurrency in Practice.

For static locks I document a level for each, low to high, and add a debug-mode check: a thread-local stack of held lock levels that throws if a lock with a lower level is taken while a higher one is held.

That check runs in tests and staging and is compiled out in production, and it turns the ordering rule from a comment into a test failure.

"The deadlock section is empty but you suspect a deadlock anyway. When does the detector miss?"

It misses any cycle that includes a wait the JVM does not model as lock ownership. A thread blocked in a socket read while the peer is blocked waiting on a monitor this thread holds is a cycle across the network, and neither side sees it.

A thread waiting on a CountDownLatch or a Future that another thread would complete, while that thread waits on a monitor the first holds, is a cycle through a signal, not a lock, and the detector only tracks lock ownership.

A cycle through a database row lock is the same story. And a Semaphore has no owner at all, so semaphore-based cycles are invisible.

In each case I trace by hand: from the blocked thread, ask "who would unblock this", find that thread, and repeat until I come back to the start. Three dumps showing the same threads unchanged is the confirmation.

"What does tryLock with a timeout actually do to the system when it fails?"

It converts a permanent hang into a periodic failure, which is better but not free.

The thread that times out must release every lock it already holds, back off for a random interval so the two contenders do not retry in lockstep, and try again; without the random backoff both threads time out together and re-collide forever, which is a livelock.

Each failed attempt also wasted the timeout duration, so under contention latency rises by multiples of it. And the failure must go somewhere: an exception to the caller, a retry, or a metric.

I use it only where ordering truly cannot be established, such as locks owned by two different libraries, and even then I set a short timeout, tens of milliseconds, and I alert on the timeout count, because a nonzero count means the ordering bug still exists and is merely being survived.

"Can you detect deadlocks at runtime without taking a dump?"

Yes, from inside the process with ManagementFactory.getThreadMXBean().findDeadlockedThreads(), which runs the same detector the dump uses and returns the thread IDs in the cycle, or null. It covers monitors and ownable synchronizers such as ReentrantLock.

A watchdog thread calling it every thirty seconds and, on a hit, writing a full dump via ThreadMXBean.dumpAllThreads(true, true) to a file and then failing the health check, is a small amount of code that turns a silent hang into a captured incident and a restart.

The cost is a brief safepoint per check, which at thirty-second intervals is nothing. It has the same blind spots as the dump section, so it will not see the mixed-resource cycles, but it catches the pure Java case before a human is paged.

Q227. "You have a dump with 300 threads. Nobody can read 300 stacks during an incident. What is your statistical first pass, and what does each state's count tell you?"

Reveal answer

Strong answer I never read a big dump top to bottom; I count first, with grep:

state-histogram.sh
$ grep -c 'java.lang.Thread.State' td1.txt          # total threads
312
$ grep 'java.lang.Thread.State' td1.txt | sort | uniq -c | sort -rn
    198   java.lang.Thread.State: BLOCKED (on object monitor)
     71   java.lang.Thread.State: TIMED_WAITING (parking)
     28   java.lang.Thread.State: WAITING (parking)
     15   java.lang.Thread.State: RUNNABLE
$ grep -o 'waiting to lock <0x[0-9a-f]*>' td1.txt | sort | uniq -c | sort -rn | head -3
    193   waiting to lock <0x000000076ab62208>

The histogram is the diagnosis in miniature. A large BLOCKED count means lock contention, and the second grep tells me whether it is one monitor or many — one dominant address means one culprit to find. Large WAITING and TIMED_WAITING counts are usually healthy: idle pool workers park while waiting for tasks. They become suspicious only when the parked frames are in my code — say, a Future.get() with no timeout. A large RUNNABLE count with high CPU means real compute; a large RUNNABLE count with idle CPU sends me looking for native waits like socket reads. Only after the counts point somewhere do I read individual stacks.

Land it Count states first, read stacks second — the histogram tells you which of the three or four classic diseases you are looking at before you read a single frame.

Likely follow-ups
"After the histogram, which threads do you read first, and how do you find them fast?"

The owner of the dominant lock, then anything RUNNABLE in my own packages. For the owner I grep for locked <ADDR> with the address the histogram surfaced; that gives one thread, and its stack is the story.

For RUNNABLE threads I grep the state line with two lines of context and filter for my top-level package name, which cuts out the pool plumbing and JVM internals, and I read those top frames.

Then I group the TIMED_WAITING threads by top frame with the same sort and uniq trick; a big cluster parked in my own code, for example in Future.get or a queue poll, is a second suspect.

I rarely need to read more than five stacks by hand after the counting pass, and that is the whole point: the histogram tells me which five.

"How do you group threads by what they are doing, not just by state?"

I extract the top application frame per thread and count those. In practice that is a two-line awk: when a line starts with a quote, remember the thread name; when the first at line appears after it, print that frame and reset.

Piping the frames into sort and uniq gives a histogram of where the threads are, which is far more useful than the state histogram alone: "180 threads at PriceCache.get line 41" identifies the code in one glance.

Tools do this for me, FastThread and Yourkit's dump viewer, and IntelliJ can open a dump and group it, but the awk works on any box with no upload of production data, which matters for regulated environments.

I keep the script in the runbook so nobody has to remember it under pressure.

"What state counts would tell you the dump is healthy and the problem lies elsewhere?"

A healthy service under load shows a modest number of RUNNABLE threads roughly matching the CPU count, most pool threads in WAITING or TIMED_WAITING inside pool plumbing, near-zero BLOCKED, and the dominant-lock grep returns nothing above a handful.

If I see that during a slow incident, the threads are not the bottleneck and I move to resources: GC pause time share, container throttling, connection pool waits, and the downstream latency histograms.

A second healthy signature is many threads waiting in a BlockingQueue.take inside my own consumer code; that is idle consumers with nothing to consume, so the slowness is upstream of them, in the producer or the broker.

Reading a healthy dump correctly and saying "not here" quickly is as valuable as finding the culprit.

Q228 · Scenario. "A service runs fine for two days, then dies with 'java.lang.OutOfMemoryError: unable to create new native thread'. The last thread dump contains thousands of threads named pool-2847-thread-1. Diagnose it."

Reveal answer

The real test Can you decode a leak from nothing but thread names.

Strong answer First, the error: an OutOfMemoryError is the JVM saying it could not get a resource it needs, and this particular variant is not about the heap at all — the JVM asked the operating system for one more thread and was refused, because each thread costs a stack (roughly a megabyte) plus a kernel entry, and the process hit a limit such as ulimit -u. Now the diagnosis:

  1. Confirm growth over time: the thread-count metric, or ls /proc/PID/task | wc -l on a live process, climbs steadily and never falls. That shape says leak, not spike.
  2. Read the names. Java's default executor naming is pool-N-thread-M: N is the pool's creation number, M the thread's number inside that pool. Thousands of threads that are all thread-1 of different pools means thousands of pools, each with one thread.
  3. That fingerprint has one cause: somewhere, code calls Executors.newFixedThreadPool(...) — an ExecutorService, a pool of reusable worker threads — per request or per task, and never calls shutdown(). Pool threads are non-daemon and wait for work forever, so each request permanently donates a thread.
  4. Find the creation site by grepping the code for executor construction inside request-scoped paths.

The fix is one shared, injected executor with a lifecycle — created at startup, shut down at exit. And the reason this was findable at 3am is naming discipline: always pass a ThreadFactory that gives threads meaningful names like report-export-3, so the dump names the owner instead of pool-2847. Prevention: an alert on thread count.

Land it Thousands of pools with one thread each is an executor-per-request bug — pools are infrastructure you build once, not objects you new up per call.

Likely follow-ups
"Which limit was actually hit, and how do you check it on Linux?"

One of four. The process limit on the user, ulimit -u, visible in /proc/PID/limits as "Max processes", which counts threads, not just processes. The kernel-wide /proc/sys/kernel/threads-max.

The PID space, /proc/sys/kernel/pid_max, since every thread consumes a PID. And in containers, the cgroup pids controller, pids.max in the container's cgroup directory, which is usually the one that fires in Kubernetes.

Memory is also possible: each thread reserves stack virtual memory, one megabyte by default from -Xss, and a strict overcommit setting or the container memory limit can refuse the mapping.

I check the current thread count with ls /proc/PID/task | wc -l, compare it to each of those limits, and the one it is closest to is the wall that was hit.

"You fixed the executor-per-request bug and thread count still grows slowly. What else leaks threads?"

The usual second sources. Timers: a new Timer() or ScheduledExecutorService per object that is never cancelled, which shows up in the dump as many threads named Timer-N or pool-N-thread-1 parked in DelayedWorkQueue.take.

Client libraries: an HTTP client, a Kafka producer, or a Redis client created per request each spawn their own I/O threads, visible by their naming, such as kafka-producer-network-thread or lettuce-eventExecutorLoop.

And CompletableFuture.supplyAsync is safe because it uses the common pool, but new Thread(...).start() inside a request path for "fire and forget" is not.

The method is the same: group thread names in the dump, find the family that grows between two dumps ten minutes apart, and read one member's stack to see who created it, which the JDK 21 dump helps with by naming the executor.

"How would you set up a thread-count alert that fires before the outage rather than during it?"

With a rate alert, not a threshold alert.

Micrometer exposes jvm_threads_live_threads and jvm_threads_states_threads per state; I alert when the live count rises steadily over an hour, using something like an increase of 20% over the trailing hour with no corresponding change in traffic, because a leak is monotonic while a healthy pool oscillates.

I add a static ceiling as well, at about half the container's pids.max, which for a typical limit of 4096 means 2000, so there is time to act.

I also alert on the pool-N naming pattern itself in staging: a test that fails if any thread in the dump matches the default naming, which forces every executor to have a named ThreadFactory and therefore an owner.

"Why is 'OutOfMemoryError' the error text when memory was not the problem?"

Because the JVM reports every failure to obtain a resource from the operating system under the same exception class, and native thread creation is one of them.

When pthread_create fails, the JVM has no better category, so it throws OutOfMemoryError with the specific message "unable to create new native thread" or in newer JDKs "unable to create native thread: possibly out of memory or process/resource limits reached". The heap might be nearly empty.

The practical consequence is that -XX:+HeapDumpOnOutOfMemoryError does fire for it, producing a heap dump that will show nothing useful, and that dashboards keyed on the exception name will call it a memory incident.

I read the message, not the class, and I make the alert text include it.

Q229. "You open a dump from a Java 21 service and see hundreds of threads parked in Unsafe.park under ForkJoinPool frames. Is that a problem, and how do virtual threads change what a dump shows?"

Reveal answer

Strong answer Mostly it is healthy noise, and knowing that saves an hour of chasing ghosts.

A worker thread with WAITING (parking) and frames like jdk.internal.misc.Unsafe.park or LockSupport.park inside ForkJoinPool.awaitWork or ThreadPoolExecutor.getTask is simply an idle pool member waiting for its next task — that is what a resting thread pool looks like.

A parked frame only becomes evidence when the parking happens inside application code: a thread parked under CompletableFuture.get() with no timeout, in my own package, is genuinely waiting on something and I need to ask what.

For virtual threads — the lightweight threads Java 21 mounts onto a small pool of carrier threads — there is an extra trap: classic jstack shows the carriers, not the thousands of unmounted virtual threads, so the dump can look deceptively small.

The honest capture is jcmd PID Thread.dump_to_file -format=json /tmp/td.json, which includes every virtual thread.

Going deeper What the JSON dump actually contains, as of JDK 21 and later: a threadContainers array where each container is an executor or a StructuredTaskScope, with its parent, its owner thread, and the list of threads it contains, each with tid, name, and a stack.

The root container holds platform threads; virtual threads created through Executors.newVirtualThreadPerTaskExecutor() appear under a container named for that executor, and unstructured virtual threads made with Thread.ofVirtual().start() appear under the root.

Virtual threads that are unmounted and parked still have their full stack printed, taken from the heap stack chunk, so a "where are my ten thousand requests stuck" question is answered by grouping that JSON by top frame, which jq does in a line.

The dump takes a safepoint like the classic one but also walks every stack chunk, so with a million virtual threads it takes seconds and writes hundreds of megabytes; I run it on one pod, not the fleet.

Land it Park frames in pool plumbing are furniture; park frames in your own code are clues — and for virtual threads, use the dump command that can actually see them.

Likely follow-ups
"What does a pinned virtual thread look like in the classic jstack output?"

It looks like a carrier thread doing application work.

A pinned virtual thread cannot unmount, so its frames are on the carrier's native stack, and jstack prints the carrier, named ForkJoinPool-1-worker-N, with a stack that runs from the pool plumbing at the bottom, through VirtualThread.run and Continuation.enter, and up into my code and the blocking call.

On JDK 21 that blocking call sits inside a synchronized frame somewhere above it. So the tell is a carrier thread with a state of BLOCKED or WAITING, or RUNNABLE in a native read, instead of the idle awaitWork park.

If most carriers look like that, the scheduler is starved. Since JDK 24 the synchronized case is gone, so on a current JDK the same picture means a native frame or a class initializer.

"How do you find which of ten thousand virtual threads is stuck?"

By grouping, not reading. I take the JSON dump and run jq to extract, for each thread, the first frame of its stack, then count by frame.

Ten thousand threads with the same top frame in a socket read against one host is one downstream problem, and I read one stack to get the class. A spread of frames is healthy work in flight.

If I need the ones that are stuck rather than merely waiting, I take two JSON dumps a minute apart and join on the thread id: virtual threads that exist in both with an identical stack are candidates.

Virtual thread ids are unique for the process lifetime, so the join is reliable. I also look at the container name each thread belongs to, which tells me which executor or scope spawned it, and that usually maps to a feature.

"Is a large number of parked platform pool threads ever a real problem?"

Yes, in two cases.

First, when the pool is much bigger than it needs to be: 500 idle workers each reserve a stack, and with -Xss1m that is half a gigabyte of virtual memory and, after each thread has been used once, real resident pages for the touched part; on a small container that can matter.

Second, when the parked count is the maximum and it is parked in the wrong place: workers parked in Future.get or in a Semaphore.acquire inside my code are not idle, they are in-flight requests that have stalled, and the pool is exhausted even though nothing is RUNNABLE. The distinction is the frame the park happens in.

Pool plumbing is fine; application frames are a queue of stuck work and I want to know what they are waiting for.

Q230 · Scenario. "The stuck service runs in Kubernetes on a slim JRE-only image. You exec in and jstack is not there. How do you still get a thread dump?"

Reveal answer

The real test Whether your debugging survives contact with modern minimal containers.

Strong answer In order of preference:

  1. kubectl exec into the pod and send kill -3 1 — in most containers the JVM is process 1, and SIGQUIT makes it print the dump to its own standard output without dying. I then read it with kubectl logs. This needs only a shell and kill, which even slim images usually have.
  2. If Spring Boot actuator is enabled, hit /actuator/threaddump through a port-forward — no shell needed at all.
  3. If the image has no shell either (distroless), use an ephemeral debug container: kubectl debug -it POD --image=eclipse-temurin:21 --target=APP_CONTAINER gives me a JDK sharing the target's process namespace, and from there jcmd can attach — provided the debug container runs as the same user id as the JVM, because the attach mechanism checks ownership.
  4. If Java Flight Recorder was started at launch, dump the recording the same way and read thread states from it.

The prevention lesson matters as much as the technique: decide before the incident how dumps get captured — bake jcmd into the image or run always-on Flight Recorder — and rehearse it, because discovering your image is toolless at 2am doubles the outage.

Land it kill -3 plus kubectl logs works almost anywhere — but the real answer is choosing your capture path before you need it.

Likely follow-ups
"kill -3 produced nothing in the logs. What could be wrong?"

Three possibilities.

The JVM is not PID 1: many images start the JVM via a shell script or an init wrapper like tini, so PID 1 is the wrapper and the signal went to it; I check with ps -ef or cat /proc/1/cmdline and target the actual java PID. The JVM was started with -Xrs, which reduces signal usage and disables the SIGQUIT handler entirely; there is no fix at runtime except attach.

Or the output is going somewhere else: the dump goes to the JVM's stdout, and if the entrypoint redirected stdout to a file inside the container, kubectl logs will never show it, so I look at that file.

A fourth, rarer case is that the process is truly wedged inside a safepoint operation, in which case the signal handler cannot run either, and the only route is a core dump with gcore read by the Serviceability Agent.

"How does the ephemeral debug container get permission to attach to the target JVM?"

Two conditions. It must share the process namespace, which --target=CONTAINER arranges on the ephemeral container so that the JVM's PID is visible and /proc/PID/root maps to the target's filesystem.

And it must run as the same UID as the JVM, because the attach handshake creates a file in the target's /tmp and the JVM checks that the socket file's owner matches its own effective user.

The Temurin image runs as root by default, so if the application runs as UID 1000 I add --profile=general or a custom profile setting runAsUser: 1000 on the debug container. Then jcmd addresses the target by its PID as seen inside the shared namespace.

If the cluster's pod security policy forbids process namespace sharing, this path is closed and I fall back to the signal or the actuator endpoint.

"What would you bake into the image so this is never a problem again?"

Not the full JDK, because image size and attack surface matter, but a jlinked runtime that includes the jdk.jcmd module, which brings jcmd and jstack for a few megabytes. Then always-on Flight Recorder with a rolling buffer written to an emptyDir or persistent volume: -XX:StartFlightRecording=disk=true,maxage=2h,maxsize=256m,dumponexit=true.

Then -XX:+HeapDumpOnOutOfMemoryError with a path on that same volume. And a runbook entry with the exact three commands for a dump, tested in staging every quarter. Some teams also expose actuator's threaddump on a management port bound to localhost only, reachable through a port-forward.

The principle is that diagnostics are part of the build, decided by the platform team once, not something discovered during the incident.

"The pod is in CrashLoopBackOff, so you can never exec in time. How do you capture anything?"

I stop the crash loop from destroying evidence. First, dumponexit=true on the Flight Recorder flag and HeapDumpOnOutOfMemoryError both write on the way down, if the volume persists across restarts, which an emptyDir does not on pod recreation but a PVC does.

Second, I change the pod's liveness probe or the container command temporarily so the process stays up long enough to attach; for a crashing JVM, -XX:+ExitOnOutOfMemoryError off and a sleep wrapper command keep the container alive.

Third, a preStop hook that runs jcmd 1 Thread.print and JFR.dump to a volume before termination, which Kubernetes invokes on graceful kills but not on OOM kills, so it is partial.

And the container log itself often has the last exception; kubectl logs --previous reads the crashed instance's output.

Drill · CPU on fire, and profiling without breaking production

Whether you can turn "CPU is at 100%" into a named line of code, and gather profile data from a live service without stopping it.

Q231 · Scenario. "A pod is pinned at 100% CPU and requests are timing out. Walk me through the exact commands that take you from 'high CPU' to the guilty line of Java."

Reveal answer

The real test The canonical hot-thread workflow — seniors recite it like a phone number.

Strong answer The trick is joining what the operating system sees with what the JVM sees, and the join key is the native thread id.

hot-thread-workflow.sh
$ top -H -p 4821              # -H lists individual threads of process 4821
    PID  %CPU  COMMAND
  20154  99.7  java            # this OS thread is burning a whole core
$ printf '%x\n' 20154         # convert the decimal thread id to hex
4eba
$ jcmd 4821 Thread.print > td.txt
$ grep -A 6 'nid=0x4eba' td.txt
"order-batch-3" #87 daemon prio=5 os_prio=0 nid=0x4eba runnable
   java.lang.Thread.State: RUNNABLE
        at com.shop.batch.CsvParser.skipRow(CsvParser.java:112)
        at com.shop.batch.ImportJob.run(ImportJob.java:54)
  1. top -H -p PID switches top from processes to threads; the PID column now shows each native thread's id, and the sort by %CPU hands me the hot one.
  2. Thread dumps record that same id in hexadecimal as nid=0x..., so I convert 20154 with printf '%x'.
  3. I take a dump and grep for nid=0x4eba — the top frame of that thread's stack is where the CPU is going: here, a CSV parser stuck at line 112.
  4. I repeat the dump twice more. If the same thread shows the same frame each time, this is a loop, not a busy moment.

The whole loop takes under two minutes and needs nothing installed beyond the JDK. If async-profiler happens to be available, a 30-second flame graph gives the same answer with proportions, but I never need to wait for tooling to exist.

the exact commands for a pinned CPUruns offline
# 1. Which THREAD is burning the CPU? Get the OS thread id.
top -H -p <pid>            # -H = per thread. Note the TID of the hot one, e.g. 12345

# 2. Convert it to hex, because jstack prints nid in hex.
printf '%x\n' 12345       # -> 3039

# 3. Take the dump and find that thread.
jstack <pid> > dump.txt
grep -A 30 'nid=0x3039' dump.txt

# The stack you land on IS the code burning the core. Three takes, ten seconds
# apart: if the same frames appear every time, it is a genuine hot loop rather
# than a busy method sampled at an unlucky moment.

# FASTER, and what I would actually reach for first if it is installed:
./profiler.sh -d 30 -f flame.html <pid>      # async-profiler, ~1% overhead

# In a container without a JDK, the JVM's own tools still work over the socket:
jcmd <pid> Thread.print
jcmd <pid> JFR.start duration=60s filename=/tmp/rec.jfr settings=profile

# AND ONE PIECE OF INTERPRETATION (Q232): if the hot thread is named
# "GC Thread#3", the application is not slow -- it is ALLOCATING too much or
# the heap is too small, and the fix is in allocation or sizing, not in code
# that appears in any application stack.

The hex conversion is the step people forget under pressure. top reports the thread id in decimal and jstack prints nid in hexadecimal, so grepping for the decimal value finds nothing and sends people back to guessing.

Land it top -H, hex the TID, grep the nid — the OS names the thread, the dump names the line.

Likely follow-ups
"The hot thread's nid is not in the dump. What happened?"

Then the thread is not a Java thread the dump lists, or the ids do not match. GC and compiler threads are listed at the bottom of a dump without stacks, so I grep the whole file, not just entries with Java frames.

If it is still missing, the thread may belong to a native library that created it outside the JVM, such as a JNI crypto or compression library, in which case perf top -t TID or reading /proc/PID/task/TID/comm gives its name.

The third cause is a namespace mismatch: inside a container, top run from the host shows host thread ids while the JVM's nid is the container-side id; running top -H inside the container fixes the join.

And I check for a typo in the hex conversion, because printf '%x' on the wrong column, the process id instead of the thread id, is a common slip at 3am.

"How would you do the same thing without top, using only /proc?"

Every thread has a directory /proc/PID/task/TID with a stat file whose fields 14 and 15 are user and system CPU ticks. I list them twice a few seconds apart, subtract, and sort.

A quick loop that reads the ticks, sleeps five seconds, reads them again, and prints the deltas per TID gives the same ranking as top -H and works in a container that has no procps installed.

On JDK 21 and later there is an even simpler route: jcmd PID Thread.print -e prints cpu= per thread in the header line, so two dumps a few seconds apart and a diff of that field name the hot thread without leaving the JDK tools at all.

That is what I do first now; the /proc loop is the fallback when I cannot attach.

"The guilty frame is in a library, not your code. What do you do with that?"

I read down the stack until I reach my own frame, because that is the call that asked for the expensive work, and I ask what input made it expensive.

A CPU spin inside a regex engine or a JSON parser is almost always a pathological input: a catastrophic backtracking pattern fed a long string, or a deeply nested document.

I capture the input by logging the arguments at my frame when a request exceeds a duration threshold, or from a JFR recording with method profiling that shows the parameters are not available but the caller is.

Then I reproduce it in a unit test with that input and time it. The fix is on my side: a length limit on the input, a safer pattern, a size cap on the parser, or a different library. Filing a bug upstream is a courtesy, not the fix.

"What would you add so the next time takes thirty seconds instead of two minutes?"

Two things. A runbook script on every box, or in the debug image, that does the whole join automatically: takes top -H for three seconds, converts the top five thread ids to hex, takes a dump, and prints those five stacks.

It is a twenty-line shell script and it removes the arithmetic from the incident.

And continuous profiling, so that the question is answered before I log in: an always-on async-profiler agent or JFR with method sampling shipped to a profiling backend such as Pyroscope or a commercial APM, giving me a flame graph of the last ten minutes for any pod without touching it.

The manual workflow stays in the runbook for the day the profiling pipeline is the thing that is broken.

Q232 · Scenario. "You run that workflow and the hot thread is named 'GC Thread#3'. What does that change about your investigation?"

Reveal answer

Strong answer Everything — it tells me the CPU is not being burned by my code path at all. Threads named GC Thread#N, G1 Conc#N, or VM Thread are the JVM's own internal workers, listed near the bottom of a dump without Java stacks.

GC is garbage collection — the JVM's automatic reclamation of memory that is no longer referenced — and a garbage-collection thread pegging cores means the collector is running constantly, which is a memory-behavior problem: the application is allocating faster than the heap can absorb, or the heap is nearly full and the collector is running back to back trying to free scraps.

So I stop reading application stacks and pivot to the memory evidence — GC logs, allocation rate, heap occupancy after collections — which is its own analysis discipline with its own tools.

The transferable lesson is that the hot thread's name routes the whole investigation: an application thread points at my code, a GC thread points at memory, and a C2 CompilerThread points at the just-in-time compiler recompiling in a storm.

Treating a GC-driven CPU fire as a code-optimization problem wastes the incident.

Land it The hot thread's name is a routing decision — "GC Thread" means close the profiler and open the GC logs.

Likely follow-ups
"Give me the first three things you read in the GC log once you have pivoted."

With -Xlog:gc* on, first the collection frequency and pause durations: lines every second with pauses of hundreds of milliseconds mean the collector is running constantly.

Second, the heap occupancy after each collection, the number after the arrow in a line like 3900M->3850M(4096M); if the after-collection value climbs steadily toward the maximum, live data is growing, which is a leak or a working set larger than the heap.

If it stays high and flat, the heap is simply too small for the live set.

Third, the collection type: a stream of young collections with little promotion is an allocation-rate problem, while back-to-back full collections or G1 mixed collections with "to-space exhausted" messages mean the old generation is full.

Those three readings separate leak, undersized heap, and allocation storm, which have three different fixes.

"How would you tell 'allocating too fast' from 'leaking' without a heap dump?"

From the after-collection occupancy trend. If heap after each collection returns to roughly the same baseline, nothing is accumulating, and the CPU is going into collecting garbage the application produces; the fix is to allocate less, found with an allocation profile.

If the after-collection floor rises across hours, something is retained, and the JVM will eventually spend all its time in full collections; that is a leak, and a heap dump names the retained type.

A quick numeric check: the allocation rate is young generation size divided by the interval between young collections, so a 1-gigabyte young generation collecting every second is 1 gigabyte per second, which is high for a typical service and points at a code path. JFR's allocation sampling then attributes the bytes to a stack.

"What if the hot thread is 'C2 CompilerThread' instead?"

Then the just-in-time compiler is busy, and the question is whether that is startup or pathology. In the first minute or two after a deploy, heavy C2 activity is normal warmup and will subside; I check the deploy time.

If it persists, something is causing deoptimization storms: code that is compiled, then invalidated because an assumption broke, then recompiled, over and over.

Typical triggers are megamorphic call sites that flip between types, very large methods that hit the compilation size limit, or a library generating classes at runtime, for example a serializer creating a class per request. JFR's jdk.Deoptimization and jdk.Compilation events name the method being recompiled.

The fix is on the application side, and a temporary mitigation is capping compiler threads with -XX:CICompilerCount so they cannot starve request threads.

"What single metric would you have wanted on the dashboard to skip this whole detour?"

GC time as a fraction of wall time, per pod.

Micrometer exposes jvm_gc_pause_seconds_sum, and a rate of that over a minute divided by 60 gives the share; below 2% is healthy, 10% is a warning, and 50% is the collector on fire, which is what a pegged GC thread means.

With that line on the main dashboard next to CPU, the routing decision that took the thread-name detour happens at a glance: CPU high and GC share high is a memory problem, CPU high and GC share low is code.

I would also add heap-after-GC as a gauge, which is the leak detector, and alert on it trending upward over a day. Those two metrics answer the memory-versus-code question before anyone opens a terminal.

Q233 · Scenario. "One thread has burned 100% of a core for an hour inside a while-loop whose exit flag was already set by another thread. It works on your laptop. What happened in production?"

Reveal answer

The real test Connecting a production CPU fire to the Java memory model — the two worlds most candidates keep separate.

Strong answer The workflow gets me there fast: top -H shows one thread at 100%, three dumps show it RUNNABLE in the same frame each time — a loop like while (!done) { }.

Then comes the puzzle: the other thread's log proves it set done = true an hour ago.

The answer is that done is a plain boolean, and without volatile — the keyword that forces every read of a variable to see the latest write — the JVM makes no promise that the spinning thread ever re-reads it.

Worse, the just-in-time compiler, the machinery that compiles hot Java code into optimized native code, is entitled to observe that nothing inside the loop changes done, hoist the read out of the loop, and compile it into an infinite loop reading a register.

On the laptop the code ran briefly, mostly interpreted, and the optimization never kicked in — which is exactly why the bug only exists in production, where the loop got hot enough to be aggressively compiled.

  1. Fix: declare the flag volatile, or use AtomicBoolean.
  2. Better fix: do not spin at all — a CountDownLatch or a blocking queue parks the thread instead of burning a core.
  3. Prevention: treat every field shared across threads without synchronization as a review-blocking finding.

Land it This is a memory-model bug wearing a CPU-fire costume — the loop is not slow, it is reading a stale value the compiler froze in place.

Likely follow-ups
"Can you prove the hoisting actually happened, rather than just theorising?"

Yes, by reading the compiled code.

Running with -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly and the hsdis disassembler plugin prints the machine code C2 generated for the method, and in the hoisted case the loop body is a jump back to itself with no memory load of the flag at all; the load happened once before the loop.

The JITWatch tool does the same with a friendlier view.

A cheaper demonstration is a small program with a plain boolean flag, a spinning thread, and a main thread that sets the flag after a second; run normally it never exits, and run with -Xint, which disables the compiler, it exits immediately.

That contrast, same code, different compiler mode, is the most convincing thirty-second demo I know for the memory model.

"Why did it stop for an hour and then, in some reports, eventually exit?"

Because visibility is permitted, just not required.

Anything that forces the compiled code to re-read the field or to be thrown away can end the spin: a deoptimization of that method for an unrelated reason, a safepoint that happens to recompile it, or a call inside the loop, such as a log line or a Thread.sleep, that acts as a compiler barrier so the load stays in the loop.

That is why adding a print statement "fixes" the bug and why it seems random. The memory model's honest statement is that without a happens-before edge the reader may see the stale value forever, and any exit is luck.

A design that relies on eventual visibility is therefore incorrect even when it works, and the fix is the volatile or, better, not spinning at all.

"What is the cost of making the flag volatile, given the loop reads it millions of times a second?"

On x86 a volatile read is a plain load; the ordering rules are satisfied by the hardware's strong model, so the cost is only that the compiler must issue the load on every iteration instead of caching in a register, which is a cache hit of about a nanosecond.

On ARM64 a volatile read compiles to a load-acquire instruction, also cheap. The write side is where volatile costs: a volatile store emits a fence or locked instruction, tens of cycles, but the flag is written once.

So the fix is essentially free, and the far larger cost is the spin itself, a whole core burned.

If I keep a spin for a low-latency reason, I add Thread.onSpinWait(), which becomes the pause instruction on x86 and reduces the power and pipeline penalty of a tight loop.

"What would the fix look like if the loop were a real work loop rather than a pure spin?"

A consumer loop like while (running) { task = queue.take(); process(task); } has the same visibility bug on running but does not burn CPU, because take() parks.

The fix is still volatile boolean running, and the shutdown then also needs to wake the thread, since a parked thread never re-checks the flag; the standard shape is to set the flag and then interrupt() the thread, with take() throwing InterruptedException and the loop exiting.

Better still is to not have a flag at all and use the executor's lifecycle: shutdownNow() interrupts workers, and the loop checks Thread.currentThread().isInterrupted(). I state the rule as: a stop flag needs both visibility and a wake-up, and interruption gives both in one mechanism.

Q234. "What do busy-wait patterns look like in a dump, and why are they a production smell even when they 'work'?"

Reveal answer

Strong answer A busy-wait is a thread checking a condition in a tight loop instead of sleeping until notified — while (!ready) { }, or queue.poll() called in a loop with no timeout, or polling a status field every iteration.

In a dump the signature is a RUNNABLE thread whose top frames sit in the same small loop across multiple dumps, paired with one core pegged per spinning thread in top -H.

It is a smell even when correct: each spinner burns a full core doing nothing, which steals CPU from real work, wrecks the bill in a container with a CPU quota, and can starve the very thread it is waiting on.

The right tools park the thread for free — BlockingQueue.take(), wait/notify, a CountDownLatch — and for the rare justified micro-spin in low-latency code, Thread.onSpinWait() at least tells the processor what you are doing.

Land it Blocking is cheap and spinning is theft — a waiting thread should cost nothing until its condition arrives.

Likely follow-ups
"A library you depend on spins internally. How do you find that and what are your options?"

It shows as one core pegged per instance of the library's thread, in top -H, with a dump showing that thread RUNNABLE in the same library frame across dumps and no sign of I/O. Lock-free queues and some low-latency clients spin deliberately, usually with a configurable wait strategy; the LMAX Disruptor's BusySpinWaitStrategy and Aeron's idle strategies are examples, and Netty's event loop polls with a short timeout.

The first option is configuration: switch to a blocking or backoff strategy, which the good libraries expose. The second is isolation: pin that thread's cost into the container's CPU request so it does not starve request threads, and size the pod accordingly. The third is replacement.

What I never do is leave a spinning thread in a container with a CPU limit, because it eats the CFS quota and throttles the whole pod.

"Isn't a short spin before parking a legitimate optimisation? When?"

Yes, and the JDK itself does it.

Parking and unparking costs a few microseconds of kernel transitions, so if the condition is expected to become true within that time, spinning briefly first avoids the sleep and wake entirely; SynchronousQueue and Exchanger spin a bounded number of iterations before parking, and the JVM's monitor implementation does adaptive spinning before inflating a lock.

The conditions that make it legitimate: the wait is expected to be shorter than a park-unpark round trip, the spin is bounded to a few hundred iterations, it uses Thread.onSpinWait(), and there are at least as many cores as spinning threads, because spinning on a single core while the thread that would satisfy the condition needs that same core is self-defeating. Anything that spins unboundedly is not this pattern.

"How do you catch busy-wait loops in review or CI before they reach production?"

In review, I look for three shapes: a while on a boolean with an empty or trivial body, a loop around a non-blocking poll() or tryLock() with no sleep or backoff, and a loop calling Thread.sleep(1) or smaller, which is a busy-wait with a thin disguise that still wakes a thousand times a second.

Static tools do not catch these reliably, so the review checklist has to.

In CI, a load test that runs the service at idle for a minute and asserts CPU below a threshold catches the worst cases, because a spinner burns a core at zero load, which is a very distinctive signature.

And a JFR recording in staging with jdk.ThreadCPULoad events shows any thread with a steady 100% CPU load, which is a one-line alert rule.

Q235 · Scenario. "Two different incidents: in one, exactly one core is pegged and the rest are idle; in the other, all sixteen cores are pegged. How does each shape your diagnosis before you run a single command?"

Reveal answer

Strong answer The shape of the CPU graph is a pre-diagnosis.

Exactly one core pegged means exactly one runaway thread, because a single thread can occupy at most one core: an infinite loop, a busy-wait spin, or a single-threaded bottleneck like one consumer chewing a hot partition.

My path is the hot-thread workflow — top -H, hex the id, grep the nid — and I expect to land on one specific frame.

All cores pegged means something systemic that scales across threads: garbage collection running parallel workers, a genuine traffic surge, an expensive operation happening on every request — catastrophic regular-expression backtracking is a classic, where one pathological input makes the matcher explore exponentially many paths — or a too-small pool where every worker does heavy compute.

There my first split is "JVM threads or application threads" from the thread names in top -H, then a flame graph to see whether the width is spread across one method appearing in every request stack.

  1. One core: find the one thread; the fix is surgical.
  2. All cores: find the per-request cost or the collector; the fix is systemic — code, heap, or capacity.

Land it One hot core is a thread bug; all hot cores is a workload or memory problem — the graph's shape picks the playbook.

Likely follow-ups
"What if exactly one core is pegged but it is a different thread each time you look?"

Then it is not one runaway thread but a serialised bottleneck: work that can only run one at a time, being handed from thread to thread.

The classic causes are a single lock that every request takes, so exactly one thread at a time is inside it and busy, with everyone else blocked; a single-threaded executor or a Kafka consumer with one partition; or a synchronized singleton such as an old SimpleDateFormat shared under a lock.

The dump distinguishes them: many BLOCKED threads on one monitor, or a queue of tasks behind one worker. The fix is to remove the serialisation, either by making the critical section smaller or lock-free, or by adding parallelism where the design permits, such as more partitions.

The signature of one core moving between threads is one of the more useful graphs to recognise on sight.

"All sixteen cores are pegged and it is application threads. How do you find the per-request cost?"

A flame graph from async-profiler for thirty seconds, in CPU mode.

With all cores busy on real work, the graph's top edge will show wide plateaus, and I look for one method that appears at the top across many different request stacks; that is the per-request cost.

If the plateau is in JSON serialisation, regex matching, string formatting, or a collection sort, I have my suspect, and I confirm by reading the width: 40% of samples in one method means removing it would nearly halve CPU. Then I ask what changed: was this always this expensive and traffic grew, or did a deploy add it?

A deploy diff and a comparison against last week's profile answer that. If instead no method dominates and the graph is flat and wide, the service is genuinely at capacity and the fix is more pods.

"The pod has a 2-core limit but the node has 64 cores. Which count matters for your reasoning?"

The limit. The JVM detects the cgroup quota and reports two available processors, so the common pool, G1's parallel workers, and any pool sized from availableProcessors() are built for two cores.

"One core pegged" then means half the pod's capacity, and "all cores pegged" means both of the two, which happens at a fraction of the traffic a bare-metal reading would suggest.

The host graph is misleading in the other direction: two threads can show as 3% of a 64-core node while the pod is completely throttled.

So I always read CPU as a fraction of the pod's limit, from container_cpu_usage_seconds_total divided by the limit, alongside the throttled-periods counter. And I confirm what the JVM believes with jcmd PID VM.info, which prints the container-detected CPU count.

Q236 · Scenario. "A Kubernetes service is 'slow', the team sees its CPU graph touching the 2-core limit and starts optimizing code. What would you check before agreeing the service is CPU-bound?"

Reveal answer

The real test Do you know that container CPU limits create stalls, not just slowness.

Strong answer I would check throttling first, because a CPU limit in Kubernetes is enforced by the Linux CFS — the Completely Fair Scheduler — as a quota: the container gets, say, 200 milliseconds of CPU time per 100-millisecond period for a 2-core limit, and once the quota is spent, every thread in the container is frozen until the next period. That freeze is the killer detail: a JVM with 16 runnable threads can burn the entire 200ms quota in about 12ms of wall time, then sit completely stopped for the remaining 88ms — and that stall lands directly in request latency while the averaged CPU graph just shows "around the limit".

  1. Read the throttling counters: nr_throttled and throttled_time in the container's cpu.stat, or the container_cpu_cfs_throttled_periods_total metric. A high throttled-period ratio confirms it.
  2. Check what the JVM believes: modern JVMs are container-aware, so availableProcessors() follows the quota; thread pools sized for a big host but squeezed to two cores make the burst-then-freeze pattern worse. -XX:ActiveProcessorCount overrides it explicitly.
  3. Remember garbage collection bursts are multi-threaded too — a young-generation collection can eat a whole period's quota by itself.

The fixes are raising or removing the CPU limit (keeping requests for scheduling), and matching thread counts — pools plus GC workers — to the quota. Optimizing code while heavily throttled is polishing an engine that is being switched off ten times a second.

Land it Under CFS quota, "slow" often means "repeatedly frozen" — check throttled periods before believing you are compute-bound.

Likely follow-ups
"What throttled ratio counts as a problem, and how would you compute it from the metrics?"

The ratio is nr_throttled divided by nr_periods from the cgroup's cpu.stat, or in Prometheus rate(container_cpu_cfs_throttled_periods_total[5m]) / rate(container_cpu_cfs_periods_total[5m]). Anything above about 10% is noticeable in tail latency; 25% and up is a serious latency problem, because a quarter of all 100 millisecond periods contain a freeze.

The throttled time, throttled_time or throttled_usec, tells me how long the freezes are; total throttled seconds per second of wall time close to one means the pod is stopped about as much as it runs.

What I want to know is the freeze length per period, which is period length minus quota divided by parallelism, and for a bursty JVM with 16 threads on a 2-core quota that is most of each 100 milliseconds.

"Why do requests without limits fix the stall, and what does that cost?"

A CPU request is a scheduling weight: it guarantees the pod at least that share when the node is contended, and lets it use idle cycles when the node is not.

A limit is a hard quota enforced every period regardless of whether the node has spare capacity, so a pod can be frozen while the node sits idle.

Removing the limit and keeping the request lets bursts complete and removes the periodic freeze, while the request still protects neighbours under contention.

The cost is predictability: a pod can consume more than its share on an idle node, which makes capacity planning fuzzier and can hide a runaway CPU bug until the node fills up.

Many platform teams settle on requests only for latency-sensitive services, with a limit set high, three or four times the request, as a safety net against runaway loops rather than as a budget.

"What JVM flags would you set for a pod with a 2-core limit?"

First, I would let the JVM detect the quota, which it does by default, and check the result with jcmd PID VM.info or a startup log of availableProcessors().

If the detected count is wrong, for example because the pod uses only requests and the JVM sees the whole node, I set -XX:ActiveProcessorCount=2 explicitly.

Then I align the thread counts that follow from it: -XX:ParallelGCThreads and -XX:ConcGCThreads are derived from the count and should stay small, the common pool parallelism follows automatically, and application pools should be sized by measurement rather than by core count.

With a two-core budget I would also consider -XX:+UseSerialGC or leaving G1 with its small thread count, since a parallel collector with 16 workers on a 2-core quota is a throttling machine.

"How do you prove throttling caused the latency, not just correlated with it?"

With an experiment, because correlation on a dashboard is not proof.

I take one pod out of the deployment and raise its limit, or remove it, leaving everything else identical, and compare its p99 against the rest of the fleet over an hour of the same traffic.

If its tail latency drops and its throttled ratio goes to zero while the others stay high, the cause is established. The other direction works too: lower the limit on a canary and watch p99 rise in step with the throttled ratio.

I also look at the shape: throttling produces latency spikes quantised to the period, so a histogram of request duration shows a bump at roughly 100 milliseconds and multiples, which a slow database does not. That quantisation is a fingerprint I show in the postmortem.

Q237. "Why can't you just attach your IDE debugger to the production JVM the way you do locally?"

Reveal answer

Strong answer Because a breakpoint does not pause a request — it pauses the world.

Remote debugging works through an agent inside the JVM, and when a breakpoint fires in the default suspend-all mode, the JVM brings every thread to a safepoint — a controlled stop where all threads are frozen so the JVM can be safely inspected.

Every in-flight request on the box halts mid-flight, health checks stop answering, the load balancer marks the node dead, and timeouts fire all over your callers — while a human stares at variables for two minutes.

Even without hitting a breakpoint, running the debug agent changes the performance profile and opens a control channel into the process, which is an operational and security liability. So the debugger is a staging tool, where freezing the process hurts nobody.

In production the equivalents are non-freezing by design: thread dumps, Java Flight Recorder, and sampling profilers, all of which observe the JVM in motion instead of stopping it.

Land it A production debugger turns one engineer's curiosity into everyone's outage — observe the JVM running, never parked.

Likely follow-ups
"What about a thread-suspend breakpoint or a non-suspending logpoint? Are those safe?"

Safer, but I still would not do it on a production node.

A thread-only suspend freezes just the thread that hit the breakpoint, so other requests proceed, but that one request holds whatever it holds, a database connection, a monitor, a pooled HTTP connection, for as long as the human looks, and everyone waiting on those resources stalls with it.

A non-suspending logpoint avoids the freeze entirely and is the closest thing to acceptable, but the debug agent must be loaded, which changes JIT behaviour, since methods with breakpoints run with reduced optimisation, and the agent's socket is an unauthenticated control channel into the process.

The right tool for the logpoint use case is a purpose-built production debugger such as Rookout or Lightrun, or simply JFR custom events and structured logging shipped in the next deploy.

"How much slower is a JVM running with the debug agent attached, even with no breakpoints?"

On modern HotSpot, with -agentlib:jdwp loaded and no breakpoints, the steady-state overhead is small, usually under a few percent, because the JIT still compiles fully and the agent mostly sits idle.

The cost appears the moment capabilities are used: setting any breakpoint can force deoptimisation of the affected methods, and enabling features such as field watchpoints or method entry events falls back to much slower code paths, sometimes tens of times slower.

Startup is also slower because the JVM must retain debugging information. So the honest statement is that the agent is cheap until someone uses it, which is exactly when it hurts.

The operational risk is the bigger issue: an open JDWP port with no authentication has been used for remote code execution, so it must never be exposed on a production network.

"A bug only reproduces in production. What is your non-freezing way to inspect variables?"

Three tools in order of cost. First, JFR custom events: I define a small event class with the fields I need, commit it at the suspect point, and read them out of the recording; the overhead is nanoseconds and the recording is already running.

Second, targeted logging behind a dynamic flag: a log line for one tenant or one request ID, switched on with a config change rather than a deploy, so I capture exactly the failing case without flooding.

Third, a heap dump taken with jcmd PID GC.heap_dump, which does freeze the process for a few seconds, so I take it on one pod that I have drained from the load balancer first; the dump then lets me inspect any object's fields offline in MAT. None of these stop request processing on a serving node, which is the only constraint that matters.

Q238. "What does Java Flight Recorder actually record, what does it cost, and what is your jcmd workflow during an incident?"

Reveal answer

Strong answer Java Flight Recorder — JFR — is an event recorder built into the JVM itself: it captures method-execution samples, lock-contention events with the exact monitor class and wait duration, allocation by call site, garbage-collection and safepoint pauses, file and socket I/O, and thrown exceptions, all into a compact binary file. Because the hooks live inside the JVM rather than in added instrumentation, the default configuration costs around 1% overhead, and the deeper profile configuration roughly 2% — cheap enough to run in production, which is its whole point. My incident workflow:

jfr-workflow.sh
$ jcmd 4821 JFR.start name=incident settings=profile duration=10m filename=/tmp/incident.jfr
$ jcmd 4821 JFR.dump name=incident filename=/tmp/incident-now.jfr   # snapshot mid-recording
$ jcmd 4821 JFR.stop name=incident
# better: always-on ring buffer from startup, so the incident is already recorded
# -XX:StartFlightRecording=disk=true,maxsize=512m,maxage=6h

I open the file in JDK Mission Control, start with its automated analysis page, then go straight to hot methods for CPU, the Java Monitor Blocked events for lock contention, and allocation by site for memory pressure. The always-on flag is the senior move: with a rolling six-hour buffer, the evidence for an incident exists before anyone is paged.

Land it JFR is the flight recorder metaphor made literal — run it continuously so the crash is already on tape.

Likely follow-ups
"What is in the 'profile' settings that the 'default' leaves out, and when is that extra cost worth it?"

The default.jfc file samples method execution every 20 milliseconds, records monitor waits over 20 milliseconds, and turns allocation profiling off in favour of cheap outside-TLAB events.

The profile.jfc file samples every 10 milliseconds, lowers the monitor and park thresholds to 10 milliseconds, enables allocation sampling, records old object samples for leak hunting, and turns on the more expensive I/O events.

The difference is roughly 1% versus 2% overhead on a typical service, which is still safe for production. I run default always-on and switch to profile for a bounded window during an incident.

For a specific hunt I edit a custom file: for lock contention I lower jdk.JavaMonitorEnter threshold to 1 millisecond, which would be too chatty permanently but is exactly right for ten minutes.

"How do you read a JFR file without Mission Control, on a server with no GUI?"

With the jfr command-line tool that ships with the JDK. jfr summary file.jfr lists the event types and counts, which tells me at a glance whether there are thousands of monitor-blocked events or none.

jfr print --events jdk.JavaMonitorEnter file.jfr dumps those events with stack traces, and jfr print --events jdk.ExecutionSample gives the raw samples.

For a quick flame graph without a GUI, jfr view hot-methods file.jfr on JDK 21 and later prints a table of the hottest methods, and the jfr view command has several dozen built-in views such as gc-pauses, allocation-by-site and contention-by-site.

I also convert to a flame graph with async-profiler's converter or the jfr2flame tool when I want the picture rather than the table.

"Does JFR see virtual threads, and what events matter for a Loom service?"

Yes, and the events are the main diagnostic for it. jdk.VirtualThreadStart and jdk.VirtualThreadEnd are disabled by default because of volume but can be turned on to count churn.

jdk.VirtualThreadPinned records every time a virtual thread blocks while pinned, with the stack and the duration, and is the first thing I look at after a migration; it should be empty on JDK 24 and later except for native frames.

jdk.VirtualThreadSubmitFailed fires when the scheduler cannot accept a task, which means the carrier pool is saturated or shut down. Method sampling includes virtual threads, so the flame graph covers them.

What JFR does not give me is a live count of virtual threads; for that I use the JSON thread dump or a gauge in the application.

"What does always-on JFR actually cost in disk and memory, and where does it write?"

In memory, JFR keeps per-thread buffers and a global buffer, typically a few tens of megabytes in total, set by memorysize when needed.

On disk, with disk=true it writes chunks to the repository directory, by default under /tmp or the path from -XX:FlightRecorderOptions=repository=, and the maxsize and maxage settings bound the total; 256 megabytes for two hours is typical for a busy service at default settings.

CPU overhead is around 1%. In a container I point the repository at a mounted volume so a dump survives the pod, and I make sure that volume is not the container's writable layer, which is slow and lost on restart.

With dumponexit=true the final chunk is written on a clean shutdown; an OOM kill from the kernel skips it, so the rolling chunks already on disk are what I get in that case.

Q239. "Explain how you'd use async-profiler and how to actually read a flame graph."

Reveal answer

Strong answer async-profiler is a sampling profiler that attaches to a running JVM and periodically records what every thread's stack looks like, combining kernel-level perf events with a JVM interface, so it can sample threads anywhere — not only at safepoints, which is a bias some JVM profilers suffer from.

Typical use: ./asprof -d 30 -f flame.html PID for thirty seconds of CPU profiling, with -e alloc for allocation or -e lock for contention.

The output is a flame graph: every box is a method, the vertical axis is call depth, and — the crucial rule — the horizontal axis is not time order; boxes are sorted alphabetically and merged.

Width is everything: a method's width is the fraction of samples it appeared in, which approximates its share of CPU time.

So I read a flame graph by scanning the top edge for wide plateaus — a wide, flat top is a method where the CPU actually spends its time, and the tower beneath it tells me how execution got there. Narrow spikes, however tall, are noise.

Land it Width is time and the plateaus are the story — anyone chasing tall narrow towers is reading the graph wrong.

Likely follow-ups
"What does async-profiler need from the box, and what fails in a locked-down container?"

For CPU mode it uses perf_event_open, which needs perf_event_paranoid at 1 or lower or the CAP_PERFMON capability, and kernel symbol access through kptr_restrict.

Most Kubernetes clusters block that by default, and the profiler then falls back to itimer mode, which samples on CPU time via signals and still works without kernel support, at the cost of losing kernel frames.

Wall-clock mode, -e wall, needs no privileges and is the one for latency questions, since it samples blocked threads too.

It attaches with the same JVM attach mechanism as jcmd, so the same UID rule applies, or it is loaded at startup as an agent, which is the reliable way in a container: -agentpath:/opt/async-profiler/lib/libasyncProfiler.so=start,event=cpu,file=/dumps/profile.html.

"Walk me through choosing between CPU, wall-clock, alloc and lock modes for a slow endpoint."

The mode has to match the question. If CPU is high, -e cpu, because it shows where computation goes.

If the endpoint is slow but CPU is low, -e wall with a thread filter for the request threads, because latency then lives in waiting, and only wall-clock sampling shows a thread parked on a lock or a socket.

If GC is busy, -e alloc, which samples allocations by the stack that made them and shows the allocation storm's source. If the dump shows contention, -e lock gives a flame graph of where threads wait on monitors and java.util.concurrent locks, weighted by wait time.

I usually run wall-clock first on a slow endpoint because it covers both cases, then narrow. Each run is thirty seconds and produces one HTML file, so trying two costs a minute.

"How do you compare two profiles to find a regression rather than just the hottest method?"

With a differential flame graph.

I take a profile from the previous build or from a healthy pod and one from the slow build under similar load, and generate a diff where each frame is coloured by the change in its share; async-profiler's converter and Brendan Gregg's difffolded.pl both produce this from the collapsed-stack output that -o collapsed writes.

Frames that grew are red and frames that shrank are blue, so a new method that appeared in the hot path stands out even if it is only 5% of samples.

Without the diff I would be comparing two pictures by eye and I would miss a modest regression spread across several frames. The precondition is matched load, so I run both profiles at the same request rate in a load test rather than on live traffic.

"What is a flame graph bad at, and what do you use instead in those cases?"

It has no time axis, so it cannot show that a method was fast for twenty seconds and then slow for ten; the merge hides ordering entirely.

For periodic stalls I need a timeline, which JFR in Mission Control gives with events plotted against time, or a flame chart, which is the unmerged variant with time on the horizontal axis.

It is also bad at rare, expensive events: a method that runs once for two seconds in a thirty-second profile is only 7% of samples and looks minor, though it is the whole p99.

Wall-clock sampling of just the slow requests, or tracing with a duration threshold, catches those better.

And it cannot show what is not on a stack, such as time waiting in a queue before a thread picks the request up; that gap is only visible in a trace with a span for the queue wait.

Q240. "Sampling versus instrumentation profilers — what's the difference, and why does production only ever get one of them?"

Reveal answer

Strong answer A sampling profiler interrupts the process on a timer — say every ten milliseconds — and records each thread's current stack; the result is statistical: methods appear in proportion to time spent, tiny costs may be missed, but the overhead is a few percent and the timing behavior of the application is barely disturbed.

An instrumentation profiler instead rewrites the bytecode to insert bookkeeping at every method entry and exit; the result is exact call counts and exact durations, but the cost is enormous — often several times slower — and worse than slow, it is distorting: cheap methods called millions of times inflate the most, so the profile exaggerates exactly the wrong suspects, and the changed timing can hide or create concurrency behavior.

That is why production only ever gets sampling — JFR or async-profiler — and instrumentation stays in development for questions where exact counts matter.

One refinement worth naming: samplers that can only sample at safepoints skew toward code near safepoint checks, which is why async-profiler's anywhere-sampling matters.

Land it Sampling estimates the truth cheaply; instrumentation measures a distorted program exactly — in production, a cheap honest estimate wins.

Likely follow-ups
"What is safepoint bias concretely, and what does it make you believe that is false?"

A safepoint is a point in compiled code where the JVM knows the exact state of every thread, placed at method returns and loop back-edges.

A profiler that can only sample at safepoints, which is how the old JVMTI GetAllStackTraces approach and early VisualVM worked, records each thread not where it is but at the next safepoint it reaches.

Tight loops without safepoint polls, and inlined code, get no samples, so the profile attributes their time to whatever method follows. The false belief is that a cheap method at a safepoint is expensive.

I have seen a profile blame a logging call that was really the return point after a hot arithmetic loop.

JFR's method sampler and async-profiler's AsyncGetCallTrace sample at arbitrary instructions and do not have this bias, which is why I trust them and not the safepoint-only tools.

"How many samples do you need before you trust a percentage?"

It is binomial statistics, so the error on a share p from n samples is roughly the square root of p times one minus p over n.

At the default 10 millisecond interval, thirty seconds on a single busy thread is 3,000 samples; a method at 10% has a standard error of about half a percentage point, which is plenty.

But that is per thread: a method at 1% of the profile with 3,000 samples has only 30 samples, and its error is about 18% of its own value, so I would not read a difference between 1.0% and 1.2% as real.

My rule of thumb is that anything under a few hundred samples is noise, and if I am chasing a tail effect I raise the sampling rate with -i or lengthen the recording rather than trust a thin slice.

"When would you accept instrumentation overhead in production, if ever?"

For a very small, deliberately chosen set of boundaries, which is what distributed tracing is.

A span around each incoming request, each outgoing call and each database statement is instrumentation, adding a few microseconds per span, and it is worth it because those boundaries are exactly where latency is spent and the count is low, tens per request.

What I never accept is method-level instrumentation across the codebase, where the overhead compounds on tiny methods and distorts the result. Micrometer's timers on a handful of business operations fall into the acceptable category as well.

The distinction is that I instrument events I already know are meaningful and sample everything else, which is what a mature observability setup looks like: traces for structure, sampled profiles for CPU, both in production.

Q241 · Scenario. "Average latency is flat at 40ms, but p99 spikes to two seconds exactly every thirty seconds. Users are complaining; your dashboard 'looks fine'. Diagnose it."

Reveal answer

The real test Whether you respect percentiles and can hunt a periodic stall.

Strong answer First, vocabulary: p99 is the latency under which 99% of requests finish, so a p99 spike means the slowest 1% of requests got dramatically worse while the typical request stayed fine — which is exactly why the average never moved. The thirty-second period is the biggest clue: load is random, but timers are periodic, so something scheduled is stalling the service on a clock.

  1. Plot p99 over time and confirm the period is exact — every 30 seconds, not roughly.
  2. Correlate the spike timestamps against the JVM's pause evidence: the GC log (-Xlog:gc*) and the safepoint log (-Xlog:safepoint), since some JVM operations briefly stop all threads and a slow one stalls everything.
  3. Pull the Flight Recorder window covering two spikes and look at what fires on that clock: a periodic JVM operation, a scheduled cache refresh saturating CPU, or file I/O stalls lining up with log flushing or rotation.
  4. Inventory the 30-second timers: @Scheduled jobs, metric flushes, sidecar agents, log rotation, health-check storms.

In practice this lands on one of three culprits — a safepoint or GC pause on a timer, a scheduled job hogging a shared resource, or synchronous log flushing — and the fix follows from which. The durable lesson I would state in the interview: alert on percentiles, because a stall that hits 1% of requests hits every user a few times an hour while every average on the wall stays green.

Land it Flat average plus periodic p99 spikes means a timer is stalling the tail — correlate timestamps, not magnitudes.

Likely follow-ups
"It turned out to be a two-second safepoint pause every thirty seconds, not GC. What causes that and how do you fix it?"

A safepoint pause is a full stop of all Java threads for a JVM operation, and several run on timers.

The classic culprit is a periodic thread dump or ThreadMXBean call from a monitoring agent, which needs a safepoint and walks every stack; with a few thousand threads that takes real time.

Others are JFR's periodic jdk.OldObjectSample and thread-state events, a metrics library calling ThreadMXBean.getThreadInfo for all threads, or the JVM's own GuaranteedSafepointInterval which by default forces a safepoint every second, though that one is cheap.

The -Xlog:safepoint output names the operation, such as ThreadDump or RevokeBias, and the time-to-safepoint, which is long when a thread is in a counted loop without a poll.

Fix: remove or slow the periodic dump, and if time-to-safepoint is the issue, -XX:+UseCountedLoopSafepoints, which is on by default in modern JDKs.

"How do you correlate p99 spikes with JVM events when your metrics are at one-minute resolution?"

One-minute buckets hide a two-second event, so I need finer sources.

The GC and safepoint logs have millisecond timestamps, and the APM's individual slow traces do too, so I join those directly: list the twenty slowest trace start times in the window and look for a JVM pause line within a second of each.

If most slow traces sit just after a pause, that is the cause.

For metrics, I temporarily raise the scrape resolution on one pod to five seconds, or better, use the latency histogram's exemplars, which link a histogram bucket to a specific trace ID at a specific time.

JFR is the cleanest source because it has everything on one timeline: I open the window in Mission Control and look at the pause events against the request duration events, and the alignment is visible without arithmetic.

"What if the spike is caused by a scheduled job on the same pod, and you cannot move it?"

Then I make the job stop competing with requests. Three levers.

Lower its priority: run it on a single thread instead of a pool, so it uses one core rather than all of them, and on Linux the JVM cannot set nice values per thread, so limiting the thread count is the practical throttle.

Bound its resource use: if it hammers the connection pool, give it its own small pool of two connections so it cannot starve requests; if it allocates heavily, process in smaller batches to reduce GC pressure.

Spread it in time: replace the exact 30-second timer with a jittered schedule so it does not align with anything else, and stretch the work over the interval rather than doing it all in one burst.

And I would keep arguing for moving it to a separate deployment, because a batch job and a latency-sensitive API in one process is a design smell.

"Give me the alert you would write so this is caught before users complain."

An alert on the p99 of the endpoint's latency histogram, evaluated over a five-minute window, firing when it exceeds the service-level objective for two consecutive evaluations: for a 200 millisecond target, histogram_quantile(0.99, rate(http_server_requests_seconds_bucket[5m])) > 0.5.

The five-minute window catches a periodic spike because the spike contributes to every window. I pair it with a GC pause alert, max_over_time(jvm_gc_pause_seconds_max[5m]) > 1, and a safepoint alert if the JVM's safepoint metrics are exported.

What I avoid is alerting on the average, which this incident showed is blind, and alerting on the p99 of a single scrape, which is too noisy. The user complaint is the alert that should never be the first one to fire.

Drill · Production fires — the classic incidents

Whether you recognize the recurring outage signatures on sight — each of these has a distinct dump or metric fingerprint, and a senior is expected to produce the fix from memory.

Q242 · Scenario. "Logs are full of HikariCP: 'Connection is not available, request timed out after 30000ms'. The DBA says the database is fine. What are the possible root causes and how do you tell them apart?"

Reveal answer

The real test One error message, three diseases — juniors pick one and guess; seniors differentiate.

Strong answer HikariCP is the standard connection pool for JDBC — Java's database access API — and this message means a thread waited the full connectionTimeout of thirty seconds for a pooled connection and none came free. That has exactly three root causes, and the pool's own metrics separate them:

  1. Pool too small for the load. Fingerprint: active connections sit at maximumPoolSize constantly, pending requests pile up, but each individual query is fast and the database shows short-lived statements. The pool is simply arithmetic: at 10 connections and 50ms per query you can serve about 200 database operations a second, and traffic exceeded it. Fix: raise the pool within the database's connection budget, or cut per-request database time.
  2. Leaked connections. Fingerprint: active climbs over hours and never comes back down, even when traffic drops — borrowed connections are never returned. I set leakDetectionThreshold=60000, and Hikari logs the stack trace of any borrower holding a connection over sixty seconds, which points at the exact code path — typically a missing close on an exception path or a manual transaction never completed. The database side shows sessions idle in transaction. Fix: try-with-resources everywhere, repair the broken transactional path.
  3. Queries too slow. Fingerprint: active is maxed and the database's process list — SHOW PROCESSLIST in MySQL, pg_stat_activity in Postgres — shows statements running for seconds. Each connection is held so long that a healthy pool starves. Fix: the query and its index, plus a statement timeout.

So my first move is never touching the pool size — it is reading active, idle, and pending together with the database's process list, because the same error message has three opposite fixes.

Land it "Pool exhausted" is a symptom with three causes — sizing, leaking, or slow queries — and the active/pending curve plus the DB process list picks the right one.

Likely follow-ups
"Which Hikari settings matter here, and what values would you set?"

maximumPoolSize sized to the database's capacity divided across instances, typically 10 or fewer per pod against a Postgres.

connectionTimeout, the 30 seconds in the error, is far too long for a request path; I set it to 1 to 3 seconds so a starved request fails fast rather than holding a Tomcat thread for half a minute.

leakDetectionThreshold at 30 to 60 seconds permanently, since its cost is one timestamp per borrow. maxLifetime a little under the database's or load balancer's idle timeout, so connections are retired before something else kills them.

idleTimeout and minimumIdle I leave at defaults, because a fixed-size pool is easier to reason about. And I set validationTimeout low. The single most important change is the connection timeout, because it decides whether a database hiccup costs seconds or minutes of thread starvation.

"Leak detection fires but the stack trace points at a framework method, not your code. How do you get to the real culprit?"

I read down the stack past the framework. The trace shows where the connection was borrowed, usually inside Spring's DataSourceUtils.getConnection called by a transaction manager, and further down is my service method that opened the transaction.

That method is the culprit: it holds the transaction, and therefore the connection, longer than sixty seconds.

Almost always it is doing something slow inside the transaction, a remote call or a large loop, or it is a long-running batch that legitimately needs the connection, in which case I raise the threshold for that path or split the batch.

If the trace really does end in framework code with no application frame, the borrow came from a framework-managed thread such as a scheduler, and I look for the scheduled method by the thread name in the log line.

"What does 'idle in transaction' on the database side tell you, and how do you find those sessions?"

It means a session has an open transaction but is not executing a statement: the application borrowed a connection, ran a query, and is now doing something else while the transaction stays open.

In Postgres, select pid, state, now() - xact_start as age, application_name, query from pg_stat_activity where state = 'idle in transaction' order by age desc lists them with how long each has been open. Long ages are held locks and leaked connections.

Setting application_name per service, and ideally per endpoint, through the JDBC URL or SET application_name makes the join to code trivial.

I also set idle_in_transaction_session_timeout on the database to something like five minutes, which kills such sessions and turns a silent hold into a loud error that gets fixed.

"You raised the pool size and the error rate got worse. Explain."

The database was the constraint, and the bigger pool pushed more concurrent queries into it.

Each query now competes with more others for the same cores and I/O, so every query gets slower, connections are held longer, and the pool exhausts at the new size too, with the added cost that the database is now overloaded for every other client as well.

That is the queueing result behind HikariCP's advice that small pools are faster: past the database's parallelism, throughput flattens and latency rises.

The fix is to move the queue back to the application, where waiting is cheap, by reducing the pool, and to shorten the per-query hold time with indexes and shorter transactions.

The diagnostic that would have prevented the change is the database's own CPU and active-session graphs, read before touching the pool.

Q243 · Scenario. "Every deploy causes a 90-second latency explosion, then the service recovers by itself. A dump taken during the window shows hundreds of threads BLOCKED in the same getInstance method. Explain and fix it."

Reveal answer

Strong answer This is a thundering herd on lazy initialization. The singleton builds something expensive on first use — loading a cache, parsing configuration, opening clients — inside a synchronized getInstance.

On a fresh JVM the first request triggers that build while holding the lock; every other request arriving during those seconds needs the same singleton and queues on the same monitor.

The dump shows exactly that: one thread RUNNABLE deep in initialization work, hundreds BLOCKED at the method entry.

Tomcat's worker pool drains, latency explodes, and — the nasty variant — if the load balancer's health checks also pass through that code path, the instance gets marked dead and restarted, which restarts the cold build, and the pod can crash-loop on its own cache.

  1. Confirm: the spike aligns exactly with deploys, and the dump during the window shows the single-initializer-many-waiters shape.
  2. Fix: initialize eagerly at startup, before the instance advertises itself ready — in Kubernetes terms, the readiness probe (the check that decides whether traffic is sent to the pod) must not pass until the expensive build is done.
  3. Where eager loading is too slow or optional, load asynchronously and serve a stale or default value while the fresh one builds, so no request ever waits on construction.

Prevention is a deploy-time discipline: warm the caches and pools as part of startup, then accept traffic.

Land it Lazy initialization plus concurrent traffic equals a herd on one monitor — do the expensive work before readiness, not on the first unlucky request.

Likely follow-ups
"Why is the holder-based or enum singleton not enough here, given it is the textbook lazy-init fix?"

Because those patterns fix the correctness of lazy initialisation, not its cost.

The initialisation-on-demand holder relies on the class loader's own lock to run the static initialiser exactly once, which is safe and cheap, but every thread that arrives while the initialiser is running still blocks on the class initialisation lock until it completes.

If the initialiser takes ninety seconds, the herd waits ninety seconds, exactly as with a synchronized getInstance. The dump even looks similar, with threads in RUNNABLE state at the class reference while the JVM reports them waiting on the initialisation.

So the pattern choice does not matter; the timing does. The expensive work must happen before traffic arrives, or asynchronously with a fallback, regardless of which singleton idiom guards it.

"How do you wire the readiness probe to the warm-up so traffic arrives only after the build?"

In Spring Boot, the readiness state is a bean the application can control.

I implement the expensive build in an ApplicationRunner or a SmartLifecycle bean that runs during startup, and the readiness endpoint, /actuator/health/readiness, reports OUT_OF_SERVICE until it finishes; if the build is asynchronous, I publish AvailabilityChangeEvent.publish(context, ReadinessState.ACCEPTING_TRAFFIC) when done.

Kubernetes then keeps the pod out of the service's endpoints until the probe passes, and with a rolling deployment the old pods keep serving until the new ones are ready.

I set initialDelaySeconds low and periodSeconds to a few seconds so the pod joins promptly once warm, and a startupProbe with a generous failure threshold so a slow build does not get the pod killed as unhealthy.

"The cache is a per-tenant structure and warming all tenants takes ten minutes. What now?"

Then I warm the hot subset and let the rest fill lazily without a herd. From access logs I know which tenants generate most traffic; warming the top hundred takes seconds and covers most requests.

For the long tail, I replace the synchronized build with a single-flight cache such as Caffeine's LoadingCache, which runs the loader once per key while other callers for the same key wait, and callers for other keys proceed, so a cold tenant costs only its own requests a delay, not the whole pool.

And I make the miss path bounded: a timeout on the build and a degraded response, such as defaults, rather than an unbounded wait.

Finally I persist the built cache to disk or a shared store so a restart reloads it in seconds instead of rebuilding from the source.

"Rolling deploys still produce a short spike even with eager warm-up. What is left?"

The JIT. A freshly started JVM runs interpreted and lightly compiled code for the first minute or two under load, so even with caches full, per-request CPU is several times higher until the hot paths reach C2. The mitigations are traffic ramping, where the load balancer sends a new instance a small share and grows it over a few minutes, which Envoy and most cloud balancers support as slow start; a synthetic warm-up that replays a few thousand representative requests against the instance before it reports ready, so compilation happens on fake traffic; and on JDK 24 and later, ahead-of-time class loading and profiling caches from JEP 483 and JEP 515, which as of Aug 2026 can persist training data across runs so a restarted JVM starts closer to peak. For most services, ramping alone removes the visible spike.

Q244 · Scenario. "The whole service slows to a crawl. The dump shows nearly every thread BLOCKED inside the logging framework — callAppenders — with one thread inside a file write. What is happening?"

Reveal answer

Strong answer The logger has become the global lock of the application. Synchronous appenders — the components that actually write log events to a file — take a lock per event so lines do not interleave. Normally the hold time is microseconds and nobody notices.

But when the disk stalls — a cloud volume out of burst credits, a full volume, a network filesystem hiccup — the thread inside write() holds the appender lock for tens or hundreds of milliseconds, and since every thread logs something on almost every request, the entire service serializes through that one lock.

The dump signature is unmistakable: one thread RUNNABLE inside FileOutputStream.write, everyone else BLOCKED in callAppenders or the equivalent appender path.

  1. Confirm the disk story: iostat -x shows high write await; cloud volume metrics show throttling or exhausted burst balance.
  2. Mitigate now: reduce log volume (drop to WARN via the framework's runtime configuration), and fix or replace the sick volume.
  3. Fix properly: asynchronous logging — Log4j2's AsyncLogger on its lock-free ring buffer, or an async appender with a bounded queue — so application threads hand off events and never touch the disk themselves.
  4. Decide the overflow policy consciously: when the buffer fills, drop log events rather than block threads — losing lines beats losing the service.

Prevention: treat logging as I/O with a failure mode, not as free, and load-test with a deliberately slowed disk once.

Land it A synchronous appender makes your latency floor equal your slowest disk write — go async and choose to drop lines, never threads.

Likely follow-ups
"You switched to async logging and now log lines are being dropped under load. Was that the right trade?"

Yes, if the drop was chosen deliberately and is visible. The async appender has a bounded queue, and when the disk cannot keep up the options are to block the application thread, which recreates the outage, or to drop.

Dropping is the correct default for a latency-sensitive service, but it must be tuned and measured: Logback's AsyncAppender drops only events below WARN when the queue is 80% full unless discardingThreshold is set to zero, so errors survive; Log4j2's async logger can be configured with AsyncQueueFullPolicy=Discard and a threshold level.

I export the dropped count as a metric and alert on it, because sustained drops mean either the disk is sick or the service is logging too much, and both are worth knowing.

What I would revisit is the volume: a service that logs several lines per request at INFO is usually logging for nobody.

"How did one slow disk write block threads in a different, unrelated logger?"

Because the lock is on the appender, not the logger.

In Logback, all loggers that route to the same file appender share that appender instance, and its doAppend is synchronized, so every thread writing any log line to that file queues behind the thread currently inside the write call.

Loggers are just names; the appender is the shared resource.

The same is true for the console appender, which is why logging to stdout in a container with a slow log collector reading the pipe produces the identical signature: one thread in FileOutputStream.writeBytes on the stdout descriptor, everyone else blocked in callAppenders.

In containers I check the log collector's health as the "disk" in this story, because a stalled Fluent Bit can block the pipe.

"What would you check on the volume itself, and what fixes the disk side?"

iostat -x 1 for the device: a high await, tens of milliseconds and up, with a %util near 100 means the disk is saturated.

On cloud volumes I check the provider's metrics for burst balance and throttled operations; a gp2 or similar credit-based volume that has spent its burst drops to a baseline of a few hundred IOPS, which a chatty service can saturate with log writes alone.

Fixes: move logs off the root volume onto a dedicated one or onto tmpfs with shipping, switch to a provisioned-IOPS volume, and reduce write frequency with buffered appenders that flush in larger chunks.

In Kubernetes, writing to stdout and letting the node's collector handle disk is usually the best answer, as long as that collector is itself healthy and not back-pressuring.

"How would you reproduce this in a test environment to validate the fix?"

By making the disk slow on purpose.

On Linux I mount the log directory on a device-mapper delay target, dmsetup create slow --table "0 SIZE delay /dev/sdX 0 200", which adds 200 milliseconds to every write; or simpler, run the service in a container with a blkio write throttle, --device-write-bps in Docker, limiting the log volume to a few hundred kilobytes per second.

Then I run the load test at normal traffic and watch p99 and the busy thread count. With synchronous appenders p99 goes to seconds and the dump shows the callAppenders pile-up, reproducing the incident.

With async appenders and a drop policy, p99 stays flat and the drop counter rises, proving the fix. That test then lives in the performance suite so nobody reintroduces a synchronous appender.

Q245 · Scenario. "Monitoring shows tens of thousands of sockets in CLOSE_WAIT on your service, growing all day. What does CLOSE_WAIT mean, and where is the bug?"

Reveal answer

Strong answer CLOSE_WAIT is a TCP connection state with a precise accusation in it: the remote side has closed its half of the connection, and the kernel is waiting for our process to call close() on ours. A handful in transit is normal; tens of thousands accumulating means our code is abandoning sockets without closing them — the socket object was dropped, but the file descriptor underneath was never released.

  1. Measure and attribute: ss -tan state close-wait | wc -l for the count, then group by peer address to see which downstream the leaked sockets point at — that usually names the client library involved.
  2. Find the code path: the classic bug is an HTTP client response body not closed on the error path — the happy path closes it, but a timeout or non-2xx branch returns early; also streams opened and lost when an exception skips the close.
  3. Distinguish the innocent look-alike: TIME_WAIT is held by whichever side closed first and expires on its own after a couple of minutes — it is normal churn, not a leak. Confusing the two wastes incidents.
  4. Fix: try-with-resources around every response and stream so every exit path closes, and connection pooling so sockets are reused rather than churned.

Left alone this ends as file-descriptor exhaustion, so I also put an alert on the CLOSE_WAIT count itself — it is one of the cheapest leak detectors there is.

Land it CLOSE_WAIT growth is the kernel telling you which side forgot to close — the peer hung up, and your code left the phone off the hook.

Likely follow-ups
"How do you get from a CLOSE_WAIT socket to the Java code that owns it?"

By joining on the file descriptor. ss -tanp state close-wait shows the PID and the descriptor number for each socket.

Then a heap dump lets me find the Java object holding that descriptor: in MAT I search for instances of sun.nio.ch.SocketChannelImpl or the older java.net.SocketImpl and read their fd field, and the dominator tree shows what references them, typically an HttpResponse, an InputStream wrapper, or a pooled connection object, which names the client library.

Without a heap dump, JFR's jdk.SocketRead events on the profile setting record the stack of every socket read with the remote address, and the stack of the last read on a leaked socket is the code that abandoned it.

The peer address alone often suffices, since each downstream usually has one client class.

"You added try-with-resources around the response and CLOSE_WAIT still climbs. What else leaks sockets?"

Closing the response object is not always the same as closing the socket.

With Apache HttpClient, a response whose entity is never consumed cannot return the connection to the pool; the fix is EntityUtils.consume or reading the body fully, which the close of a CloseableHttpResponse does but a plain HttpResponse does not.

With the JDK HttpClient, an unread body of a BodyHandlers.ofInputStream response holds the connection. Another source is the server side: our own accepted connections where the client closed and our handler never finished, common with a stuck request thread.

And connection pools with no idle eviction keep sockets the server has already closed; those show as CLOSE_WAIT until the pool's validation touches them, so enabling evictIdleConnections and validateAfterInactivity clears them.

"Why is a high TIME_WAIT count a different problem, and when does it matter?"

TIME_WAIT is held by the side that closed first, for twice the maximum segment lifetime, 60 seconds on Linux, to absorb late packets safely. It is not a leak: the kernel owns it, the descriptor is already freed, and it expires by itself.

It matters in one case: a client opening and closing many short connections to the same destination, where each connection consumes an ephemeral port and the roughly 28,000 ports in the default range are all sitting in TIME_WAIT, so new connections fail with "cannot assign requested address".

That is the symptom of a missing connection pool, and the fix is reuse, not kernel tuning, though net.ipv4.tcp_tw_reuse=1 and a wider ip_local_port_range buy time.

So when I see a big TIME_WAIT number I ask "who is not pooling", and when I see CLOSE_WAIT I ask "who is not closing".

Q246 · Scenario. "Requests start failing with 'java.net.SocketException: Too many open files'. Walk me through the hunt."

Reveal answer

Strong answer A file descriptor is the small integer handle the kernel gives a process for each open file, socket, or pipe, and every process has a ceiling on how many it may hold. This error means we hit it — and since sockets are descriptors too, the service now cannot accept or make connections, so it fails broadly and weirdly.

  1. Measure against the real limit: ls /proc/PID/fd | wc -l for the current count, and cat /proc/PID/limits for the process's actual ceiling — not ulimit -n in my shell, which describes my shell, not the service.
  2. Classify the population: lsof -p PID, then count by type. Thousands of sockets to one host means a connection or response-body leak toward that host; thousands of handles on the same file means open-without-close in a loop; many pipes point at process spawning.
  3. Check the growth curve on the descriptor-count metric: steady climb from startup is a per-request leak; a step jump correlates with a feature or deploy.
  4. Match the dominant descriptor type to code and fix the missing close — almost always an exception path that skips cleanup, cured by try-with-resources.

Raising the limit — LimitNOFILE in the systemd unit, or the container spec — is legitimate breathing room during the incident, but it only moves the wall; a leak will reach any number. Prevention: export the process's open-descriptor count and alert at around 70% of the limit, so the hunt happens on a Tuesday afternoon instead of during the outage.

Land it Count them, classify them with lsof, fix the close — raising the ulimit is anesthesia, not surgery.

Likely follow-ups
"lsof is not installed in the container. How do you classify the descriptors?"

From /proc directly. ls -l /proc/PID/fd shows each descriptor as a symlink whose target is a file path, or socket:[inode], or pipe:[inode], or anon_inode:[eventpoll]. Counting by target type with a short awk gives the same breakdown lsof would.

For sockets, I join the inode numbers against /proc/net/tcp and /proc/net/tcp6, which list every socket with its inode, local and remote address in hex, and state, so I can group leaked sockets by destination without any tools.

For files, the symlink target is the path, so a thousand descriptors pointing at the same jar or log file identify the leak instantly.

This works in a distroless image with only a shell missing, via a debug container sharing the process namespace, because /proc/PID is visible across it.

"What descriptors does a healthy JVM hold, so you know what is normal?"

A baseline of a few hundred. Every jar on the classpath is mapped and held open, so a Spring Boot fat jar counts as one but an exploded classpath with 200 jars is 200 descriptors.

Then the listening sockets, the accepted connections in flight, the pooled database connections, the pooled HTTP connections per destination, the log files, a handful of epoll and eventfd descriptors for NIO selectors, and the JVM's own files such as the perf memory file.

So 300 to 600 at idle is ordinary. The default soft limit of 1024 on some distributions is therefore tight, and 65,536 is the common production setting.

Knowing the baseline means that when I see 8,000 I can say "7,500 of those are sockets to one host" rather than wondering whether 8,000 is normal.

"Descriptor count is stable but the error still fires occasionally. What is that?"

A burst rather than a leak.

Some operation opens many descriptors at once and closes them afterward, so the average looks fine but the peak hits the limit: a parallel stream opening a file per element, a fan-out of a thousand HTTP calls with no connection pool cap, or a backlog of accepted connections during a traffic spike.

The descriptor-count metric at one-minute resolution smooths the peak away. I catch it by lowering the scrape interval on one pod, or with JFR's jdk.FileRead and jdk.SocketRead events around the error's timestamp, which show the burst's stacks.

The fix is a bound on the concurrent operation, a semaphore or a pool with a maximum, rather than a bigger limit, though raising the limit is a fine stopgap because a burst does not grow without end the way a leak does.

"How do you set the limit correctly in Kubernetes, given ulimit in the shell does not apply?"

The limit a container inherits comes from the container runtime's defaults, typically from containerd's or Docker's daemon configuration, and it is often already 1,048,576 for the soft limit on modern setups, though older nodes had 1,024.

I check what the process actually got with cat /proc/PID/limits inside the pod, never assume.

If it is low, the options are the node-level runtime configuration, an init container or entrypoint that runs ulimit -n 65536 before starting the JVM, which works if the hard limit permits it, or a securityContext that grants the capability to raise it.

The JVM has no flag for it. I verify after deploy with the same /proc/PID/limits check and export the ratio of open to max as a metric with an alert at 70%.

Q247 · Scenario. "Outbound calls intermittently take five extra seconds. Thread dumps during the slowness show threads RUNNABLE in Inet6AddressImpl.lookupAllHostAddr. What is this and what do you do?"

Reveal answer

Strong answer That frame is DNS — the Domain Name System, which translates hostnames into network addresses — and threads sitting in lookupAllHostAddr are stuck inside the native name lookup. It is another case of RUNNABLE hiding a wait. The five-second number is itself a clue: it is a classic resolver timeout, the stall you get when the first configured DNS server is dead and the lookup waits out its timeout before trying the next.

  1. Confirm the resolver story from the box: test lookup times directly, and check /etc/resolv.conf for a dead first server or an overloaded node-local cache.
  2. Check Java's own caching rules, because they control how often we even ask: successful lookups are cached for networkaddress.cache.ttl — thirty seconds by default — but failed lookups are cached only for networkaddress.cache.negative.ttl, ten seconds by default, so a flaky name gets re-resolved constantly, multiplying exposure to the slow resolver.
  3. Look at connection behavior: a service that opens fresh connections per request resolves names constantly; one with pooled, kept-alive connections resolves rarely and barely notices DNS trouble.

Fixes, in order of leverage: repair the resolver path (healthy node-local DNS cache, no dead servers in the list), reuse connections so lookups are rare, tune the JVM's TTLs deliberately rather than by default, and bound the damage with connect timeouts so a resolution stall costs a known amount. Prevention: monitor DNS lookup latency as a first-class dependency — it is one of the few dependencies that every outbound call shares.

Land it DNS is a dependency that hides inside every other dependency — pooled connections and a healthy resolver make it boring, which is the goal.

Likely follow-ups
"Why exactly five seconds, and where in the stack is that number configured?"

Five seconds is the default per-server timeout of the glibc resolver, set by the options timeout:N line in /etc/resolv.conf, with attempts:2 as the default retry count.

When the first nameserver does not answer, the resolver waits the full timeout before trying the next, so a dead first server adds exactly five seconds to every uncached lookup.

In Kubernetes there is a second source of stalls: the default ndots:5 setting means a name like api.partner.com is first tried with each search domain appended, producing several failing lookups before the real one, and if the cluster DNS is slow each of those costs time.

The fixes are a healthy first server, a lower timeout:1 with attempts:3, and using fully qualified names with a trailing dot or a lower ndots for external hosts.

"Java's DNS cache TTL: what are the defaults really, and does the security manager story still apply?"

As of Aug 2026 the defaults are that successful lookups are cached for 30 seconds and failures for 10 seconds, controlled by networkaddress.cache.ttl and networkaddress.cache.negative.ttl in the JDK's conf/security/java.security file or set at startup with Security.setProperty.

The old story that Java caches forever applied only when a security manager was installed, and the security manager was removed from the JDK entirely in JDK 24, so that behaviour is gone. The system property sun.net.inetaddr.ttl still works as a legacy override.

What I would set: a positive TTL matching the DNS record's TTL if the service targets endpoints that fail over by changing addresses, and a negative TTL of a few seconds so a transient NXDOMAIN does not stick.

"How would you measure DNS latency from inside the JVM without changing code?"

With JFR. Since JDK 21 there is no dedicated DNS event, but a wall-clock method profile shows time spent in InetAddress.getAllByName and the native lookupAllHostAddr, and the duration distribution of those samples is the resolver latency.

Alternatively, Micrometer's HTTP client instrumentation records connect time separately from response time on some clients, and a jump in connect time with no change in TCP handshake time is DNS.

From the box, dig +stats api.partner.com @nameserver reports the query time, and a loop of those against each configured server tells me which one is slow. And at the cluster level, CoreDNS exports coredns_dns_request_duration_seconds, which shows whether the resolver itself is the bottleneck for everyone.

"What if the slowness comes from the JVM resolving on every request even though connections are pooled?"

Then the pool is not reusing connections, and DNS is a symptom. Each new connection resolves the host, so a lookup per request means a connection per request.

The usual reasons are a client created per request, so the pool is new each time; a server that sends Connection: close; a pool with idle eviction set to a very short time; or HTTPS to a host whose certificate or SNI configuration forces renegotiation.

I confirm with the client's pool metrics, leased versus available connections and the rate of new connection creation, and with ss -tan dst HOST showing many short-lived sockets and TIME_WAIT churn.

Fixing the reuse fixes the DNS exposure at the same time, and the lookup count drops to one per connection lifetime, which is minutes rather than milliseconds.

Q248 · Scenario. "A report job runs on @Scheduled(fixedRate = 60000). It used to take 45 seconds; data grew and it now takes 90. Strange things start happening. What exactly goes wrong, and how do you schedule it correctly?"

Reveal answer

Strong answer fixedRate means "a run is due every 60 seconds, measured start to start, regardless of how long the previous run took". The moment the job's duration crossed its period, the schedule went into debt. What that looks like depends on the scheduler behind it.

On Spring's default single-threaded scheduler, runs cannot literally overlap, so overdue runs queue and execute back to back with zero gap — the job now runs continuously, and every other scheduled task on that one thread starves silently.

With a multi-threaded scheduler, or Quartz without a concurrency guard, two runs of the same job genuinely execute at once: a thread dump shows two threads inside the same job method, and you get doubled emails, database lock contention between the twins, and corrupted "last run" bookkeeping.

  1. Detect: emit the job's run duration as a metric and alert when it approaches the period — this failure announces itself months in advance.
  2. Fix the semantics: fixedDelay measures from the end of one run to the start of the next, so a slow run stretches the cycle instead of stacking runs.
  3. Fix multi-instance overlap: several pods each run the scheduler, so add a distributed guard — ShedLock or a database lock — so exactly one instance runs the job; in Quartz, @DisallowConcurrentExecution.
  4. Make the job idempotent anyway, because some day it will double-run despite everything.

Land it The moment a job's duration can exceed its period, fixedRate becomes a self-overlap generator — use fixedDelay plus a distributed lock, and watch duration versus period as a metric.

Likely follow-ups
"With fixedDelay and a distributed lock in place, the job still ran twice in one minute across two pods. How?"

Almost certainly the lock expired before the job finished.

ShedLock and similar tools take a lock with a lockAtMostFor duration as a safety against a crashed holder; if that is set to 30 seconds and the job takes 90, the lock is released while the first pod is still running, and the second pod acquires it and starts a duplicate.

The fix is lockAtMostFor longer than the worst-case run, with an alert on run duration approaching it. The second cause is clock skew between pods, which matters for time-based locks; using the database's clock, which ShedLock does for JDBC, avoids that.

The third is two different lock names for what is logically one job after a refactor. The job's own log should print the lock holder's identity and the acquisition time, which makes the sequence obvious.

"Should the job even be in the web service? What would you do in a greenfield design?"

I would take it out. A scheduled job inside a horizontally scaled API means every replica runs the scheduler and needs a distributed lock to run once, and the job's resource use competes with request latency on the same pod.

In a greenfield design I make the job its own deployment, a Kubernetes CronJob or a single-replica worker, so there is exactly one runner by construction, it has its own CPU and memory, and it can be scaled or paused independently.

The job itself reads a checkpoint, does bounded work, writes the checkpoint, and exits, which makes retries and overlap questions disappear. If the work is triggered by events rather than time, a queue consumer replaces the schedule entirely.

The distributed lock is the right patch for the existing design, not the design I would choose.

"How do you make a report job idempotent, concretely?"

By making every side effect keyed. If the job writes rows, it writes them with a deterministic key such as the report period and the entity, using an upsert, so a second run overwrites instead of duplicating.

If it sends emails, it records each recipient and period in a sent table with a unique constraint before sending, and skips on conflict, so a re-run sends nothing twice.

If it calls an external API, it passes an idempotency key derived from the same period and entity.

The run itself records a status row with the period as its key: started, finished, or failed, so a second run for the same period can see the first and either skip or resume.

That turns "the job ran twice" from an incident into a no-op, which is the only durable protection since locks and schedules will eventually let a duplicate through.

"What does the default Spring scheduler thread pool look like, and what would you change?"

By default Spring Boot's @Scheduled tasks run on a single-threaded ThreadPoolTaskScheduler, so all scheduled methods in the application share one thread and any slow one delays every other.

The first change is spring.task.scheduling.pool.size to a small number, say 4, so jobs do not starve each other, accepting that this enables true overlap and therefore requires the delay semantics and the lock. The second is naming, spring.task.scheduling.thread-name-prefix, so dumps show which thread is a scheduler.

The third, on JDK 21 with spring.threads.virtual.enabled=true, is that the scheduler uses virtual threads and the pool size stops being the constraint.

And I add Micrometer timers around each job by annotating with @Timed or wrapping them, because a job with no duration metric is one that will silently cross its period one day.

Q249 · Scenario. "A downstream service degrades to 20% errors. Two minutes later it is 100% down and so are you. Traffic from users never changed. What happened and how do you design retries that don't do this?"

Reveal answer

The real test Do you understand that retries are load amplification wearing a safety costume.

Strong answer This is a retry storm. Every caller was configured to retry three times on failure, immediately.

When the downstream degraded, each failing request became up to four requests, so the sick service — already short on capacity — received a multiple of its normal load at the worst possible moment, tipped over completely, and then the storm kept it down: every attempt fails, every failure retries, and the system holds itself underwater.

The giveaway in metrics is amplification — request rate into the downstream spiking while user-facing request rate is flat.

  1. Immediate mitigation: shed the retries — open the circuit breaker or flag retries off — and let the downstream breathe; recovery is usually quick once offered load drops back below capacity.
  2. Redesign with backoff and jitter: retries wait exponentially longer each attempt, with a randomized component so thousands of clients do not retry in synchronized waves.
  3. Add a retry budget: retries may not exceed, say, 10% of base traffic; past that, failures return to callers instead of amplifying. A circuit breaker enforces the same idea by tripping open when the error rate crosses a threshold.
  4. Retry only what is safe and bounded: idempotent operations, with a timeout on every attempt, and at one layer of the stack — if the edge, the service, and the client library each retry three times, a single user click can become twenty-seven requests.

Land it A retry is a bet that the failure was transient, paid for in extra load on a struggling service — budget the bets, jitter them, and place them at exactly one layer.

Likely follow-ups
"Show me the arithmetic for how much load your retries added at 20% and at 100% error rate."

Take 1,000 requests per second from callers and three immediate retries on failure.

At a 20% error rate, 200 requests fail on the first attempt and each is retried; if the retry has the same 20% failure chance, the expected attempts per request are 1 + 0.2 + 0.04 + 0.008, about 1.25, so the downstream sees 1,250 per second, a 25% increase at the moment it is already struggling.

At 100% errors every request makes all four attempts, so it sees 4,000 per second, four times its normal load, with zero successes.

That is the cliff: the amplification factor is small while the service is healthy and becomes the full retry count exactly when it is dead. Add a second retrying layer above and the numbers multiply: 4 × 4 is 16 times normal load.

The math is why a retry budget is a hard rule and not a preference.

"You added exponential backoff with jitter and the downstream still could not recover. Why?"

Backoff spreads the retries in time but does not reduce their total. If every failed request still gets three more attempts, the downstream receives the same four times its capacity, just smoothed over a longer window, and it stays underwater as long as callers keep retrying.

Recovery needs the offered load to drop below capacity, which only a budget or a breaker achieves: after some failure rate, stop retrying entirely and fail the request.

The second reason is that the original requests keep arriving at full rate; if the downstream is at 50% capacity, even zero retries leave it overloaded, and something must shed the excess, which is load shedding at the downstream or a concurrency limit at the caller.

And a third: queued requests in the downstream from before the collapse are dead work that must be drained or dropped before it can serve live traffic.

"How do you implement a retry budget in practice with Resilience4j or a similar tool?"

Resilience4j's Retry has no budget concept built in, so I compose it with a circuit breaker and a rate limiter.

The breaker in front of the retry means that once the failure rate crosses the threshold, calls fail fast and the retry never fires, which caps amplification at the breaker's window.

For a true budget I add a RateLimiter that only retries pass through, sized at 10% of normal traffic, so retries beyond that are rejected while first attempts are unaffected.

gRPC's client configuration has a native retryThrottling with a token bucket that is exactly this design, and Envoy's retry budget does it at the mesh layer by percentage of active requests, which is the best place because it is enforced for every service uniformly.

I also export the retry count as a metric with a ratio alert, because a budget being hit is the early signal of a downstream in trouble.

"What makes a failure safe to retry, and how do you know from the response?"

Two conditions: the operation must be idempotent, so a repeat cannot cause a second effect, and the failure must be plausibly transient, so a repeat can succeed. Connection refused, connection reset before any bytes were sent, and a 503 with a Retry-After are transient.

A read timeout after the request was sent is ambiguous, because the server may have completed the work, so it is safe only for idempotent operations, a GET, a PUT, a DELETE, or a POST with an idempotency key.

A 500 is usually a bug that will repeat; a 400, 401, 403 or 404 never benefits from retry, and retrying a 429 makes the rate limit worse unless the delay honours Retry-After.

So my retry predicate is a short allowlist of statuses and exception types, not "any exception".

Q250 · Scenario. "Requests hang forever. jstack finds no deadlock. The DBA finds no deadlock. Yet the service is frozen, and it stays frozen. What class of problem should you suspect, and how do you prove it?"

Reveal answer

The real test The mixed-resource deadlock — the one neither tool can see alone. This separates staff-level debuggers.

Strong answer Suspect a deadlock whose cycle passes through two different lock systems — a JVM monitor on one side and a database row lock on the other.

Concretely: thread A, inside a transaction, updates a row (acquiring the database's lock on it) and then tries to enter a synchronized block; thread B already holds that monitor and, while holding it, executes an update on the same row, so it blocks inside the database driver.

A waits for the monitor B holds; B waits for the row lock A holds. It is a textbook cycle — but split across two worlds.

Each tool sees only half: jstack shows A as BLOCKED and B as merely RUNNABLE inside a socket read ("just a slow query"), so no cycle; the database shows B's session waiting on a row whose holder is a session that is idle in transaction and waiting on nothing the database knows about — again no cycle.

  1. Recognize the shape: a permanent hang, jstack clean, and the monitor holder's stack ends inside JDBC — executeUpdate down to a socket read.
  2. Join the two views: map database sessions to JVM threads — set a per-request application_name or log the connection identity — and show that B's blocking session belongs to the very thread waiting on B's monitor. That closes the cycle on paper.
  3. Note why it hangs "forever": the database side would eventually break — lock wait timeouts like innodb_lock_wait_timeout default to about 50 seconds — but a monitor wait has no timeout at all.

The fix is a rule, not a patch: never perform database work while holding a JVM lock, and never acquire a JVM lock while holding uncommitted row locks — one resource world at a time, or one global acquisition order across both.

Land it When both tools say "no cycle" but nothing moves, the cycle crosses tools — join JVM threads to database sessions and it appears.

Likely follow-ups
"How do you set application_name per thread so the join works, without touching every query?"

At the connection pool level.

HikariCP lets me run a statement on every borrow through a wrapper, but the cheaper method is to set it per session when the connection is created via connectionInitSql, and then per request with a small interceptor that executes SET application_name = 'orders-api:POST /checkout:thread-42' after borrowing.

In Postgres that is a cheap session-level setting. With Spring, a TransactionSynchronization or a datasource proxy hook runs once per transaction start.

The value should include the service, the endpoint, and the JVM thread name, so a row in pg_stat_activity maps directly to a thread in the dump.

MySQL has no direct equivalent but supports a comment in the first statement, and some drivers expose a connectionAttributes parameter that shows in performance_schema.session_connect_attrs.

"You cannot change the code today. How do you break the hang and buy time?"

Two database-side knobs turn the permanent hang into a periodic failure. First, lock_timeout in Postgres, set per role or in the JDBC URL's options, makes any wait for a row lock fail after a few seconds; in MySQL, innodb_lock_wait_timeout lowered from 50 to 5.

When B's update times out, it throws, B releases its monitor, A proceeds, and the cycle dissolves into one failed request instead of a frozen service.

Second, idle_in_transaction_session_timeout kills a session that holds row locks while doing nothing, which is A's state while it waits for the monitor.

Neither is a fix, and both make the bug visible as errors, which is the point: the error rate now says how often the cycle happens, and the stack traces of the timeouts point at the two methods that must be restructured.

"What tooling would have detected this in staging?"

A test that runs the two operations concurrently against a real database, in a loop, with a global timeout, which is what a jcstress-style harness cannot do because the cycle needs the database.

I write it with Testcontainers: two threads, one performing the update-then-synchronize path, the other the synchronize-then-update path on the same row, a thousand iterations, and a five-second watchdog that fails the test and prints a dump if neither completes.

It reproduces within seconds because the window is wide. In addition, an ArchUnit or Error Prone rule that forbids calling a repository or JdbcTemplate from inside a synchronized block, and its mirror, forbids taking a monitor inside a @Transactional method, catches the pattern statically.

The rule is simple to state: a transaction and a monitor should never be held at the same time.

Q251 · Scenario. "A rare data-corruption bug reproduces every few hours under load. You add debug logging around the suspect section, and the bug completely disappears. Why — and what do you do instead?"

Reveal answer

Strong answer The logging did not fix the bug; it changed the experiment.

Logging is synchronized — appenders take a lock per event — and the Java memory model attaches ordering and visibility guarantees to lock operations, so the log lines added exactly the synchronization the buggy code was missing.

It also slows the racing threads by microseconds, shifting the timing so the harmful interleaving stops occurring.

Both effects hide races, and the disappearance is itself a strong diagnosis: I am almost certainly looking at a data race — unsynchronized shared access whose outcome depends on timing.

  1. Treat the vanishing act as evidence, not victory: the bug is still there, waiting for different timing in production.
  2. Observe without synchronizing: emit JFR custom events, which are cheap and do not take shared locks, or record into a pre-allocated lock-free ring buffer in memory and dump it only when the corruption is detected.
  3. Take the hypothesis offline: extract the suspect access pattern into a jcstress test — OpenJDK's harness that hammers a few lines of concurrent code across millions of interleavings — where the race reproduces in seconds instead of hours.
  4. Then fix the actual sharing bug: the missing volatile, the compound check-then-act without a lock, the collection shared without a concurrent wrapper.

Land it A bug that logging "cures" is a race by definition — the cure is accidental synchronization, and the real fix is making the synchronization deliberate.

Likely follow-ups
"What does a JFR custom event look like, and why does it not perturb the race the way logging does?"

It is a small class extending jdk.jfr.Event with annotated fields: @Label("Balance update") class BalanceEvent extends Event { long accountId; long before; long after; }. At the suspect point I create one, set the fields, and call commit().

The write goes into a thread-local buffer with no shared lock, so there is no synchronization between threads, and the cost is tens of nanoseconds, so timing barely shifts. The buffers are flushed to the recording asynchronously.

Contrast with a log line, which formats a string, takes the appender lock, and writes to a file, adding microseconds and a full happens-before edge between every pair of threads that log.

JFR events are also queryable: jfr print --events BalanceEvent lists them with thread and timestamp, so I can see the exact interleaving that preceded the corruption.

"How would you extract the suspect into a jcstress test, concretely?"

I isolate the shared state and the two or three operations that touch it into a small class with the same field declarations, plain or volatile, and the same method bodies stripped of I/O. The jcstress test has a @State class holding that object, @Actor methods that each run one of the operations on it, and an @Arbiter or result fields that record the outcome.

I declare the acceptable outcomes with @Outcome annotations and mark everything else as forbidden. Running it for a few minutes reports every outcome observed with counts; a forbidden outcome appearing even once is the race, and the counts tell me how rare it is.

The value is that the test is deterministic in what it checks, runs in the build, and stays as a regression test after the fix, which a production repro never can.

"The corruption stopped after you fixed one race, but you are not confident. How do you close the case?"

With evidence from three directions. First, the jcstress test for the fixed code shows zero forbidden outcomes over a long run, and the same test against the old code shows them, which proves the fix addresses the reproduced race.

Second, in production, a JFR custom event or an invariant check at the point of corruption, such as asserting the balance never goes negative and emitting an event if it does, runs for a couple of weeks with zero hits, where before it fired every few hours.

Third, a review of every other access to the same fields, because a race on one field usually means the sharing model was never designed and there are siblings.

If all three are clean I close it, and I write the sharing rule for that class into its Javadoc so the next change does not reopen it.

"Are there tools that detect data races in Java automatically?"

Fewer than for C and C++, where ThreadSanitizer is standard.

For Java, the practical ones are jcstress for targeted tests, and dynamic race detectors that instrument bytecode to track happens-before at runtime, such as the research tool RoadRunner or the older ThreadSanitizer-for-Java experiments, which have too much overhead for production but can run a test suite.

Static tools catch the common shapes: Error Prone's GuardedBy checker enforces that fields annotated with @GuardedBy("lock") are only touched while holding that lock, and SpotBugs flags inconsistent synchronization where a field is sometimes accessed under a lock and sometimes not.

None of them finds every race, so the honest answer is that a sharing discipline, immutable objects and confined mutable state, prevents more races than any detector finds.

Q252 · Scenario. "One pod out of twelve keeps dying with OutOfMemoryError. Same build, same config, same traffic split. You cannot reproduce it anywhere. What's your move?"

Reveal answer

Strong answer One pod misbehaving under an identical build means the data differs, not the code — something routes disproportionate work to that pod. My first job is not to explain it; it is to stop losing the evidence, because right now every crash destroys the proof.

  1. Arm the JVM to capture on death: -XX:+HeapDumpOnOutOfMemoryError with -XX:HeapDumpPath=/dumps pointing at a mounted persistent volume sized larger than the heap, so the dying JVM writes a full heap snapshot before the pod vanishes.
  2. Add -XX:+ExitOnOutOfMemoryError so that after the dump the JVM exits immediately rather than limping on — an OutOfMemoryError can kill arbitrary threads mid-operation and leave the application half-alive and corrupting state; a clean exit lets the orchestrator restart it fresh.
  3. While waiting for the next occurrence, hunt the asymmetry: which Kafka partitions are assigned to that pod (one hot or poisoned partition follows the consumer), whether session-sticky routing pins one huge tenant to it, whether a poison message is redelivered to it on every restart, whether it alone runs a singleton job via leader election.
  4. When the dump lands, hand it to heap analysis — that is its own discipline — but by then the partition or tenant correlation has usually already named the suspect.

Prevention: make those two flags standard in every service's launch configuration, because the first OutOfMemoryError should always leave a body to examine.

Land it One bad pod means skewed data, not broken code — arm the dump flags first, then find what only that pod is fed.

Likely follow-ups
"The heap dump is 8 GB and MAT cannot open it on your laptop. What do you do?"

I do not analyse it on a laptop.

MAT needs roughly as much heap as the dump's live set, so I run it headless on a large machine: the ParseHeapDump.sh script that ships with MAT, given -Xmx12g, parses the dump and produces the leak suspects, dominator tree, and histogram as HTML reports without a GUI. That runs in the cluster on a job pod with the dump volume mounted, and I download the reports, which are megabytes.

If even that is too large, jcmd PID GC.class_histogram on a live pod gives the instance counts by class in seconds with no dump at all, and for a leak the top of that list is usually the answer.

I also make sure the dump was taken with -XX:HeapDumpOnOutOfMemoryError rather than a live dump, since the OOM dump already excludes unreachable objects.

"How do you confirm the partition hypothesis without waiting for another crash?"

From the consumer group's assignment. kafka-consumer-groups --describe --group NAME lists each partition, its assigned consumer, and its lag; if the dying pod owns a partition whose lag or throughput is far above the others, or which holds one enormous key, that is the asymmetry.

I compare the message size distribution per partition with a quick consumer that samples each one, since a single 50-megabyte message on one partition is a classic.

Then I test the hypothesis directly: reassign that partition to a different pod by restarting the group with a sticky assignor and watch whether the OOM follows the partition. For a tenant-routing hypothesis I do the same with the load balancer's routing table.

Moving the suspected cause and seeing the symptom move is the proof, and it takes an hour rather than another two days.

"What if the dump shows nothing unusual, just lots of ordinary request objects?"

Then the pod is not leaking; it is simply doing more concurrent work than its heap allows, and the dump is showing a burst.

I look at the dominator tree by thread: if the retained memory hangs off many request threads each holding a large response buffer, one large request or many at once exceeded the budget.

That points at input size limits, a missing cap on page size, a bulk endpoint with no bound, or an export that materialises a result set.

The fix is to bound the work per request, stream large responses, and reject requests beyond the limit with a 413.

And I check whether this pod has a smaller heap by accident, for example a different node with less memory and a percentage-based -XX:MaxRAMPercentage, which is a surprisingly common "same config" that is not the same.

"Why is ExitOnOutOfMemoryError better than letting the JVM continue, and when would you not use it?"

Because after an OOM the process is in an unknown state.

The error is thrown in whichever thread happened to allocate last, which may be a pool worker that dies silently, a Kafka consumer that stops polling, or a thread holding a lock that never gets released; the JVM keeps running, health checks may pass, and the service serves partial or corrupt results for hours.

Exiting immediately hands the decision to the orchestrator, which restarts a clean process in seconds.

I would not use it only when the process has irreplaceable in-memory state to flush, which is a design smell in itself, or in a batch job where I would rather it fail the current item and continue, but even there I prefer -XX:+CrashOnOutOfMemoryError for the core dump and a restart. In a stateless service it is always on.

Q253 · Scenario. "A product manager says 'the app is slow' and that's all the information you get. Show me your first fifteen minutes."

Reveal answer

The real test Whether you have a method, or you ssh somewhere and start hoping.

Strong answer The discipline is metrics before machines, and I use two checklists: RED — Rate, Errors, Duration for every service — and USE — Utilization, Saturation, Errors for every resource.

  1. Minutes 0–3: turn the sentence into a number. Which endpoint or flow, which percentile, how bad, since when. "Checkout p99 went from 300ms to 4s starting 14:10" is debuggable; "slow" is not.
  2. Minutes 3–5: what changed at that time. Deploys, configuration and flag changes, traffic shape, a dependency's release. Most incidents are changes; correlation with the start time is the cheapest diagnostic that exists.
  3. Minutes 5–12: sweep the dashboards, RED then USE. Per-endpoint duration and errors to localize the slow path; then saturation of each resource in order — CPU and container throttling, garbage-collection time share, thread-pool busy versus max, connection-pool active and pending, downstream latency and timeout counts. I am looking for the one graph whose shape changed at 14:10; saturation of some pool is the usual answer.
  4. Minutes 12–15: localize and go deep. Is it one pod or all of them? One pod means that box — hardware, neighbor, skewed data; all pods means shared code or a shared dependency. Only now do I pick one bad pod and take my three thread dumps, because now I know what I am looking for in them.

The junior mistake is inverting this — an hour inside one pod's dump for a problem the dashboards would have placed in the database in ninety seconds.

Land it Metrics shrink the search space from "everything" to one resource; dumps then confirm — never the other way around.

Likely follow-ups
"Minute 15 and nothing on the dashboards changed at 14:10. What do you do next?"

I widen the definition of "changed" and the definition of "us". Nothing changing on my dashboards usually means the change is upstream or in the data.

I check the callers: did a client start sending a new query shape, a bigger page size, or a burst from a batch job, which shows as a change in request mix rather than request count.

I check the data: did a table cross a size where a plan flipped, which shows in the database's slow query log as the same statement suddenly taking longer.

I check the platform: a node change, a kernel patch, a noisy neighbour, DNS, or a certificate rotation, visible in the node's metrics rather than the pod's.

And I ask whether "slow" is real by checking the client-side metric, since a slow CDN or a browser-side regression looks like a slow API from the product's chair.

"How do you decide whether to roll back a deploy at minute five, before you have a cause?"

On correlation and cost, not on certainty.

If a deploy landed within a few minutes of the latency step, and rolling back is cheap and safe, which it is for a stateless service with backward-compatible schema changes, I roll back immediately and investigate afterward, because the expected value is high: most incidents are changes, and a rollback costs minutes while an investigation costs an hour of user pain.

If the deploy included a schema migration or a data backfill, rollback may not be safe, and I instead look for a feature flag to disable the new path.

The rule I state: mitigate first, diagnose second, and never let the desire to understand the cause delay a cheap reversal. The postmortem is where understanding lives.

"What would the RED and USE numbers look like for the most common answer, a saturated database pool?"

RED at the endpoint: rate unchanged or slightly down, errors near zero at first and then rising as connection timeouts fire, duration p99 up sharply with p50 also up, because everyone waits for a connection, not just the tail.

USE at the pool: utilisation at maximum, saturation visible as a pending count above zero and an acquire-time histogram shifting from microseconds to seconds, errors as the timeout count.

Downstream, the database's active sessions equal the fleet's pool total and its CPU may be high or, if the cause is a slow query, moderate with a few long-running statements.

That combination, everything slow rather than one endpoint slow, pending connections, and a full pool, is recognisable within a minute of looking, which is why the pool graphs are on the first dashboard page rather than a drill-down.

Drill · Method & prevention

Whether your debugging is a repeatable system — percentiles, correlation, instrumentation, and timeouts — rather than a collection of war stories.

Q254. "Why do averages hide incidents? Give me a worked number, not a slogan."

Reveal answer

Strong answer Take a service doing 600 requests per minute, where 594 finish in 30ms and 6 hang for 5 seconds. The average is (594 × 30 + 6 × 5000) / 600 ≈ 80ms — a number nobody would page on.

Yet six users every minute, over eight thousand a day, are waiting five full seconds, and the p99 says so plainly: it sits at 5 seconds. The mean buries a small population of disasters under a large population of successes; percentiles refuse to.

It compounds: a single user session making 30 API calls has a 1 − 0.99³⁰ ≈ 26% chance of hitting the slow 1% at least once — so "one percent of requests" quietly becomes "a quarter of sessions".

That is why alerting, dashboards, and service-level objectives are all defined on percentiles, and the average is at best a sanity check.

Land it The average answers "how is the typical request", incidents live in "how is the worst 1%" — measure the question you actually care about.

Likely follow-ups
"Why can't you average percentiles across pods, and what do you do instead?"

Because a percentile is a position in a sorted list, and the position in the merged list cannot be computed from positions in the parts.

If pod A's p99 is 100 milliseconds over 10,000 requests and pod B's is 5 seconds over 100 requests, the average of the two p99s is 2.5 seconds, but the true fleet p99 is close to 100 milliseconds because pod B contributes only 1% of requests.

Instead I aggregate the histograms: each pod exports bucket counts, Prometheus sums the buckets across pods, and histogram_quantile computes the fleet percentile from the merged distribution. That is why Micrometer's percentiles-histogram setting matters and the client-side precomputed percentiles do not aggregate.

The same rule applies over time: the p99 of five one-minute windows is not the p99 of the five minutes.

"What percentile should the service-level objective use, and why not p100?"

Usually p99 or p99.9 for a user-facing API, chosen by how many users the tail touches, which the session arithmetic answers: at 30 calls per session, p99 covers only about three quarters of sessions, so a product with long sessions needs p99.9. p100, the maximum, is not a useful target because a single request that hit a GC pause, a retry, or a network blip defines it, and it cannot be engineered to zero without infinite cost; alerting on it produces pages for noise. The service-level objective is stated as "99% of requests under 300 milliseconds over a 30-day window", which is a percentile threshold plus a compliance fraction, and it comes with an error budget: the 1% that may be slow, which is what the team spends on deploys and experiments.

"How much do histogram buckets cost, and how do you keep the cardinality sane?"

Each histogram is a set of counters, one per bucket, and Micrometer's default percentile histogram creates several dozen buckets per timer.

Multiply by the number of label combinations, endpoint times method times status, and a service with 50 endpoints has a few thousand series, which is fine.

The trouble starts with an unbounded label such as a user ID or a raw path with an ID in it, which multiplies the buckets by millions and takes down the metrics backend.

So I enforce that path templates, not raw paths, are the label, which Spring's instrumentation does by default, and I limit the bucket set with serviceLevelObjectives to the few boundaries I alert on when I want it lean.

The rule is that labels are bounded sets known at build time, never values from the request.

Q255 · Scenario. "Latency spiked for 90 seconds at 14:32 yesterday and self-recovered. Management wants a cause, not a shrug. How do you reconstruct it after the fact?"

Reveal answer

Strong answer By triangulation: three independent recorders, joined on the timestamp, each covering the others' blind spots.

  1. The APM trace — application performance monitoring, the request-level tracing system — shows where inside the request the time went during the window: a specific database span, a downstream call, or, most tellingly, an unexplained gap where the thread simply was not running.
  2. The GC log answers whether the JVM itself paused: if it shows a 1.4-second collection at 14:32:41, that unexplained gap in the traces is solved, and the follow-up is a memory question. Kept on always via -Xlog:gc*:file=..., it costs effectively nothing.
  3. The JVM's activity record for the window — an always-on Flight Recorder ring buffer, or thread dumps if someone captured them live — shows what the threads were doing: piled on one monitor, stuck in socket reads to one host, or busy in one hot method.

The join only works with discipline that must exist before the incident: every log and recorder on the same clock in UTC, GC logging always on, Flight Recorder always on with a few hours of retention, and traces sampled continuously. Then the story assembles itself: traces localize the layer, the GC log convicts or acquits the JVM, and the thread evidence names the code. If instead only one recorder exists, every 90-second mystery ends in a shrug — which is itself the finding I would bring to management, with the fix being the missing recorders.

Land it One data source gives a guess, three sources joined on a timestamp give a cause — and all three must be recording before anything breaks.

Likely follow-ups
"You only have the APM traces and they show a gap in the middle of every slow request. What is your shortlist?"

A gap is time when the request thread did nothing that instrumentation saw, so the shortlist is things that stop or park a thread without a span.

A JVM pause, GC or safepoint, which affects all requests on that pod at the same wall-clock instant; the tell is that the gaps on different traces on the same pod start at the same timestamp.

A pool wait, thread or connection, which the instrumentation does not span by default; the tell is that the gap sits just before a database or client span. A lock wait, which sits just before the code that needs the lock.

CPU throttling from a container quota, which stalls everything in the pod in 100 millisecond quanta. I can separate these by whether the gaps align across requests, which points at pod-wide pauses, or occur at the same span boundary, which points at a resource wait.

"How do you keep 90 seconds of evidence from a self-recovering incident if JFR was not on?"

For that incident, honestly, I cannot; whatever the metrics and logs captured is what I have, and I say so.

The step I take is to make sure the next one is captured: a rolling JFR buffer enabled by flag in the next deploy, GC logging to a file with rotation, and a lightweight automated reaction so that when the p99 alert fires, a script on the pod takes three thread dumps and dumps the JFR buffer to a persistent volume before anyone is awake.

That automation is the difference between a reconstructable incident and a shrug, and it costs a small sidecar or a hook in the alerting pipeline.

For the current case I can still often find the cause by looking at what else happened at 14:32 in the cluster, since a 90-second event that self-recovers is very often a neighbour: a node-level event, a deploy elsewhere, or a dependency's own blip.

"Management wants a cause today. How do you present a probable cause honestly?"

I separate what is established from what is inferred, with the evidence for each. Established: the window was 14:32:10 to 14:33:40, it affected all pods, p99 went to 4 seconds, error rate stayed at zero, and the database's active sessions doubled at the same time.

Inferred: the trigger was a downstream slowdown, because the traces show the gap in the same client span and that service's own latency graph shows a spike at 14:32.

I state the confidence, high or medium, and what would raise it, for example the downstream team confirming an event on their side.

Then the actions: timeouts and a bulkhead on that client so the next one costs 200 milliseconds instead of 4 seconds, and the recorders that were missing.

A probable cause with named evidence and a hardening plan is a real answer; a confident guess with no evidence is the shrug in disguise.

Q256. "What do you instrument on every thread pool and every downstream dependency, before anyone asks?"

Reveal answer

Strong answer For every pool — thread pools, database connection pools, HTTP client pools — I want four numbers:

  • Active versus maximum, so I can see saturation approaching.
  • Queued or pending waiters. A persistently non-zero queue is the earliest possible warning that the pool is undersized.
  • Time-to-acquire, as a histogram. Borrow latency is invisible in request latency until it is enormous.
  • Task or hold duration, which explains why a pool saturates.

For every downstream dependency I want four more: a latency histogram — never just an average, for the reasons percentiles exist — error counts split by type, timeout count as its own series, and retry count so amplification is visible.

The reasoning behind all of it is that saturation precedes failure by days or weeks. Pending waiters and creeping borrow times appear long before the first user-visible error.

And with Micrometer exposing Hikari, Tomcat and executor metrics almost for free, not having these is a choice rather than a cost.

Land it Instrument saturation, not just failure — a queue that is never empty is an outage with weeks of advance notice.

Likely follow-ups
"Which of those become meaningless with virtual threads, and what replaces them?"

Thread pool active-versus-max and queue depth stop meaning much, because there is no pool and no queue; a virtual thread per task is created immediately.

What replaces them is in-flight work count, a gauge of live virtual threads or of requests currently executing, and the resource waits that the thread cap used to hide: connection pool pending count and acquire time, bulkhead and semaphore wait time, and rejected-request counts from any concurrency limiter at the door.

The carrier pool has a small set of useful numbers too: the JFR pinned events and the scheduler's parallelism. And the downstream metrics stay exactly the same, since latency histograms, error types, timeout counts and retry counts describe the dependency, not the threading model.

In short, I move the saturation metrics from the thread layer to the resource layer.

"Isn't a Micrometer histogram per pool and per dependency expensive? What does it actually cost?"

A timer with a percentile histogram costs a few dozen long counters in memory, so tens of kilobytes per label combination, and recording a value is a few nanoseconds to find the bucket and increment it atomically.

For a service with ten pools and twenty dependencies, that is a few hundred series and negligible CPU. The cost that bites is scrape size and backend storage, which grow with series count, and that only becomes a problem with an unbounded label.

So the answer is that the histograms are close to free and the discipline is in the labels.

The one place I am careful is a per-query timer keyed by SQL text, which can explode if statements embed values; I key by a statement name or a hash of the normalised text instead.

"How do you instrument a pool that does not expose metrics, such as a third-party client's internal pool?"

I wrap the borrow. If the client offers hooks, such as Apache HttpClient's PoolingHttpClientConnectionManager.getTotalStats(), I poll that into gauges every few seconds.

If it does not, I time the call boundary myself with a timer around the client's invoke, and I derive saturation from the outside: concurrency in flight, measured with a counter incremented on entry and decremented on exit, compared against the configured maximum, tells me utilisation; the time between my call and the first byte, if the client exposes it, separates queueing from network.

As a last resort, JFR's jdk.ThreadPark events with the stack inside the client's pool class count how often and how long callers park waiting for a connection, which is exactly the acquire-wait metric, obtained without touching the library.

Q257. "State your timeout discipline for a service that calls other services. Where did the industry's worst default come from?"

Reveal answer

Strong answer The rule: every remote call has an explicit connect timeout and an explicit read timeout, each with a justified value — typically a little above the dependency's observed p99 — and no call ever inherits a default.

The villain that made this rule necessary is HttpURLConnection, whose default for both timeouts is zero, meaning wait forever; early RestTemplate setups built on it inherited that, and countless outages have the same anatomy: a dependency hangs, and every calling thread waits on it indefinitely until the pool is gone — the exact fire from the all-threads-in-socketRead dump.

Two refinements complete the discipline. First, budgets must shrink down the call chain — if the edge gives up at 2 seconds, an inner service waiting 5 is doing work whose answer no one will read.

Second, a timeout is only half a decision: expiry needs a plan — fail, serve a fallback, or retry within a retry budget — otherwise the timeout just chooses where the error surfaces.

Land it A missing timeout converts someone else's incident into your outage — every remote call gets a bounded wait and a decision about what happens when it expires.

Likely follow-ups
"Which modern Java clients still default to no timeout, and which have sane defaults?"

As of Aug 2026: the JDK's HttpURLConnection still defaults both connect and read timeouts to zero, meaning infinite. The JDK HttpClient has no default connect timeout and no default request timeout unless timeout(Duration) is set on the request, so it also waits indefinitely.

Apache HttpClient 5 defaults to no response timeout but has a three-minute connection request default. Spring's RestClient and RestTemplate inherit whichever factory they use, so a plain RestClient.create() on the JDK client has no read timeout.

OkHttp is the exception with sensible ten-second defaults for connect, read and write.

Because the defaults are inconsistent, I never rely on them: every client is built through one factory in the codebase that sets all timeouts explicitly, and a test asserts that factory is the only construction site.

"How do you propagate a shrinking deadline down the call chain in practice?"

With a deadline, not a timeout. The edge computes an absolute deadline, now plus the budget, and passes it in a header such as X-Request-Deadline or gRPC's built-in grpc-timeout, which does this natively.

Each service reads the header, subtracts its own expected work, and sets the timeout on its outbound calls to the remaining time, capped by the call's own maximum; if the remaining time is already below the call's minimum useful time, it fails fast without calling.

Inside a service the remaining budget is carried in a ScopedValue or request context. gRPC clients and servers propagate deadlines automatically through the context, which is one of its genuine advantages.

For HTTP, Spring does not do it out of the box, so a filter reads the header and a client interceptor applies it; it is about fifty lines.

"What is the failure mode when a timeout is too short, and how do you tune it?"

Two failures. First, wasted work: the downstream finishes the request after I gave up, so it spent its capacity for nothing, and if I retry, it does the work twice.

Second, false errors during a healthy tail: a timeout at the p99 makes 1% of requests fail by definition.

Tuning: I take the dependency's latency histogram over a representative period, set the timeout above its p99.9, and confirm that the resulting timeout rate is well under the error budget, say a tenth of a percent.

Then I watch the timeout count as a metric and treat a rising trend as a signal that the dependency is drifting, which is a conversation with its owners rather than a bigger timeout.

Hedged requests, sending a second attempt at the p95 and taking whichever answers first, are the tool for tails when the operation is idempotent and the downstream has capacity.

Q258 · Scenario. "A Kafka consumer processed nothing for 40 minutes. The pod's liveness probe was green the entire time. How does a health check lie, and how do you build one that doesn't?"

Reveal answer

Strong answer The probe was answering a different question than the one that mattered. A typical liveness endpoint is served by the web server's thread pool and checks that the process is up, maybe pinging a database. The consumer, though, runs on its own thread — and that thread was stuck, deadlocked or wedged in a rebalance, while the web threads cheerfully returned 200. The process was alive; the work was dead, and liveness only measured the former.

  1. Make health mean progress: the consumer loop updates a heartbeat timestamp every cycle, and the health endpoint fails when now minus heartbeat exceeds a threshold — now the probe measures the actual job, not the web server's pulse.
  2. Add a watchdog thread that calls ThreadMXBean.findDeadlockedThreads() — the JVM's built-in deadlock detector, available programmatically — and trips the same failure on a hit.
  3. Preserve the evidence before the restart: a liveness failure kills the pod, and the kill destroys the stuck state, which is why this bug went unexplained for months. The watchdog should capture a thread dump to persistent storage — or trigger a Flight Recorder dump — first, then let the restart proceed.
  4. Alert on the work metric independently: consumer lag climbing while liveness is green is exactly the contradiction that should page someone.

The principle: a health check must exercise the path whose failure you fear. Anything less is a green light wired to the wrong circuit.

Land it Liveness says the process exists; only a progress heartbeat says the work is happening — and always dump before you restart, or the bug stays a mystery.

Likely follow-ups
"Liveness versus readiness versus startup probes: which one should a stuck consumer fail?"

Liveness, because the fix for a wedged consumer thread is a restart, which is what a liveness failure triggers.

Readiness controls whether a pod receives traffic from a Service, so it is the right probe for "I cannot serve right now but will recover", such as a dependency being down or a cache warming; failing readiness for a stuck consumer would just remove the pod from HTTP routing while the consumer stays stuck.

Startup probes cover the slow boot so the liveness probe does not kill a pod that is still initialising.

The trap is the reverse: a liveness probe that checks the database, so a database outage restarts every pod in a loop and turns one incident into two.

Liveness checks the process's own health and progress; readiness checks whether it can serve; dependencies belong in readiness at most.

"How does the heartbeat handle a consumer that is legitimately idle because there are no messages?"

By heartbeating on the loop, not on the message. The consumer's poll call returns every few hundred milliseconds even when the topic is empty, so the heartbeat is updated after each poll returns regardless of whether records came back.

Silence then means the loop is not turning, which is the failure I care about, not that the topic is quiet.

The threshold is a multiple of the poll interval plus the maximum processing time for a batch, so a slow batch does not trip it; for a five-second max.poll.interval.ms and one-second processing, thirty seconds is reasonable.

Kafka has its own version of this on the broker side: a consumer that stops calling poll within max.poll.interval.ms is kicked out of the group, and that rebalance shows in the broker's metrics, which is a second signal to alert on.

"What would make the watchdog itself get stuck, and how do you guard against that?"

Anything the watchdog shares with the thing it watches.

If the health endpoint runs on the same executor as the consumer, or takes a lock the consumer holds, or the heartbeat read blocks on a synchronized map the consumer is updating, the probe hangs with the consumer and Kubernetes sees a probe timeout, which does count as a failure, so that at least still restarts.

Worse is a watchdog that swallows exceptions and reports healthy on any error.

So the watchdog thread is its own dedicated thread with a name, it reads a volatile long timestamp with no lock, it never calls into application code, and its dump capture runs with a timeout so a slow disk cannot wedge it.

And I test it: a chaos test that parks the consumer thread in a debugger-like sleep and asserts the probe goes red within the threshold.

"The consumer was stuck in a rebalance for 40 minutes, not deadlocked. What went wrong there?"

A rebalance stalls the whole group until every member rejoins, so one member that never finishes its onPartitionsRevoked callback, for example one committing offsets against a slow database or waiting on a lock, keeps everyone waiting; or a member that has stopped polling but has not left holds its assignment until session.timeout.ms expires, and if that was set to a large value the group waits that long.

Forty minutes usually means a rejoin loop: a member joins, times out, is removed, rejoins, and the group never stabilises. The broker's consumer group state shows PreparingRebalance for the duration.

Fixes: keep the revoke callback fast and bounded, use the cooperative sticky assignor so a rebalance does not stop all partitions, and alert on time spent in rebalance, which the client exposes as rebalance-latency-max.

Q259. "The incident is over. What does a good postmortem look like, and why must it be blameless?"

Reveal answer

Strong answer A good postmortem has four parts: a timeline built from evidence — graphs, dumps, deploy records — with every claim anchored to a timestamp; contributing causes rather than a single root cause, because real incidents are a chain (the missing timeout and the undersized pool and the alert that did not exist); action items that each have an owner and a date, reviewed later for completion, because an action item without an owner is a wish; and wide sharing, so the next team inherits the lesson instead of the incident.

Blameless is not politeness — it is data quality.

The person who fat-fingered the config holds the most valuable information in the room, and they only surrender it fully in a process that punishes systems, not people; the moment postmortems assign blame, the next one is written defensively and the organization starts learning fiction.

The test I apply to a finished postmortem: had this document existed a month earlier, would the incident have happened?

Land it Blameless is an accuracy requirement, not a kindness — you are buying the truth from the people who have it.

Likely follow-ups
"How do you write the timeline when the clocks on different systems disagreed?"

I pick one clock as the reference, usually the metrics system's, and I state the measured offset of every other source next to its entries.

The offsets come from a shared event visible in two sources, such as the deploy marker that appears both in the CI log and in the metrics annotations, or a request whose log line and trace span both carry a timestamp.

A 40-second skew between a pod's log and the tracing backend is common when a node's NTP has drifted, and if it is not corrected the timeline claims effects before causes.

After the postmortem, the action item is making the skew impossible: NTP or chrony health as a monitored metric on every node, and UTC in every log format. A timeline with an unexplained ordering is worse than no timeline, because people reason from it.

"How do you keep action items from quietly dying after the postmortem?"

By treating them as work, not as notes. Each action item becomes a ticket in the team's normal tracker with an owner and a due date, linked from the postmortem document, and the postmortem is not marked complete until those tickets are.

A monthly review lists open postmortem tickets older than their due date, which is the mechanism that gives them priority against feature work; without that review they lose every time.

I also separate the items by kind: the immediate fix, which usually shipped during the incident; the preventive change, which is the real value; and the detection improvement, the alert or recorder that would have shortened the incident, which is the one most often skipped and most often decisive next time.

If an item is not worth doing, the document should say so and why, rather than leaving it to rot.

"What does 'contributing causes, not root cause' change about the action items?"

It multiplies them and makes them cheaper. A single root cause invites a single fix, usually at the point where the failure became visible, and the next incident routes around it.

Listing the chain, the missing timeout, the undersized pool, the alert that did not exist, the runbook that was out of date, gives four places to cut it, and cutting any two makes the same incident impossible even if the third is imperfect.

It also removes the argument about which cause is the "real" one, which is where blame creeps back in. The exercise I use is to ask, for each contributing cause, "if only this had been different, would the incident have happened?

" and if the answer is no for several, each is a legitimate action item, ranked by cost and by how many other incident types it also prevents.

Q260. "Can load testing find your concurrency bugs? Be honest about what each testing tool actually catches."

Reveal answer

Strong answer Honestly: mostly no, and pretending otherwise is how races reach production with a green pipeline. Three tools, three distinct bug classes.

Load tests find capacity bugs — pool exhaustion, queue growth, timeout behavior at saturation, the lock convoy that only forms above a request rate — because those are statistical and reproduce under any sufficient load.

They rarely find true data races, because a race needs a precise interleaving and your load generator's timing is nothing like production's.

For races, the honest tool is jcstress — OpenJDK's concurrency-stress harness, which takes a few lines of shared-state code and hammers them across cores millions of times, actively hunting the reorderings the memory model permits; it finds in seconds what load tests miss for years, but only for small, extracted units.

Third, fault injection — adding latency or death to a dependency with a tool like Toxiproxy — is the only way to prove the timeouts, retries, and circuit breakers actually engage, rather than existing solely in configuration.

A senior runs all three and claims for each only what it can deliver.

Land it Load tests prove capacity, jcstress proves memory-model correctness in the small, fault injection proves your defenses fire — "we load-tested it" was never a race-freedom claim.

Likely follow-ups
"How do you set up a fault-injection test that proves the circuit breaker actually opens?"

With Toxiproxy between the service and its dependency, driven from the test.

The test starts the service pointed at the proxy, warms it with normal traffic to confirm the breaker is closed, then adds a latency toxic of five seconds, or a timeout toxic that hangs connections, and keeps sending requests at the normal rate.

The assertions are on observable behaviour: within the breaker's window the Resilience4j state metric reports open, the endpoint's p99 drops back to a few milliseconds because calls are failing fast, the fallback response is returned, and the Tomcat busy-thread count stays low.

Then the test removes the toxic and asserts the breaker goes half-open and then closed within the configured wait.

Without this test, a breaker with a misconfigured sliding window can sit closed through an entire outage, and nobody knows until the dump shows every thread in a socket read.

"What does a load test need to look like to find a lock convoy rather than miss it?"

It needs the right concurrency and the right request mix.

A convoy forms only when enough threads contend on the same monitor at once, so the test must drive at least as many concurrent requests as production's peak, not a fraction of it scaled by a wish; a test at 20% of production concurrency will never form the convoy that appears at 100%.

It must hit the code path that takes the lock, which means the mix must include the rare endpoints, not just the top three.

And it must run long enough for the slow event that lengthens the hold time, such as a cache rebuild, to occur, or trigger it deliberately.

The signal to watch is not throughput but the dump: a thread-dump capture at peak in the test, grouped by blocked monitor, is the assertion, with a threshold like "no monitor with more than five waiters".

"Are there Java-specific tools that shake out concurrency bugs at the integration level, beyond jcstress?"

A few, with honest limits. The Lincheck library from JetBrains tests concurrent data structures for linearizability by generating operation sequences and checking that every observed outcome matches some sequential ordering; it is stronger than jcstress for collection-like classes and weaker for memory-model corner cases.

For Spring-level tests, running the integration suite with a small deliberately hostile configuration finds pool and lock bugs: a connection pool of one, a thread pool of two, and Testcontainers with a latency-injecting proxy.

Chaos tooling such as Chaos Monkey for Spring Boot injects latency and exceptions into beans at runtime. What none of these replace is the design review that asks, for every shared mutable object, who writes it and under what lock.

09 · TuningPerformance, API & Database Tuning — Q261–Q300

This section drills the tuning questions a senior backend engineer actually gets: not "name three GC algorithms" but "your endpoint fires two hundred queries — prove it, rank the fixes, and defend the trade-off". The recurring theme is discipline: measure before touching, know what each layer of the stack costs in milliseconds, and be honest about what every optimization gives up. Deep database internals and JVM internals live in their own drills — here you own everything between the HTTP socket and the JDBC driver.

Drill · Measure first — method & capacity

These questions test whether you diagnose with numbers and a method, or start guessing at code — the single fastest way interviewers separate seniors from juniors.

Q261 · Scenario. "Users are complaining the service is slow. You have full access to dashboards, logs, and the code. What is the very first thing you do?"

Reveal answer

The real test Whether your instinct is to measure and localize, or to open the code and start optimizing on a hunch.

Strong answer The first thing I do is refuse to touch code. "Slow" is not a diagnosis, so I turn it into numbers and a location.

  1. Quantify it. Which endpoints, how slow, and at which percentile — the p95 is the time that the slowest 5% of requests exceed, and complaints usually live in the p95/p99 while the average looks fine. I pull the latency histograms per endpoint, not the mean.
  2. Establish when it started and correlate with change events: a deploy, a config change, a traffic increase, a data-volume milestone. A sudden step on the graph at 14:02 next to a 14:00 deploy answers half the question.
  3. Localize the time. I open a few slow distributed traces — the per-request records that show every hop and query with its timing — from the APM tool (application performance monitoring, e.g., Datadog or an OpenTelemetry backend) and see which span holds the time: our CPU, a database query, a downstream call, or waiting for a pooled resource.
  4. Check saturation signals: connection-pool wait time, thread-pool queue depth, database load. Slowness under load is usually queueing, not slow code.
  5. Only now form a hypothesis, fix the single largest measured contributor, and verify with the same percentile graphs I started from.

Land it Optimizing before measuring is how you spend a week making a cold path 2× faster while the real bottleneck ships untouched — I always buy the diagnosis first.

Likely follow-ups
"The traces show the time is inside your own service, not a database or a downstream. Now what?"

Then it is either CPU or a wait that tracing does not span. I split those with two numbers: the pod's CPU usage against its limit, and the thread state at the time.

If CPU is high, I take a thirty-second async-profiler flame graph in CPU mode on one slow pod and look for the wide plateau; serialisation, regex, string building and collection sorting are the usual answers.

If CPU is low, the thread is waiting on something uninstrumented, so I take wall-clock samples or three thread dumps and look for request threads parked in a lock, a pool acquire, or a future.

The gap's position in the trace narrows it: a gap right before the database span is the connection pool, a gap at the very start is the request queue in Tomcat, and a gap at the end is response writing to a slow client.

"How do you avoid fixing the wrong thing when several things look slow at once?"

By ranking by contribution to the target, not by how bad each looks.

I compute, for each candidate, how much of the p99 it accounts for: a database query at 30 milliseconds on every request contributes more than a downstream at 500 milliseconds called on 2% of requests, when measured at the percentile I care about.

Then I fix the largest single contributor, deploy it alone, and re-measure with the same graphs before touching the next. Changing two things at once means I cannot attribute the improvement, and it hides the case where the second change made things worse.

It is slower per change and faster overall, because I stop after the target is met instead of optimising everything in sight. The interview point is that a measurement gives me an ordered list, and the discipline is walking the list one item at a time.

"What would you refuse to do in this first pass, even if asked?"

Three things. I would not raise pool sizes, thread counts, or heap as a first move, because without the measurement those changes are as likely to worsen the queueing as to relieve it, and a bigger database pool on a saturated database makes everything slower.

I would not restart pods to "see if it helps", because a restart destroys the evidence and if it does help, it tells me only that something accumulates, not what.

And I would not start a code optimisation on a hunch, however plausible; a week making a serialiser faster is wasted when the trace would have shown the time in a missing index.

The exception is a cheap, reversible mitigation with a clear correlation, such as rolling back a deploy that landed at the moment the graph stepped; that is a measurement-driven action, not a guess.

"Give me the concrete queries or views you open, in order, for a Spring Boot service."

First, the latency histogram per endpoint: histogram_quantile(0.99, sum by (le, uri) (rate(http_server_requests_seconds_bucket[5m]))), which shows which endpoint moved and when. Second, the same graph with deploy annotations overlaid. Third, the pool signals: hikaricp_connections_pending and hikaricp_connections_acquire_seconds, plus tomcat_threads_busy_threads against tomcat_threads_config_max_threads.

Fourth, the JVM: jvm_gc_pause_seconds rate and heap after GC. Fifth, the trace search filtered to the slow endpoint sorted by duration, opening three traces from the tail. Sixth, the downstream client timers, http_client_requests_seconds by clientName.

That is under ten minutes, and at the end I know the endpoint, the start time, and whether the time is in the database, a dependency, the JVM, or my code.

Q262. "Your API has a 200 millisecond latency target. Walk me through how you would budget that across the request path."

Reveal answer

The real test Whether you think of latency as a budget that hops spend, with numbers, or as a single mysterious total.

Strong answer I split the 200 ms across every hop and make each owner accountable for their slice.

A realistic split: client network round trip 40 ms, gateway and TLS on a reused connection 5 ms, authentication check 10 ms, our own compute 15 ms, two database queries at 10 ms each for 20 ms, one downstream service call 60 ms, response serialization 5 ms.

That totals 155 ms, leaving roughly 45 ms of headroom — which I need, because budgets must hold at the p95, not the average, and tail latencies stack up worse than means do.

The budget's real value is that it forces decisions: if the downstream call actually costs 120 ms, the arithmetic says I must cache it, call it in parallel with something else, or renegotiate the 200 ms — I cannot wish it away.

Land it A latency budget turns "the service is slow" into "the downstream hop is 40 ms over its allowance", which is a conversation you can actually act on.

Likely follow-ups
"Why do tail latencies stack worse than averages, and what does that do to the budget?"

Because the p99 of a sum is not the sum of the p99s in the friendly direction.

If each of five sequential hops has a 1% chance of being slow, the chance that a request hits at least one slow hop is about 5%, so the composed p99 is worse than any single hop's p99, and the composed p95 already includes a slow hop.

Averages add exactly; tails compound. For the budget that means I cannot allocate 200 milliseconds by summing each hop's p99 and calling it done; the request's p99 will exceed it.

So I budget each hop at a higher percentile than the target, p99.9 for five hops to get roughly a p99 overall, or I reduce the number of sequential hops, which is the strongest lever: fewer hops, less compounding.

Parallel hops help because their latencies take the max rather than the sum.

"The downstream call is 120 ms and cannot be cached. What are your options within 200?"

Four, in order of preference.

Overlap it: start the downstream call first and do the authentication check, the database queries and any other independent work while it is in flight, so the 120 milliseconds runs in parallel with the other 55 rather than after them, which brings the total to about 130 plus the serial parts.

Trim the call: ask for fewer fields or a smaller page, since payload size often dominates downstream time. Hedge it: for idempotent calls, send a second request at the p95 mark and take the first response, which cuts the tail at the cost of extra load.

Or renegotiate: return the core response in 200 milliseconds and deliver the downstream's contribution asynchronously, via a second call or a placeholder, which is a product decision, and I raise it as one rather than quietly missing the target.

"How do you make each team accountable for its slice in practice?"

By turning the slice into a service-level objective on their own service with a matching alert, so the budget is not a document but a monitored number.

If the downstream's slice is 60 milliseconds at p99, their dashboard shows their p99 against 60 and they get paged when it drifts, before my composite target fails.

On my side, the client timer for that dependency has an alert at the same boundary, so both teams see the same breach at the same time.

The budget document lists each slice, its owner, and the metric that measures it, and it is reviewed when either service changes shape.

That is what stops the budget from being a launch-time estimate that nobody re-reads: the slices are live alerts, and a breach is a conversation with a number attached rather than a complaint.

Q263. "When would you reach for JMH versus a load test — and how can a method that benchmarks fast still leave you with a slow service?"

Reveal answer

Strong answer JMH — the Java Microbenchmark Harness — measures one method in isolation, and it exists because naive timing loops lie: the JIT (the just-in-time compiler, which turns hot bytecode into optimized machine code at runtime) needs warmup, and it will happily delete code whose result is unused.

JMH handles warmup iterations, forked JVMs, and dead-code traps for me. I use it to choose between two implementations of the same hot function. A load test — Gatling, k6, JMeter driving realistic concurrent traffic — measures the whole service: connection pools, serialization, queueing, network.

A method can be fast and the service slow because service latency is usually dominated by waiting, not computing: waiting on I/O, on a pooled connection, on a lock, in a queue.

A perfect 2 microsecond method contributes nothing when the request spends 150 ms parked on a saturated pool.

Land it JMH answers "which implementation is faster"; only a load test answers "does the service meet its target" — and I never let the first stand in for the second.

Likely follow-ups
"What are the classic JMH mistakes that make a benchmark lie, even with the harness?"

Dead code elimination: computing a result and discarding it lets the JIT remove the work, so every result must be returned from the method or passed to a Blackhole.

Constant folding: a loop-invariant input declared as a local or a static final lets the JIT precompute the answer, so inputs live in non-final fields of a @State object. Wrong scope: sharing a state object across threads when the method is not thread-safe, or the reverse.

Measuring allocation-free code without a GC profiler and then being surprised in production, where the allocation matters; -prof gc fixes that.

Too little warmup for code that changes behaviour after inlining kicks in, or benchmarking a single call site so the JIT specialises a virtual call that is megamorphic in production. Each of these produces a confident, precise, and wrong number.

"What does a load test need to be trustworthy, since bad load tests lie too?"

An open-loop workload, realistic data, and a warm target.

Open loop means the generator sends requests at a fixed rate regardless of how fast responses come back, which is how real users behave; a closed-loop tool that waits for each response before sending the next automatically backs off when the service slows, hiding the queueing collapse that is the whole point of the test.

Realistic data means production-shaped sizes and key distributions, not one hot row that lives in every cache. A warm target means the JIT has compiled and the pools are full before measurement begins, so the first minute is discarded.

And the test must run long enough to see garbage collection cycles and cache expiry, typically twenty minutes or more. Gatling and k6 are open-loop by default when configured with arrival rates, and that setting is the one I check first.

"Give me a concrete example of a JMH win that made no difference to the service."

A team replaced a String.format call in a request path with a hand-built StringBuilder, and JMH showed the new version 15 times faster, 400 nanoseconds down to 25.

In production the endpoint's p99 did not move, because the format call ran once per request and the request took 80 milliseconds, of which 60 was a database query and 15 was waiting for a connection; 375 nanoseconds saved is 0.0005% of the request.

The profile would have shown the format call as an invisible sliver.

The reverse is also instructive: a change that JMH showed as neutral, switching a list to a pre-sized one, removed a resize that had been producing a large allocation per request, and the GC pause reduction improved the p99 by 10 milliseconds.

Microbenchmarks answer the question you asked, and the service asks a different one.

Q264. "Throughput versus latency — can you have both? Give me the honest answer."

Reveal answer

Strong answer Up to a point, and then you must choose.

They trade off through queueing: to maximize throughput you run the system near 100% utilization, but as utilization approaches saturation, the time each request waits in queue grows explosively — the latency curve looks flat and then turns into a hockey stick, often somewhere past 70–80% utilization.

So an interactive API deliberately buys latency by leaving capacity idle, running well below saturation.

In the other direction, batching — grouping many items into one database round trip or one disk write — raises throughput substantially but adds delay to each individual item while it waits for its batch. Neither choice is wrong; they serve different products.

Land it I ask what the endpoint sells — a checkout call sells latency and gets headroom, a nightly pipeline sells throughput and gets batching — and I refuse to pretend one number optimizes both.

Likely follow-ups
"Where does the 70–80% number come from, and can you show the formula?"

From queueing theory. For a single server with random arrivals and service times, the M/M/1 model, the average time in the system is the service time divided by one minus the utilisation.

At 50% utilisation a request waits on average one service time; at 80% it waits four; at 90% nine; at 95% nineteen. The curve is flat until about 70% and then rises steeply, which is the hockey stick.

Real systems with many servers, the M/M/c model, tolerate slightly higher utilisation before the knee, and bursty arrivals move it lower.

So the 70 to 80% range is where the average wait roughly doubles or triples the service time, which is the point most latency targets can no longer absorb.

I use the formula to size headroom: to keep queueing under one service time, I run at or below 50%; to keep it under four, 80% is the ceiling.

"How do you set batch size for throughput without wrecking latency?"

With two bounds, count and time, whichever comes first.

A batch flushes when it reaches N items or when the oldest item has waited T milliseconds, so under heavy load batches fill quickly and are efficient, and under light load no item waits longer than T. Kafka's producer does exactly this with batch.size and linger.ms; a database writer does it with a chunk size and a flush interval.

I choose T from the latency budget the item's caller can tolerate, often 5 to 20 milliseconds, and N from the point where the per-item cost stops dropping, which for JDBC inserts is a few hundred.

Then I measure both the throughput at peak and the p99 added latency at low load, and adjust. The mistake is a count-only batch, which at low traffic holds the last few items forever.

"Give me a case where you got both, and explain why it did not violate the trade-off."

Removing waste improves both, because the trade-off is about queueing at a given amount of work, not about the work itself.

When we fixed an N+1 query pattern, each request did 200 fewer round trips: latency fell because the request did less, and throughput rose because each request held its connection and thread for a fraction of the time, so the same pool served more requests before saturating.

Connection reuse, caching a repeated read, and streaming instead of buffering all have the same shape: less work per request moves the whole curve down and to the right. What remains true is that at the new, higher capacity, pushing utilisation toward 100% still explodes latency.

So the honest statement is that efficiency gains shift the curve, and the operating point on that curve is still a choice.

Q265. "Your service takes 500 requests per second and each request takes about 80 milliseconds. Size the thread pool and reason about scaling."

Reveal answer

The real test Whether you can do capacity math out loud instead of quoting a default.

Strong answer This is Little's law: the average number of requests in flight equals arrival rate times time in system. 500 per second × 0.08 seconds ≈ 40 concurrent requests.

In a thread-per-request model that means roughly 40 busy threads on average, so I would size the pool around 80–100 — about 2× headroom, because arrival is bursty and the p99 request holds its thread longer than 80 ms.

The connection pool — the kept-ready set of open database connections that requests borrow and return — is sized separately from concurrent database queries, not concurrent requests, since a request holds a connection for only part of its 80 ms.

On scaling: I scale out when a shared per-node resource saturates — the pool, the network interface, heap pressure — and scale up when per-node overhead or licensing makes many small nodes wasteful. Either way I re-run the same arithmetic per node.

Land it Forty concurrent requests is a small number — the win is showing the interviewer I derived it rather than guessing "200 threads" because that is Tomcat's default.

Likely follow-ups
"Traffic doubles to 1,000 per second. What actually happens to your 80–100 thread pool?"

Little's law says 80 concurrent requests on average, so a pool of 100 is now at 80% utilisation with almost no headroom for bursts.

A burst pushes it to 100 busy threads, and further requests queue in Tomcat's accept queue, adding wait time that increases the per-request time, which by the same law increases the concurrency needed; the system can spiral if the wait feeds back into timeouts and retries.

But before I double the pool, I check what those threads are waiting on: if 60 of the 80 milliseconds are a database call and the connection pool is 20 per pod, the real cap is 20 concurrent database calls, or about 330 requests per second per pod, which was already close at 500.

So doubling traffic means either more pods or a shorter per-request time, and the thread pool size is the last number I would change.

"How does the arithmetic change with virtual threads?"

The thread count disappears from the calculation and the resource limits take its place. Forty concurrent requests are forty virtual threads, and a thousand are a thousand, each costing a few kilobytes of heap; there is no pool to size.

What remains is the same Little's law applied to each bounded resource: with 60 milliseconds of database time per request, 500 requests per second need 30 connections in use on average, so a pool of 20 per pod is short and that becomes the bottleneck the thread pool was hiding.

CPU also stays: 15 milliseconds of compute per request at 500 per second is 7.5 cores, which the pod must have.

So I redo the arithmetic per resource, connection pool, downstream concurrency limit, CPU and heap, and I put an explicit concurrency limit at the door sized from the tightest of them.

"Why 2× headroom and not 1.2× or 5×?"

Because arrivals are not uniform and the p99 request is longer than the average one.

Little's law gives the mean in-flight count; with random arrivals the instantaneous count fluctuates roughly by its square root, so at a mean of 40 the count exceeds 52 regularly and 60 occasionally, and the requests that take 300 milliseconds instead of 80 hold their thread four times longer.

A 1.2× pool would queue on every normal burst.

5× would be 200 threads sitting idle, wasting stack memory and, more importantly, hiding a problem: if a dependency slows down, 200 threads all pile into it before anything fails, so the outage is bigger when it arrives.

2× is a rule of thumb that keeps queueing rare while keeping the failure bounded. The better answer is to measure the busy-thread histogram under real load and set the pool at its p99.9 plus a margin.

"What number tells you that the pool is undersized, before requests start failing?"

Queue depth and queue wait time, not busy count.

A pool at maximum busy threads is only a problem if work is waiting behind it, so the earliest signal is Tomcat's connection count exceeding busy threads, or in a custom executor the ThreadPoolExecutor.getQueue().size() gauge above zero for more than a moment, together with the time a task waits between submit and start, which I measure with a timestamp captured at submit.

A queue that is non-empty for more than a few seconds at a time, at a traffic level below peak, means the pool will not survive peak.

I alert on that queue-age metric rather than on the busy count, because busy at maximum with an empty queue is simply a well-sized pool doing its job.

Q266. "What do you put on the dashboard for every endpoint and every pool — the minimum set you refuse to run without?"

Reveal answer

Strong answer Per endpoint, three signals: rate (requests per second), errors (as a rate, split by status class), and duration — and duration must be a histogram, because an average of a fast path and a stuck path is a number nobody experiences.

Histograms give me real p50/p95/p99 lines; in Spring that is Micrometer's http_server_requests with percentile histograms enabled. Per pool — thread pools and connection pools alike — I want active count, queued or pending count, and wait time to acquire.

The pending and wait-time series matter most: hikaricp_connections_pending climbing while active sits at max is the early warning that arrives minutes before timeouts do. I also want deploy markers on the same graphs, because "what changed" is the first diagnostic question.

Land it Rate, errors, duration histograms per endpoint, plus acquire-wait per pool — everything else is nice to have, but without these five I am debugging blind.

Likely follow-ups
"How do you enable those histograms in Spring Boot, and what does it cost the scrape?"

management.metrics.distribution.percentiles-histogram.http.server.requests=true turns on the bucketed histogram for the server timer, and the same property with http.client.requests covers outbound calls; for Hikari and Tomcat, the gauges are exported automatically once Actuator and the Prometheus registry are on the classpath.

The histogram adds around 60 to 70 buckets per timer series, so a service with 40 endpoints, a few methods and a handful of status codes produces a few thousand extra series, and the scrape payload grows from tens of kilobytes to a few hundred.

That is fine for any modern backend. To keep it lean I use management.metrics.distribution.slo.http.server.requests=50ms,100ms,200ms,500ms,1s,2s, which adds only the boundaries I alert on, and I keep the URI label on templates, never raw paths.

"What do you add for a Kafka consumer or a scheduled job, where RED does not fit?"

For a consumer: consumer lag per partition, which is the queue depth of the system; records processed per second and per-record processing time as a histogram, which together predict whether lag will grow; commit failures and rebalance count and duration; and a heartbeat age gauge for the liveness question.

For a scheduled job: last successful run timestamp, so an alert on its age catches a job that silently stopped; run duration as a histogram against the period; and items processed per run, so a job that runs fine but does nothing is visible.

The common thread is that for asynchronous work the key signal is backlog and freshness, not request rate. The alert I never omit is "time since last success", because it fires for every failure mode including the scheduler itself dying.

"Deploy markers: how do you get them onto the graphs automatically?"

From the deployment pipeline.

The CI job that rolls out a version posts an annotation to Grafana's annotations API with the service, the version and the timestamp, or writes an event to the metrics backend; Datadog and similar tools have a deploy event API for the same purpose.

In Kubernetes, a small controller watching Deployment rollouts can post the annotation for every service without each pipeline knowing about it.

I also export the running version as a metric label on a gauge, app_info{version="1.42.0"} 1, so a query can show when each pod flipped, which handles gradual rollouts that a single marker cannot.

The purpose is to make "what changed" a glance rather than a search, and the effort is a few hours once for the whole organisation.

Q267 · Scenario. "A checkout request takes 900 ms and four services are involved. How do you find which hop is slow — walk me through actually reading the trace."

Reveal answer

Strong answer Distributed tracing gives every request a trace ID that travels in a header across services, and each unit of work records a span — a named, timed segment nested under its parent. I read the waterfall like this:

  1. Pick exemplar traces from the slow tail — actual p99 requests — not an average trace, and pull a fast trace of the same endpoint to diff against.
  2. Look for the one long span: if the payment-service span is 700 of the 900 ms, the search moves there, and its child spans say whether that is its database or its own downstream.
  3. Look for a staircase: dozens of short sequential spans, each 10 ms, is the chatty pattern — an N+1 across services or per-item remote calls — where no single hop is slow but the sum is.
  4. Look for gaps: time between a parent span ending and the child starting that no span claims. Gaps are queueing, pool-acquire waits, or missing instrumentation, and they are where "the trace doesn't add up to 900 ms" time hides.
  5. Confirm against that hop's own metrics before acting — one trace is an anecdote; the histogram says whether it is the pattern.

Tooling: OpenTelemetry for instrumentation, with Jaeger, Tempo, or a commercial APM as the backend.

Land it The waterfall answers "which hop" in one screen — long span, staircase, or gap — and each of those three shapes dictates a different fix.

Likely follow-ups
"The trace is missing spans for a hop, so the time appears as a gap in the parent. How do you fill it?"

A gap with no child span means that hop is not propagating the trace context, or is not instrumented at all.

First I check propagation: the outgoing call must carry the traceparent header from the W3C Trace Context standard, and the receiving service must read it; a client built without the instrumented factory, or a service using an older B3 header format, breaks the chain and either drops the span or starts a new trace.

Second, if the hop is a queue, the producer must inject the context into the message headers and the consumer must extract it, which Spring Kafka and OpenTelemetry's Kafka instrumentation do when enabled.

Third, for a gap inside a single service, I add manual spans around the suspect code with the OpenTelemetry API, which is a few lines. Until it is filled, I treat the gap as that hop's time and correlate by timestamp with its own metrics.

"Sampling is at 1%, so the slow trace you need was not recorded. What then?"

I switch to tail-based sampling for the investigation. Head-based sampling decides at the start of the request whether to keep the trace, so it keeps 1% of everything and misses most of the rare slow ones.

Tail-based sampling, which the OpenTelemetry Collector supports with its tail sampling processor, buffers the whole trace and decides at the end, so I can keep 100% of traces slower than a threshold or with an error, and 1% of the rest.

The cost is memory in the collector to hold traces in flight for a few seconds.

If I cannot change the collector today, I raise the head sampling rate to 100% on one pod for ten minutes, which is a runtime configuration change in most agents, and gather the slow traces from that pod.

Exemplars from the latency histogram also point at specific slow trace IDs that were sampled.

"Give me a concrete example of the staircase pattern and how you fixed it."

A checkout trace showed the order service calling the inventory service 47 times in sequence, once per line item, each call 12 milliseconds, for 560 milliseconds of the 900. No single call was slow, so latency alerts on the inventory service never fired.

The fix was a batch endpoint, POST /inventory/check with a list of SKUs, which turned 47 sequential calls into one 25 millisecond call; the trace afterward showed a single span.

The intermediate fix while the batch endpoint was built was to fan the 47 calls out in parallel on a bounded executor, which brought the segment to about 40 milliseconds but put 47 times the concurrency on inventory, so it was a stopgap with a semaphore.

The staircase is the cross-service N+1, and the fix is the same as the database one: a set-based call instead of a loop of calls.

"How do you keep the trace overhead acceptable at high request rates?"

Span creation costs a few microseconds and a small allocation, so at ten spans per request and 1,000 requests per second it is about 10,000 spans per second, well under 1% of a core. The cost that grows is export: serialising and shipping every span.

Head sampling at the SDK reduces that by the sampling rate, and batching in the exporter, which is the default BatchSpanProcessor, amortises the network.

The remaining trap is attribute cardinality and size: putting a full SQL statement or a request body on every span multiplies the bytes, so I attribute a statement name and a size, not the payload.

I measure the agent's overhead the same way as everything else, by comparing CPU per request with the agent on and off in a load test, and I expect a low single-digit percentage.

Q268. "Your Java service serves its first two minutes of traffic badly after every deploy. Why, and what do you do about it?"

Reveal answer

Strong answer A freshly started JVM is slow for structural reasons: the JIT has not yet compiled the hot paths, so code runs interpreted or lightly optimized; connection pools are empty and every early request pays connection setup; caches are cold.

Mitigations, in the order I apply them: ramp traffic gradually instead of cutting over — slow-start weighting in the load balancer, or Kubernetes readiness gates plus a warmup phase that replays representative requests through the real code paths before the instance joins rotation; pre-warm pools with a minimum idle connection count; use class data sharing (CDS/AppCDS) to cut class-loading time.

The honest word on GraalVM native image: it compiles ahead of time, so startup drops to tens of milliseconds and memory shrinks — ideal for scale-to-zero and serverless — but you trade away the JIT's profile-guided peak throughput and take on build-time configuration for reflection.

For a long-running, throughput-heavy service I usually keep the JIT and invest in the ramp.

Land it Warmup is a traffic-management problem before it is a compiler problem — ramp the instance, and only reach for native image when startup time is the product requirement.

Likely follow-ups
"What does the JDK itself offer for warmup now, as of JDK 25?"

The ahead-of-time cache from Project Leyden.

JEP 483 in JDK 24 introduced -XX:AOTCache: a training run with -XX:AOTMode=record and then -XX:AOTMode=create produces a cache of loaded and linked classes, which cuts class loading time on later starts, and JDK 25 extended it with JEP 514, a single-step -XX:AOTCacheOutput workflow, and JEP 515, which stores method profiles in the cache so the JIT starts with warm profiling data instead of collecting it from scratch.

As of Aug 2026 that gives a noticeably shorter ramp for a typical Spring service, though the compiled code itself is not yet cached in a released JDK. It replaces the older AppCDS flags, which still work.

The practical constraint is that the training run must be representative, so I generate the cache in CI with a replay of real traffic against the built image.

"How do you build a warmup that exercises the real code paths without real side effects?"

With recorded traffic and a safe mode.

I capture a sample of production requests, a few thousand covering every endpoint by weight, with any mutation requests pointed at a dedicated tenant or a dry-run flag so the code runs but the write is rolled back or targets a scratch account.

At startup, before readiness, the service replays those requests against itself over the loopback interface, which drives the same controllers, serialisers, database queries and client calls through the JIT. The replay runs for about a minute or until the compilation queue drains, which I can observe via -XX:+PrintCompilation in staging or the jdk.Compilation JFR event rate.

It is more work than traffic ramping, so I do it only where the ramp is not available, such as a queue consumer that receives full load the moment it joins the group.

"CRaC — checkpoint and restore — how does it fit, and would you use it?"

CRaC snapshots a warmed JVM process to disk and restores it in milliseconds, so the restored process already has compiled code, filled pools and populated caches; it is built on Linux CRIU. Spring Boot supports it since 3.2 through lifecycle hooks that close sockets and connections before the checkpoint and reopen them after restore.

The gains are dramatic for startup, tens of milliseconds to a warm state.

The costs are operational: it needs a CRaC-enabled JDK build, such as Azul's or the Liberica builds, the checkpoint must be taken in an environment matching production, and anything that captured state at checkpoint time, random seeds, secrets, open connections, must be re-initialised on restore, which is a correctness hazard.

I would use it for scale-to-zero and burst scaling where startup time is the product, and for a steady long-running service I would take the JDK 25 AOT cache and a traffic ramp instead.

"How do you measure that a warmup change actually helped?"

With the deploy-window p99 as the metric. I plot the endpoint's p99 for the first five minutes after each pod joins rotation, aligned on the join time, before and after the change, and compare the area under the curve above the steady-state p99.

A good warmup makes that curve flat from the first minute.

Secondary numbers: time from container start to readiness, which should not have grown unreasonably, and the JIT compilation rate in the first minute from the jdk.Compilation event count, which should be lower after the change because the work happened before traffic.

I also watch for regressions in the ramp, such as a warmup that compiled a different set of methods than real traffic uses, which shows as a second bump when the real hot paths compile.

The test is repeated across a few deploys, since a single deploy is noisy.

Drill · JPA, Hibernate & JDBC under load

This group tests whether you understand what your ORM and driver actually do on the wire — the failure modes that never show up on a laptop and always show up in production.

Q269 · Scenario. "An endpoint that lists 200 orders takes 1.8 seconds. The APM shows 201 database calls for one request. Diagnose it and rank your fixes."

Reveal answer

The real test Whether you recognize the N+1 signature instantly, can prove it, and know that the fixes are ranked, not interchangeable.

Strong answer This is the classic N+1 query problem: JPA — the Java Persistence API, the standard for mapping Java objects to database tables, with Hibernate as the usual implementation — runs one query for the orders, then lazily runs one more query per order to fetch each order's customer. To see it, I enable SQL logging (logging.level.org.hibernate.SQL=DEBUG) or, better, wrap the datasource with p6spy or datasource-proxy, which count queries per request; in the APM it is unmistakable — 201 tiny JDBC spans stacked under one endpoint span.

sql-log-excerpt.txt
select o.id, o.customer_id, o.total from orders o where o.status = ?
select c.id, c.name from customers c where c.id = ?   -- 1st order
select c.id, c.name from customers c where c.id = ?   -- 2nd order
-- ... 198 more identical single-row selects, one per order
-- datasource-proxy: 201 queries / 1 HTTP request

Fixes, ranked:

  1. JOIN FETCH in the JPQL for this specific query — one SQL statement brings orders and customers together. My default for a known hot path.
  2. @EntityGraph on the repository method when I want to keep a reusable finder and declare the fetch shape per call site.
  3. hibernate.default_batch_fetch_size=100 as a global safety net — it rewrites the 200 follow-ups into a couple of IN (…) queries. Not one query, but it caps the damage everywhere.

The caveat: JOIN FETCH on two collections at once multiplies rows into a cartesian product — 200 orders × 30 items × 5 payments is 30,000 rows — or fails outright with MultipleBagFetchException. Fetch one collection per query, or fetch-join one and batch-fetch the other. Prevention: assert query counts in an integration test so the regression fails the build, not the p95.

the 201 queries, and the four ways to fix themruns offline
// THE CAUSE: one query for the list, then one per element for a lazy association.
List<Order> orders = repo.findAll();          // 1 query
for (Order o : orders) {
    o.getCustomer().getName();                // +1 query EACH -> 200 more
}

// FIX 1 — a fetch join. One query, and my default for a known access pattern.
@Query("select o from Order o join fetch o.customer where o.status = :s")
List<Order> findByStatusWithCustomer(@Param("s") Status s);

// FIX 2 — an entity graph. Same effect, declarative, reusable.
@EntityGraph(attributePaths = {"customer", "lines"})
List<Order> findByStatus(Status s);

// CAREFUL: joining TWO collections multiplies rows (a cartesian product).
// Fetch one collection per query, or use Hibernate's batch fetching:
//   spring.jpa.properties.hibernate.default_batch_fetch_size=50
//   -> turns 200 queries into 4 (IN clauses of 50), with no query changes.
//   This is the highest value-per-effort setting for an existing codebase.

// FIX 3 — a projection. Fetches only the columns the response needs, and
// returns something that is not an entity, so laziness cannot bite at all.
public interface OrderSummary {
    Long getId();
    String getCustomerName();      // resolves the customer.name path
}
List<OrderSummary> findByStatus(Status s);

// FIX 4 — the one to avoid: EAGER on the mapping. It fixes this endpoint and
// silently pessimises every OTHER query that touches Order, for ever.
@ManyToOne(fetch = FetchType.EAGER)     // do not

// DETECTION, so it never reaches production again:
//   spring.jpa.properties.hibernate.generate_statistics=true
//   and a test that asserts the query count for the endpoint.

default_batch_fetch_size is the pragmatic fix for a large existing codebase. It turns N+1 into roughly N/50+1 across every association at once, without touching a single query — which buys time to fix the important paths properly.

Land it Fetch-join the query you are fixing, set a global batch size as the seatbelt, and never "fix" it with eager fetching everywhere — that just makes every other query pay.

Likely follow-ups
"The fetch join fixed the customers, but now the orders' line items are N+1. Why didn't the same fix work twice?"

Because JOIN FETCH on two collections in one query is either forbidden or explodes.

Hibernate throws MultipleBagFetchException when two List-typed collections are fetch-joined together, and if they are Sets it allows it but returns the cartesian product: 200 orders with 30 items and 5 payments each is 30,000 rows that Hibernate must deduplicate in memory.

So the second collection cannot simply be added to the same join.

The correct shape is to fetch-join one collection and batch-fetch the other with @BatchSize(size = 100) on the association or the global default_batch_fetch_size, which turns the second N+1 into two IN queries; or to run two separate queries against the same persistence context, the first fetching orders with customers and the second fetching the same orders with items, which Hibernate merges by identity. Either way the total is two or three statements, not 201.

"How do you assert a query count in a test so this cannot regress?"

By counting statements at the datasource. With datasource-proxy or p6spy wrapping the test datasource, each test can read the number of executed statements; the QueryCountHolder from datasource-proxy exposes select, insert, update and delete counts per thread.

The test loads a page of 200 orders through the real repository and service, then asserts select count == 2 or whatever the design intends. Hibernate's own Statistics object, enabled with hibernate.generate_statistics=true, gives getPrepareStatementCount() without a proxy.

Libraries such as Vlad Mihalcea's db-util package this as a one-line SQLStatementCountValidator.assertSelectCount(2).

The important detail is that the test data must have enough rows to trigger the N+1, at least a few dozen, because a fixture with two orders passes a query-count assertion of "less than five" while hiding the bug.

"What does the global batch size cost, and why is 100 a reasonable default rather than 1000?"

Batch fetching rewrites the per-entity loads into WHERE id IN (?, ?, ...) queries with up to that many parameters, so the cost is one query per batch instead of one per entity, plus the parameters.

Very large batches have three downsides: databases have parameter limits, such as Postgres's 65,535 and older SQL Server's 2,100; a huge IN list can produce a worse plan than several smaller ones; and Hibernate historically generated a fixed set of statement variants for different batch sizes to help statement caching, though since Hibernate 6 it uses padded or exact sizes more efficiently.

At 100, a list of 200 orders becomes two queries, which is nearly optimal, and a list of 20 becomes one.

Going to 1,000 rarely saves a measurable round trip and occasionally hits a limit, so 100 is the practical default and I raise it only for a measured case.

"When would you not fetch-join at all and go straight to a DTO projection?"

When the endpoint reads and never writes the entities.

A fetch join brings full entities into the persistence context: every column, plus a snapshot of each for dirty checking, plus the association graph, which for 200 orders with customers and items is thousands of managed objects for a page that displays five fields each.

A JPQL constructor expression, select new OrderSummary(o.id, o.total, c.name) from Order o join o.customer c, or a Spring Data interface projection, selects only those columns, allocates plain objects, and skips the persistence context entirely, which is both faster and lighter on the heap.

It also fixes the serialisation problem at the same time, because there is nothing lazy in a DTO. So for list and read endpoints my first choice is the projection; the fetch join is for the case where I load entities because I am about to modify them.

Q270 · Scenario. "A controller works in every unit test, but in production it throws LazyInitializationException. What happened and what is the right fix?"

Reveal answer

Strong answer Lazy loading means related data is not fetched until the code first touches it, and that touch needs a live Hibernate session — the per-transaction workspace, also called the persistence context, that tracks loaded entities and issues the follow-up queries. The exception means something touched a lazy field after the transaction and session closed — typically the controller or the JSON serializer walking the entity after the service method returned. The fixes, in order of preference:

  1. Fetch what this use case needs inside the query — JOIN FETCH or an entity graph — so the object is complete when the session closes.
  2. Better still, return a DTO — a data transfer object, a plain class shaped for the API — via a projection query, so nothing lazy ever leaves the service layer at all.

The wrong fix is switching the mapping to FetchType.EAGER: that is global, so every query in the codebase now drags the association along whether it needs it or not, it invites cartesian-product joins, and it still does not guarantee single-query fetching. It trades one visible exception for invisible, permanent overfetching. The other wrong fix is leaving open-session-in-view on to paper over it — which is its own question.

Land it The exception is the system telling you the use case's fetch shape was never declared — declare it in the query or project a DTO, and never punish every query with field-level eager.

Likely follow-ups
"Why did the unit tests pass — what was different about their session handling?"

Most likely the tests ran inside a transaction.

@DataJpaTest and @SpringBootTest with @Transactional on the test class wrap each test in a transaction that is rolled back at the end, so the session stays open for the entire test method, including the assertions that walked the lazy association; in production the session closed when the service method returned.

A second reason is that the test's data was small or already in the persistence context from the setup, so the association was initialised without a query.

The lesson is that a test which touches lazy state must mirror the production boundary: call the service, then clear the entity manager or end the transaction, then serialise or walk the result outside it.

I add a test that does exactly that for any endpoint returning entity-derived data, and it fails on the missing fetch shape before the deploy does.

"Isn't Hibernate.initialize or a getter call inside the service a fine fix?"

It works and it is the worst of the reasonable options. Touching the association inside the transaction, either with Hibernate.initialize(order.getCustomer()) or by calling getCustomer().getName(), forces the lazy load while the session is open, so the exception goes away.

But it does so with a separate query per entity, which is the N+1 pattern by construction, and it leaves an invisible dependency in the service method: a comment-free line whose only purpose is to warm state for a caller.

It is acceptable as a quick production fix at 3am for a single entity load.

As the real fix, I want the query to declare its shape so the loading is one statement and the intent is in the JPQL, or a DTO so no lazy state exists.

"How would you find every place in the codebase that would throw this once OSIV is turned off?"

I turn it off in staging and let the tests and traffic tell me. With spring.jpa.open-in-view=false the exception fires at every location that relied on it, and each stack trace names the controller and the serialised field.

I run the integration test suite first, which catches the covered endpoints, then replay production traffic against staging for a day and collect the distinct exception sites from the logs.

In parallel I look statically: any controller returning an @Entity type or a collection of them is a candidate, which an ArchUnit rule lists in one run. The fixes then go endpoint by endpoint, DTO projections first.

I turn OSIV off in production only when staging is clean, and I keep a metric on LazyInitializationException counts so a regression is visible on the dashboard rather than in a user's error page.

Q271. "What does open-session-in-view actually do, what does it hide, and would you turn it off?"

Reveal answer

Strong answer Open-session-in-view — OSIV, on by default in Spring Boot as spring.jpa.open-in-view=true — keeps the Hibernate session open past the service layer, for the entire web request including response rendering.

The convenience is that lazy loading during JSON serialization just works, so you never see LazyInitializationException.

What it hides is exactly that: queries now fire from the serializer, outside any service transaction, so you get invisible N+1 loads in the rendering phase, reads that are not transactionally consistent with the service's work, and database connections being reacquired and held during serialization — which means slow response writing can hold connections your pool needs.

The trade-off is real for a small server-rendered app, where the convenience may win. For a service that returns JSON from a service layer, I turn it off and let the resulting exceptions point me at every place that was silently overfetching.

Land it OSIV converts loud, fixable exceptions into quiet query storms — in an API service I set open-in-view=false and treat each new LazyInitializationException as a fetch shape I should have declared anyway.

Likely follow-ups
"Explain precisely how OSIV holds a connection during serialisation, and when it releases it."

The OpenEntityManagerInViewInterceptor binds an EntityManager to the request thread before the controller runs and closes it after the response is written.

Inside the service, the transaction borrows a connection and, when it commits, Hibernate releases the connection back to the pool by default, because the release mode is after-transaction.

But if the serialiser then touches a lazy association, Hibernate needs a connection again, borrows one from the pool with no transaction, runs the query, and holds that connection until the session closes at the end of the request, which is after the last byte has been written to the client.

So a slow client on a mobile network can hold a pooled connection for the whole download. That is the mechanism by which OSIV turns response-writing time into connection-pool time, and why the pending count rises under slow clients.

"Spring Boot logs a warning about OSIV at startup. What exactly is it warning about, and can you keep OSIV safely anywhere?"

The warning says that spring.jpa.open-in-view is enabled by default and that database queries may be performed during view rendering. It is there because the default is a convenience that most teams do not know they are relying on.

Keeping it is defensible in a server-side rendered application with Thymeleaf templates, where the template is the view and lazy navigation in it is the design, provided the response is small and the client is fast so the connection hold is short.

In an API that returns JSON built from DTOs, OSIV has nothing to do, and turning it off costs nothing. In a WebFlux application the setting does not exist because there is no request thread to bind to.

My default for a JSON service is off, set explicitly in configuration with a comment, so the next person does not re-enable it to silence an exception.

"OSIV is off and now a background @Async method throws LazyInitializationException. Same fix?"

Same principle, different boundary.

The async method runs on a different thread, so it never had the request's session even with OSIV on; what broke is that someone passed a managed entity from the request thread into the async task and the task walked a lazy field.

Entities are session-bound objects and should not cross thread boundaries.

The fix is to pass identifiers or a DTO into the task and let the task load what it needs inside its own @Transactional scope, which also fixes the subtler bug that the entity might be stale or half-flushed when the other thread reads it.

The same rule applies to messages: never put an entity on a queue. The exception is doing the same job as before, pointing at a place where session-bound state leaked out of its scope.

Q272 · Scenario. "A method annotated @Transactional(REQUIRES_NEW) is being called, yet its work rolls back together with the caller's. The annotation seems ignored. Why?"

Reveal answer

The real test Whether you can explain the proxy mechanism in one line, because that one line explains a whole family of Spring surprises.

Strong answer This is self-invocation. Spring implements @Transactional with a proxy — a wrapper object placed in front of your bean that opens and commits the transaction around each call.

Only calls that arrive from outside the bean pass through the wrapper; when a method calls another method on this, the call goes straight to the plain object, so the inner method's transaction annotation is silently ignored — no error, no log line.

That is why the REQUIRES_NEW never created a new transaction: the inner method simply ran inside the caller's. To confirm, I turn on logging.level.org.springframework.transaction.interceptor=TRACE and watch which methods actually open transactions, or check TransactionSynchronizationManager.isActualTransactionActive() at the suspicious point.

Fixes: move the inner method to its own bean so the call crosses a proxy boundary — the cleanest option — or use TransactionTemplate to demarcate the new transaction programmatically. Self-injection works but reads as a puzzle for the next maintainer.

Prevention: an ArchUnit rule or code-review convention that transactional methods are public entry points on their own beans, never internal helpers.

Land it Every Spring annotation that "does something around a method" only works across a proxy boundary — say that sentence and the interviewer knows you understand the machinery, not just the annotation.

Likely follow-ups
"Does the proxy type matter — JDK dynamic proxy versus CGLIB — for this bug?"

Not for self-invocation; both proxies are bypassed by a call on this. Where the type matters is in what gets proxied at all.

A JDK dynamic proxy implements the bean's interfaces, so only interface methods are advised and injecting the concrete class fails; Spring Boot defaults to CGLIB subclass proxies, which advise public methods on the class, but a CGLIB proxy cannot override a final method or class, and private methods are never advised by either.

Also, with CGLIB the proxy's fields are uninitialised because the subclass instance is a shell delegating to the target, so a method that reads a field directly on the proxy sees null, which is a classic puzzle in constructor-injected beans.

The fix in each case is the same: annotated methods are public, non-final, and invoked through an injected reference.

"What are the other things that silently break when the proxy boundary is crossed the wrong way?"

Every proxy-based annotation: @Cacheable, where a self-call hits the method and bypasses the cache; @Async, where a self-call runs synchronously on the caller's thread; @Retryable, where no retry happens; @PreAuthorize, where a self-call skips the security check, which is the dangerous one; and @Timed or any Micrometer aspect, where the metric is simply never recorded. There is also the reverse trap: a @Transactional method calling a @Transactional(REQUIRES_NEW) method on another bean does open a new transaction and therefore borrows a second connection from the pool, so under load that pattern needs two connections per request, and a pool sized for one deadlocks against itself when every thread holds one connection waiting for a second. Both traps come from the same mental model: the annotation is behaviour attached to a boundary, not to the method body.

"How would you detect self-invocation automatically, not just by convention?"

Two ways. Statically, an ArchUnit test that finds every method annotated with @Transactional and checks that no method in the same class calls it; ArchUnit's JavaMethodCall analysis gives call sites, so the rule is a few lines and fails the build.

IntelliJ also has an inspection for this. Dynamically, in an integration test, TransactionSynchronizationManager.isActualTransactionActive() and getCurrentTransactionName() assert that a method that claims REQUIRES_NEW is in fact running in a transaction named after itself, not after its caller.

And in production, the Hikari acquire metrics tell the story indirectly: a REQUIRES_NEW that works borrows a second connection per request, and if that borrow never happens under load, the annotation is not firing.

Q273 · Scenario. "A service method wrote two of its three rows, then threw a checked business exception — and you discover the two rows were committed. The method was @Transactional. Explain."

Reveal answer

Strong answer By default, Spring rolls back only on unchecked exceptions — RuntimeException and Error.

A checked exception is treated as a declared business outcome, so the transaction interceptor lets the commit proceed, and the two rows written before the throw became permanent.

That default is historical: checked exceptions were presumed recoverable conditions the caller would handle, not failures.

The immediate fix is to declare the intent explicitly — @Transactional(rollbackFor = Exception.class) on that method — or to throw an unchecked exception for what is genuinely a failure. My prevention stance:

  1. Team convention: failures are runtime exceptions; checked exceptions are reserved for outcomes the caller genuinely handles, and any transactional method that throws one gets an explicit rollbackFor or noRollbackFor so the behavior is stated, not inherited.
  2. A test for the rollback path of every transactional write — the test that throws mid-method and asserts nothing persisted. It is the cheapest test that catches this whole class of bug.

Land it "Transactional" does not mean "rolls back on any exception" — it means "rolls back on the exceptions Spring was told about", and a senior states that rule explicitly in the annotation rather than trusting the default.

Likely follow-ups
"The exception was caught and handled inside the method — did the transaction commit or roll back?"

It depends on where it was thrown, and this is where teams get burned. If the exception was thrown and caught entirely inside my method, the transaction interceptor never saw it, so the transaction commits normally with whatever was written.

But if the exception was a RuntimeException thrown from a nested @Transactional method on another bean, that inner proxy already marked the shared transaction rollback-only before my catch block ran; my method then returns normally and the commit throws UnexpectedRollbackException, which is the confusing "I handled the error and it still failed" case.

I detect it by calling TransactionAspectSupport.currentTransactionStatus().isRollbackOnly() in the catch block, or I avoid it by not catching across a transactional boundary: either let it propagate, or give the inner call REQUIRES_NEW so its failure is isolated.

"Where does the rollback rule live, and does it apply to the Jakarta @Transactional too?"

It lives in the annotation's attributes and in the RuleBasedTransactionAttribute that Spring builds from them.

rollbackFor and noRollbackFor are matched against the exception's class hierarchy, and the most specific matching rule wins, so rollbackFor = Exception.class with noRollbackFor = ValidationException.class rolls back on everything except that one.

The Jakarta jakarta.transaction.Transactional has the same shape with rollbackOn and dontRollbackOn, and Spring honours it, but its default is identical: unchecked rolls back, checked does not.

There is no global switch in Spring Boot to change the default, so teams that want "any exception rolls back" everywhere either use a meta-annotation, @Transactional(rollbackFor = Exception.class) wrapped in their own annotation, or register a custom TransactionAttributeSource. The meta-annotation is the readable choice.

"How do you write the rollback test so it is meaningful rather than tautological?"

It must observe the database from outside the failed transaction.

The shape: an integration test with a real database via Testcontainers, not an in-memory one with different semantics; the test itself is not @Transactional, because a test-managed transaction would wrap and roll back everything and hide the bug.

It calls the service method with an input that triggers the exception after the first write, asserts that the expected exception propagates, and then queries the table through a separate JdbcTemplate and asserts the row count is unchanged.

The tautology to avoid is asserting on the entity manager's state, which is in-memory and tells nothing about the commit. This test takes a second to run and catches the checked-exception default, the self-invocation bug, and a missing annotation, all with one assertion.

Q274 · Scenario. "During a partner API slowdown, your database pool exhausted and every endpoint failed — yet the database itself was nearly idle. The failing code calls the partner from inside a @Transactional method. Connect the dots."

Reveal answer

Strong answer Once a transactional method runs its first query, its database connection is pinned to that thread until the transaction commits or rolls back. With a remote HTTP call inside the transaction, the connection sits idle-but-borrowed for the entire call.

When the partner degraded to, say, 5 seconds per call, every request held a connection for 5 seconds; a pool of 20 connections then sustains only 4 requests per second, so under normal traffic the pool drains in moments and every other endpoint — including ones that never touch the partner — starves waiting for a connection.

Diagnosis signature: Hikari active connections pegged at max while the database reports idle sessions; a thread dump — a snapshot of what every thread is doing — shows threads inside transactional methods blocked in socket reads; traces show the HTTP span nested inside the transaction span.

The fix is structural: get the remote call out of the transaction.

Call the partner first and then open a short transaction to record the result, or commit the local state and publish the outbound call via an outbox — the pattern where the intent is written to a table in the same transaction and a separate worker performs the remote call.

Prevention: a hard team rule that a transaction contains database work only — no HTTP, no queue publish, no file I/O.

Land it Transactions should be measured in milliseconds, and the moment one contains a network call its duration belongs to someone else's outage — keep the transaction boundary tight around the database work alone.

Likely follow-ups
"Show me the outbox shape in a bit more detail, including how the worker avoids duplicates."

In the same transaction as the business write, the service inserts a row into an outbox table: an ID, the target, the payload, a created timestamp, and a status.

The transaction commits both or neither, so there is no window where the order exists but the intent to call the partner does not.

A worker polls outbox where status = 'pending' order by created limit 100 for update skip locked, which lets several workers run without picking the same rows, calls the partner, and marks each row sent.

The partner call itself can still be repeated if the worker dies between the call and the status update, so the call carries an idempotency key, the outbox row's ID, and the partner deduplicates on it.

That gives at-least-once delivery with exactly-once effect, and the transaction that mattered, the local one, stays milliseconds long.

"What if the partner's answer is needed to decide whether to commit — an authorisation, say?"

Then the call precedes the transaction, and the state machine records both steps. I call the partner first with an idempotency key derived from the pending operation, outside any transaction, holding no connection.

When the answer arrives I open a short transaction that writes the result, authorised or declined, and the local state. If my process dies between the two steps, a reconciliation job asks the partner for the status of that key and completes the local write.

What I avoid is the intuitive shape, open transaction, call partner, commit, because it holds a connection for the partner's latency and turns their slowness into my pool exhaustion.

If the business genuinely wants both writes to be atomic across two systems, the honest answer is that it cannot be, and the design is a saga with compensation, not a transaction.

"How do you find every transaction in the codebase that makes a remote call?"

Statically and at runtime.

Statically, an ArchUnit rule: methods annotated @Transactional, or any method they call transitively within the application's packages, must not call classes in the HTTP client, messaging, or file I/O packages; ArchUnit can walk the call graph within the analysed classes, so a helper method that hides the call is still caught.

At runtime, in staging, a datasource proxy that records how long each connection is held per transaction and logs the stack when the hold exceeds, say, 200 milliseconds; a transaction that contains a network call will show up on the first slow response.

Hikari's leakDetectionThreshold at a low value such as two seconds does the same more crudely. Between the two, the list of offending methods is usually short and the refactor is mechanical.

"Why was the database idle if the pool was exhausted — doesn't that contradict pool exhaustion?"

No, it is the defining evidence. The pool counts borrowed connections, not busy ones.

Every connection was borrowed by a thread that was waiting on the partner's socket, so from the pool's side all 20 were in use and the 21st request timed out; from the database's side, all 20 sessions were idle, most of them idle in transaction, executing nothing.

The database's CPU was low and pg_stat_activity showed twenty sessions with the state idle in transaction and a query that finished seconds ago.

That combination, pool full and database idle, is the fingerprint that distinguishes this incident from slow queries, where the database is busy, and from a leak, where the borrowed count never comes down after traffic drops.

I would put "active sessions doing nothing" on the dashboard for exactly this reason.

Q275 · Scenario. "A nightly job loads 10,000 entities, sets two fields on each, and saves. It takes 20 minutes and hammers the heap. What is it actually doing, and how do you fix it?"

Reveal answer

Strong answer The job is paying Hibernate's dirty checking bill at maximum rate.

Hibernate keeps a snapshot of every entity it loads, and at flush — the moment it synchronizes in-memory changes to the database — it compares each entity field-by-field against its snapshot to decide which UPDATEs to emit.

So this job pulls 10,000 full rows over the wire, holds 10,000 entities plus 10,000 snapshots on the heap, runs 10,000 comparisons, and then issues 10,000 individual UPDATE statements.

The fix is to stop moving the data to the change and instead move the change to the data: one bulk JPQL statement — update Account a set a.status = :s, a.reviewedAt = :t where a.batchId = :b — or the equivalent native SQL, which is a single statement doing set-based work where the data lives.

The job drops from minutes to seconds. The caveat: bulk JPQL bypasses the persistence context, so any already-loaded entities are now stale — clear the session afterward.

And for read paths generally, @Transactional(readOnly = true) earns its keep by the same mechanism: it sets the flush mode so no flush and no dirty-check comparison happens, lets Hibernate skip snapshot bookkeeping, and passes a read-only hint to the driver, which some setups use to route the query to a replica.

Land it An ORM is for object workflows, not set operations — when the change is "two fields on ten thousand rows", one UPDATE statement is the honest tool, and readOnly=true is how you stop paying dirty-checking tax on paths that never write.

Likely follow-ups
"The update is not uniform — each row's new value depends on its own data. Bulk JPQL will not do it. Now what?"

First I check whether the dependency can be expressed in SQL, which it usually can: update accounts set tier = case when balance > 10000 then 'gold' else 'silver' end where ... is set-based and runs in seconds.

If the logic genuinely needs Java, I stream the entities in a stateless way and write in batches: a StatelessSession in Hibernate, or a Spring Data Stream<T> with a fetch size, processing in chunks of 500, calling flush() and clear() after each chunk so the persistence context never holds more than 500 entities and their snapshots, with hibernate.jdbc.batch_size=50 and order_updates=true so the updates go to the driver in batches.

That brings 10,000 rows to a few seconds and a flat heap. And I run it in chunked transactions rather than one twenty-minute one, so a failure at row 9,000 does not roll back everything and lock the table throughout.

"What exactly does readOnly=true change, layer by layer?"

At the Spring layer it sets the transaction definition's read-only flag.

Hibernate's Spring integration then sets the session's flush mode to MANUAL, so no automatic flush and no dirty-check comparison happens at commit, and since Hibernate 5.4 it also sets the session default to read-only, so entities are loaded without snapshot copies, which halves the memory per entity.

At the JDBC layer Spring calls Connection.setReadOnly(true), which the Postgres driver translates into a read-only transaction and which routing datasources such as a replica-aware proxy use to send the query to a replica; MySQL's driver uses it to enable a read-only optimisation on InnoDB. What it does not do is prevent writes: a native update inside a read-only transaction in Postgres fails, but a managed entity modified inside one is simply never flushed, silently. So it is a performance and routing hint, not a guard.

"Twenty minutes for 10,000 rows seems too long even for N updates. What else was going on?"

The arithmetic supports the suspicion: 10,000 updates at a millisecond each is ten seconds, not twenty minutes. So the job had at least one more problem.

The usual candidates are lazy associations touched in the loop, so each entity triggered several more selects; a missing index on the update's key so each update scanned; row locks contended with the live application, so updates waited; or a flush before every query, which Hibernate does in AUTO flush mode when a query might depend on pending changes, and with 10,000 dirty entities each flush dirty-checks all of them, making the job quadratic.

That last one is the classic and explains twenty minutes exactly. I would confirm with SQL logging and a profile before the rewrite, because the set-based update fixes all of them at once but the diagnosis tells me what other jobs share the disease.

Q276. "First-level versus second-level cache in Hibernate — when does the second level actually pay off, and what is the catch?"

Reveal answer

Strong answer The first-level cache is the persistence context itself: per session, always on, and it simply means loading the same entity twice by ID within one transaction costs one query. It is deduplication, not a performance feature you tune.

The second-level cache (2LC) is shared across sessions — backed by Ehcache, Infinispan, or similar — and caches entities by ID between transactions.

It genuinely pays off for read-mostly reference data fetched by primary key: country tables, product category metadata, configuration — data where slight staleness is harmless.

The catch is invalidation in a cluster: every node must learn about every change, writes that bypass Hibernate leave the cache silently wrong, and the related query cache is invalidated by any write to the touched tables, which under real write load makes it net negative.

My honest position: most services are better served by an explicit Caffeine or Redis cache at the service layer, where keys, lifetimes, and invalidation are deliberate decisions rather than ORM side effects.

Land it Enable 2LC for by-ID reference data you rarely write; for everything else, cache explicitly at the service layer where you can see and reason about the invalidation.

Likely follow-ups
"How does the second-level cache handle a write in a cluster, and where does it go wrong?"

Each node's cache is local unless the provider replicates.

On a write, the node that performed it invalidates or updates its own cache entry for that ID, and if the provider is a clustered one such as Infinispan in invalidation mode, it sends an invalidation message to the other nodes, which drop their copy.

If the provider is a local Ehcache with no clustering, the other nodes keep serving the old value until their TTL expires, which is the common misconfiguration.

It also goes wrong with any write that Hibernate does not see: a bulk JPQL update, which Hibernate handles by invalidating whole regions, a native SQL statement, which it does not, and another application writing the same table, which nothing handles.

So a 2LC is safe only when every write to those tables goes through this application's entity layer, and that is a constraint few systems keep for long.

"What are the cache concurrency strategies, and which one would you pick?"

Hibernate offers four. READ_ONLY for data that never changes, the cheapest and safest; an update throws. NONSTRICT_READ_WRITE for rarely updated data where a brief window of staleness after a write is acceptable, with no locking.

READ_WRITE for data that is updated and must not be served stale, implemented with soft locks in the cache around the write so readers get the database value during the window. TRANSACTIONAL for providers that participate in JTA transactions, which almost nobody runs now.

My pick for the reference-data case is READ_ONLY or NONSTRICT_READ_WRITE, because they are simple and their failure mode is bounded staleness. READ_WRITE on a hot entity means lock traffic in the cache on every write, which is where the cost can exceed the benefit.

"How would you measure whether the 2LC is actually helping?"

With Hibernate statistics, turned on with hibernate.generate_statistics=true and exposed via Micrometer's Hibernate binder. The numbers are secondLevelCacheHitCount, secondLevelCacheMissCount and secondLevelCachePutCount, per region.

A hit ratio below about 80% on a region means the entries are not being reused enough to justify the invalidation risk, and a put count close to the miss count with a high miss count means constant churn.

Then I compare the endpoint's p95 and the database's query rate with the region enabled and disabled, in a load test, which is the only honest test; a cache that saves 2 milliseconds on a 5 millisecond primary-key lookup while adding a cluster invalidation on every write is net negative.

The statistics collection has a small overhead, so in production I sample it on one pod.

Q277. "Thirty instances of your service each run the default pool of 10 connections against one Postgres. Is a bigger pool faster? Do the math with me."

Reveal answer

The real test Whether you know the counterintuitive truth that smaller pools are usually faster, and can defend it with arithmetic.

Strong answer Bigger is usually slower.

A database can truly execute only about as many queries in parallel as it has cores, plus some allowance for I/O waits — HikariCP's starting formula is cores × 2 for the database server, so a 16-core Postgres does its best work around 32 active connections.

Every connection beyond that does not add throughput; it adds queries queueing inside the database, context switching, and lock contention, so each query gets slower.

Now the fleet math: 30 instances × 10 connections is 300 potential connections against a Postgres whose max_connections might be 100 — instances start failing to connect during deploys and spikes, and even if I raise the limit, 300 active connections on 16 cores is thrashing, not throughput.

The right shape is to size the total near the database's sweet spot: 30 instances × 3 connections is 90 — still high — or better, put PgBouncer (a connection proxy that multiplexes many client connections onto few server ones) in front so the fleet shares a small true pool.

Counterintuitively, requests then wait briefly in the app-side pool queue and complete sooner overall, because the database runs uncongested.

Land it The pool exists to protect the database from concurrency it cannot use — size the fleet-wide total to the database's cores, not each instance's optimism.

Likely follow-ups
"What does PgBouncer change, and what breaks when you put it in front of a JPA application?"

PgBouncer sits between the fleet and Postgres and multiplexes many client connections onto a small server pool, in one of three modes.

Session mode assigns a server connection per client connection, which saves nothing; transaction mode assigns a server connection per transaction and returns it at commit, which is the useful one; statement mode is too restrictive for most applications.

Transaction mode breaks anything that assumes session state persists across transactions: server-side prepared statements, which the Postgres JDBC driver creates after prepareThreshold executions, so prepareThreshold=0 or PgBouncer 1.21 and later with its prepared statement support is needed; SET commands that are not SET LOCAL; advisory locks held across transactions; and LISTEN.

Hikari's connectionInitSql runs per server connection, not per client, so per-request settings must go inside the transaction. Once those are handled, the fleet's 300 connections become 40 real ones.

"Where does the cores × 2 formula come from, and when is it wrong?"

It is the HikariCP wiki's summary of a PostgreSQL benchmark: throughput peaked at roughly the number of cores times two plus the number of disk spindles, because each active connection is a process that alternates between CPU and I/O, so about two per core keeps the cores busy while others wait on disk.

It is wrong in both directions. With fast NVMe storage and a working set in memory, the I/O wait is tiny, so the sweet spot drops toward one per core.

With queries that wait on locks, on a slow network to the client, or on external calls in stored procedures, more connections can help because the waiting ones do not use CPU. And it is a per-database number: two applications sharing the database share the budget.

So I use it as a starting point and then measure the database's throughput against active connections in a load test, which usually shows a flat top somewhere between one and three per core.

"Postgres max_connections is 100 and you have 30 pods with 10 each. What breaks first during a rolling deploy?"

Connection refusals on the new pods. During a rolling update, old and new pods overlap, so for a while there are, say, 35 pods each wanting 10 connections, 350 against a limit of 100.

Hikari on a new pod tries to fill to minimumIdle, which defaults to the maximum, gets "too many connections" from Postgres, and the pod fails its readiness probe or starts serving errors; if readiness depends on the pool, the rollout stalls.

Old pods already holding connections keep theirs, so the failures fall on the new ones.

Fixes in order: reduce per-pod pool size so the fleet total fits with room for the overlap, set minimumIdle low so pods connect lazily, and put PgBouncer in front so the pod count stops mattering.

And an alert on Postgres's numbackends against max_connections, since this failure has a visible run-up.

"What changes for the pool math when you move to virtual threads?"

Nothing about the database and everything about the pressure on the pool. The database still does its best work at a few dozen active connections, so the fleet-wide pool total stays the same.

But with platform threads, the 200-thread Tomcat cap limited how many requests could wait for a connection; with virtual threads, ten thousand requests can all be waiting on a pool of ten, so connectionTimeout becomes the critical setting and the pending count can reach thousands.

The pool becomes the concurrency limiter for the whole service, which is fine as long as the wait is short and bounded.

I set the connection timeout to a second or two, shed excess load at the door with a concurrency limit derived from the pool size and the average hold time, and watch the acquire histogram as the primary saturation metric.

Q278 · Scenario. "Requests are failing with 'Connection is not available, request timed out after 30000ms'. Leak, slow queries, or undersized pool — how do you tell which, before changing anything?"

Reveal answer

Strong answer Those three causes have the same symptom and different fingerprints, so I read the metrics before touching the size.

  1. Slow queries: active connections pegged at max and the time each connection is held per use has climbed. I confirm in the database — the slow-query log or pg_stat_activity showing long-running statements — and the fix belongs to the query, not the pool.
  2. Leak: active climbs steadily and never comes back down even when traffic drops, because connections are borrowed and never returned. I set Hikari's leakDetectionThreshold=60000, which logs the stack trace of any borrow held over 60 seconds — that stack names the guilty code. Typical culprits: a manual getConnection() outside try-with-resources, or a transaction pinned open across a remote call, which is a leak in slow motion.
  3. Undersized: connections are held briefly, usage looks healthy, but the pending/wait queue deepens only at peak traffic and recovers after. Only then do I consider a bigger pool — checking first that the database has headroom for it, because if the database is the constraint, a bigger pool just moves the queue somewhere more expensive.

Prevention: alert on connection acquire-wait p95 rising, which fires minutes before the 30-second timeout does, and keep leak detection on permanently in every environment.

Land it "Pool exhausted" is a symptom with three diseases — active-time, return-behavior, and wait-queue metrics distinguish them, and only one of the three is ever cured by making the pool bigger.

Likely follow-ups
"The metrics say leak but leak detection logs nothing. Why?"

Two reasons.

The threshold is longer than the hold: leak detection fires when a connection has been out for more than leakDetectionThreshold, and a connection held for 50 seconds under a 60-second threshold never logs, while a steady stream of such holds keeps the pool near empty.

Lowering the threshold to 10 seconds during the investigation catches those.

The other reason is that the leak is not a leak but a slow return: connections are returned, but each borrow lasts long enough that the active count looks flat and high; the difference is visible in the usage histogram, hikaricp_connections_usage_seconds, which shows long holds rather than never-returned.

A true leak has holds that never appear in the usage histogram because they never end. Both point to the same code, the transaction that stays open, so the fix overlaps; the diagnosis just names it differently.

"Which Hikari metrics do you read, and what does each look like in each of the three cases?"

hikaricp_connections_active, hikaricp_connections_idle, hikaricp_connections_pending, hikaricp_connections_acquire_seconds as a histogram, hikaricp_connections_usage_seconds as a histogram, and hikaricp_connections_timeout_total. Slow queries: active at max, usage histogram shifted right, acquire histogram rising, pending nonzero, and the database busy.

Leak: active climbing in steps that never fall, idle at zero, usage histogram unchanged because the leaked connections never record a usage, pending rising after the last connection is gone, and the database idle in transaction.

Undersized: active hits max only at peak, usage histogram normal, pending and acquire spike briefly and recover, timeouts only at peak hours. I read these on one graph with all six series and the diagnosis is usually visible in the shape of the active line alone.

"You concluded undersized and raised the pool from 10 to 20. What must you check before and after?"

Before: the database's capacity, meaning cores, current active session count across all clients, and max_connections minus what is already used, including the reserve for superuser connections; and the fleet arithmetic, 12 pods times 20 is 240, which must fit both the limit and the sweet spot.

After: the endpoint p99, which should fall, and the database's per-query latency, which must not rise; if per-query latency rose, the database was closer to saturation than I thought and the extra connections are queueing inside it, and I back off.

I also check the pending count went to zero rather than merely shrinking, because if it did not, the constraint is somewhere else, usually the hold time.

A pool change is an experiment with a hypothesis and a rollback, and I deploy it to one pod first.

Q279. "Why do prepared statements matter for a high-traffic service — beyond the SQL injection answer everyone gives?"

Reveal answer

Strong answer A prepared statement is a query template with placeholders: the SQL text is parsed and planned once, and subsequent executions send only parameter values. Three benefits compound at scale.

First, safety: parameters are never concatenated into the SQL text, so injection is structurally impossible for that statement. Second, parse cost: at thousands of queries per second, re-parsing identical SQL is measurable CPU on the database — templates eliminate it.

Third, plan reuse: the execution plan can be cached and reused rather than recomputed.

The Java-side detail seniors know: pooling and statement caching live in the driver, so it must be configured — for MySQL, cachePrepStmts=true with prepStmtCacheSize=250 and prepStmtCacheSqlLimit=2048; Postgres switches to server-side prepared statements after prepareThreshold executions.

One honest caveat in one sentence: a reused generic plan can be wrong for heavily skewed data, and that plan-stability discussion belongs to the database drill.

Land it Prepared statements are the rare optimization that is also the security control — the only configuration question is making sure the driver's statement cache is actually turned on.

Likely follow-ups
"What is the difference between client-side and server-side prepared statements in the Postgres driver?"

A client-side prepared statement is just the driver substituting parameters into the SQL text safely and sending a complete statement each time; it gives injection safety but no parse or plan reuse.

A server-side prepared statement is registered with the database by name, parsed and planned once, and subsequent executions send only the name and the parameters.

The Postgres JDBC driver starts client-side and switches a statement to server-side after it has been executed prepareThreshold times on the same connection, five by default, so the first four executions of every query on every fresh connection pay the parse.

With a pool, connections are long-lived and the threshold is crossed quickly. Setting prepareThreshold=1 makes the switch immediate, and the driver caches up to preparedStatementCacheQueries statements, 256 by default, per connection.

"When can a reused plan be the wrong plan, and what does Postgres do about it?"

When the parameter value changes the best plan. A query filtering on a status column where 99% of rows are 'done' should scan for status 'done' and use the index for status 'pending'; a generic plan built without knowing the value picks one strategy for both.

Postgres handles this by planning the first five executions of a server-side statement with custom plans that see the actual values, then comparing the average custom plan cost with a generic plan's cost and switching to the generic one only if it is not worse; plan_cache_mode forces one or the other when the heuristic guesses wrong.

MySQL replans on each execution and does not have this issue but also does not get plan reuse.

The symptom in production is one query that is fast for most parameters and slow for the popular value, which the slow-query log shows as the same statement with wildly varying times.

"How do you see whether your statements are actually being cached, in production?"

On the database side. For Postgres, pg_stat_statements shows each normalised query with its call count, and pg_prepared_statements on a given session lists the server-side statements it holds; if every session shows the same handful of statements, caching is working.

If the parse rate is high, the pg_stat_database view does not expose parse counts directly, but the CPU profile of the Postgres process would show time in the parser and planner.

For MySQL, SHOW GLOBAL STATUS LIKE 'Com_stmt_prepare' against Com_stmt_execute gives the ratio; a prepare per execute means the cache is off or too small. On the Java side, JFR's jdk.SocketWrite events would show the size of the messages, but the database counters are the direct evidence.

Q280. "You need to insert 10,000 rows from Java. Walk me through making that fast, with rough numbers."

Reveal answer

Strong answer The enemy is round trips. Ten thousand single INSERTs at even 1 ms of network round trip each is 10+ seconds of pure waiting before the database does any real work.

JDBC batching — addBatch() then executeBatch() in chunks of 500 to 1,000 — sends many rows per trip, and committing per chunk keeps transactions bounded.

On MySQL I also set rewriteBatchedStatements=true, which rewrites a batch into true multi-row INSERT … VALUES (…), (…) statements; the combination typically lands a 10–50× speedup, taking that 10-thousand-row load from tens of seconds to well under two.

Through Hibernate the same idea needs hibernate.jdbc.batch_size=50 plus hibernate.order_inserts=true, and one trap worth naming: IDENTITY ID generation silently disables insert batching, because Hibernate must read back each generated key — use a SEQUENCE-based generator with an allocation size instead.

For truly bulk loads, the database's native path (COPY in Postgres) beats JDBC entirely.

Land it Count round trips, not rows — chunked batches with the driver rewrite turn ten thousand trips into twenty, and the IDENTITY-disables-batching trap is the detail that shows you have done this in anger.

Likely follow-ups
"Why does IDENTITY disable batching, and what does the SEQUENCE alternative cost?"

With IDENTITY, the database assigns the key during the insert, and JPA requires the entity's identifier to be known once persist returns, so Hibernate must execute each insert immediately and read the generated key back, one round trip per row; there is no way to defer it into a batch. With SEQUENCE, Hibernate asks the database for the next value before the insert, and with an allocation size of 50 it fetches one value and uses the next 49 locally, so 10,000 rows need 200 sequence calls plus 20 batched insert round trips of 500 rows. The cost is gaps in the ID sequence when a process dies holding unused values, which is harmless, and the requirement that the database supports sequences, which MySQL does not; on MySQL the practical answer is TABLE generation, which is slow, or accepting IDENTITY and using JDBC batching directly for bulk paths.

"How do you choose the batch size, and what does too big look like?"

The per-row cost drops quickly up to a few hundred rows per batch and flattens after; at 1,000 the round-trip overhead is already amortised to almost nothing, so the gains beyond that are noise. Too big shows up as memory and as failure granularity.

The driver builds the batch in memory, so a batch of 100,000 rows of a kilobyte each is 100 megabytes on the client, and with MySQL's rewrite it becomes a single SQL string that can exceed max_allowed_packet, which defaults to 64 megabytes, producing a confusing "packet too large" error.

On the failure side, a constraint violation in row 50,000 fails the whole batch and, depending on the driver, tells you nothing about which row. So I use 500 to 1,000, commit per batch, and log the batch index so a failure is locatable.

"When would you use COPY or LOAD DATA instead, and what do you give up?"

For anything in the millions of rows or on a regular bulk schedule.

Postgres COPY FROM STDIN through the driver's CopyManager streams rows in a text or binary format directly into the table, bypassing the SQL parser and the per-row protocol overhead, and routinely loads hundreds of thousands of rows per second on ordinary hardware; MySQL's LOAD DATA LOCAL INFILE is the equivalent.

What I give up: the ORM entirely, so no entity lifecycle callbacks, no validation annotations, and no second-level cache invalidation; the ability to handle a bad row gracefully, since a single malformed row fails the whole COPY unless I pre-validate; and portability, since each database has its own command.

For a nightly load of a reference table, those are fine. For inserting orders from a request path, JDBC batching is the right level.

Q281 · Scenario. "A CSV-export endpoint for a big customer dies with OutOfMemoryError. The query selects about a million rows. What is happening and how do you stream it properly?"

Reveal answer

Strong answer By default, most JDBC drivers materialize the entire result set in memory before your first next() call — a million rows of a few hundred bytes each is hundreds of megabytes, and the heap gives out (OOM — out of memory). The fix is cursor streaming: fetch a window of rows at a time and write them out as you go.

  1. Set a fetch size so the driver pulls chunks: statement.setFetchSize(1000). Driver fine print matters — Postgres honors it only with auto-commit off, and MySQL needs useCursorFetch=true (or the legacy setFetchSize(Integer.MIN_VALUE) for row-by-row streaming).
  2. Stream, don't collect: JdbcTemplate with a RowCallbackHandler, or a Spring Data method returning Stream<T> inside a transaction and a try-with-resources block — write each row to the servlet output stream immediately, never into a List.
  3. Keep it off the persistence context: a million managed entities means a million dirty-check snapshots, so use a plain projection, or clear the session periodically if entities are unavoidable.
  4. Acknowledge the trade-off: streaming holds one connection and transaction for the whole export, so bound it — run exports on a separate small pool, or chunk with keyset pagination so no single connection is held for minutes.

Land it The default result-set behavior is "load everything, then start" — for anything unbounded, the senior move is fetch-size streaming plus a hard decision about how long you will pin the connection.

Likely follow-ups
"You set setFetchSize(1000) and it still ran out of memory. What did you miss?"

Almost always a driver precondition. On Postgres, the fetch size is silently ignored unless three things hold: auto-commit is off, the statement is TYPE_FORWARD_ONLY, and the fetch size is greater than zero, so a JdbcTemplate call outside a transaction streams nothing.

On MySQL, setFetchSize is ignored unless useCursorFetch=true is on the JDBC URL, or the fetch size is exactly Integer.MIN_VALUE.

I verify by checking the driver's behavior directly: with streaming working, a query for a million rows returns from executeQuery() in milliseconds and memory stays flat during iteration; without it, executeQuery() itself takes seconds and the heap jumps.

If the driver is fine, the next suspect is my own code collecting rows into a list, or the servlet response buffer not being flushed.

"How do you keep the HTTP response from buffering the whole CSV in memory on the way out?"

By writing to the response stream and flushing as I go, without a Content-Length header, so the container uses chunked transfer encoding.

In Spring MVC I return a StreamingResponseBody whose lambda receives the OutputStream; inside it I wrap the stream in a BufferedWriter, write each row, and call flush() every thousand rows or so. That keeps at most one buffer's worth of rows in memory.

Two details matter: StreamingResponseBody runs on a separate thread from Spring's async support, so the transaction and the JDBC cursor must be opened inside the lambda, not in the controller; and I disable any servlet filter that buffers responses, such as a content-caching filter for request logging, on this endpoint, because such a filter re-materializes the whole body.

"The export now takes four minutes and holds a connection the whole time. Is that acceptable?"

Only if it is isolated and bounded. Isolation means a separate small HikariCP pool, say three connections, dedicated to exports, so four-minute holds can never starve the main pool that serves interactive traffic.

Bounding means a limit on concurrent exports, enforced with a Semaphore or by the pool size itself, and a statement timeout on the export query so a runaway cannot hold the connection for an hour.

Postgres also needs care with long-running transactions because they block vacuum; a REPEATABLE READ snapshot held for four minutes is fine, but hours are not.

If exports are frequent or large, the better design is to move them off the request path entirely: a background job writes the CSV to object storage in keyset-paginated chunks and the client gets a download link, which drops the connection between chunks.

"How would you do this with JPA and Hibernate specifically without blowing the persistence context?"

Three tools. First, a Spring Data repository method returning Stream<OrderRow>, annotated @QueryHints(@QueryHint(name = HibernateHints.HINT_FETCH_SIZE, value = "1000")) and called inside a read-only transaction with try-with-resources, so Hibernate uses a scrollable result.

Second, select a projection, either an interface projection or a JPQL constructor expression, so no managed entities are created and there is nothing to dirty-check.

Third, if entities are unavoidable, call entityManager.detach(e) per row or entityManager.clear() every thousand rows, because the persistence context otherwise holds a snapshot of every entity loaded in the transaction.

I also mark the transaction read-only, which lets Hibernate skip the dirty check on flush and lets the driver use a read-only snapshot.

Q282 · Scenario. "Your paginated API is fine for early pages, but page 10,000 times out. Why does OFFSET do this, and what is the fix?"

Reveal answer

Strong answer OFFSET 500000 LIMIT 50 does not jump to row 500,000 — the database must walk and discard half a million rows in sort order before returning the 50 you asked for, so cost grows linearly with page number, and deep pages also drift when concurrent inserts shift rows between requests.

The fix is keyset pagination, also called the seek method: instead of a page number, the client sends the sort-key values of the last row it saw, and the query seeks directly past them — where (created_at, id) < (:lastCreatedAt, :lastId) order by created_at desc, id desc limit 50.

With an index on that key the database jumps straight to the position, so page 10,000 costs the same as page one; why that index makes the seek cheap is the database drill's territory, and I hand it off in one sentence.

The trade-offs to state: you need a deterministic, unique sort key (hence the id tiebreaker), and you lose random jumps to an arbitrary page number — for infinite-scroll APIs and exports nobody misses them, and I expose it as an opaque cursor token in the API.

Land it OFFSET pays for every row it skips while keyset pays only for the rows it returns — for any deep or unbounded listing I design the API around a cursor from day one.

Likely follow-ups
"How do you build the opaque cursor, and what stops clients from tampering with it?"

The cursor encodes the last row's sort key values, for example the JSON {"createdAt":"2026-08-27T10:15:00Z","id":88123}, Base64url-encoded so it is a single safe token. Opacity matters because clients otherwise hard-code the format and I can never change the sort key.

To prevent tampering I append an HMAC, a keyed hash, over the payload using a server-side secret, and reject any cursor whose signature does not match; that stops a client from skipping to arbitrary positions or injecting values that break the query.

I also version the cursor with a leading byte so old tokens can be rejected or migrated after a sort-key change. The response carries nextCursor and a null cursor means the end. The token stays under a hundred bytes, which is fine for a query parameter.

"The product owner insists on showing 'page 3 of 250' and jumping to page 200. Now what?"

Then I separate the two requirements. The total count can be served from an approximate source, for example a periodically refreshed counter or Postgres's reltuples estimate, because an exact COUNT(*) over a filtered million rows is its own slow query.

Jumping to page 200 is the genuinely hard part; keyset cannot do it because it does not know the key at row 10,000.

The compromise I offer is a hybrid: keyset for next and previous, which covers most navigation, and OFFSET only for explicit jumps, capped at some depth such as page 100, beyond which the UI offers filtering and sorting instead.

For truly deep random access, a precomputed row-number table or a search engine with a sorted index is the honest answer, and I say that cost out loud rather than quietly shipping deep OFFSETs.

"Why exactly does OFFSET have to walk the skipped rows? Cannot the index skip ahead?"

Because a B-tree index knows order but not position.

It can find the first row with created_at < X in logarithmic time, but it has no count of how many rows precede an arbitrary position, so "the 500,000th row in sort order" requires walking 500,000 index entries and, for each visible-row check, often a heap fetch too.

On Postgres, EXPLAIN (ANALYZE, BUFFERS) makes it visible: the plan shows an index scan with rows=500050 actually read and then a Limit node discarding all but 50, with buffer counts in the hundreds of thousands. The keyset version of the same plan shows rows=50.

That side-by-side plan output is the artifact I put in the pull request, because it settles the argument without a load test.

"What changes for a paginated API sorted by a non-unique, mutable column like price?"

Two things.

Non-uniqueness needs the tiebreaker, so the key becomes (price, id) with a composite index in that exact order, and the WHERE clause uses row-value comparison (price, id) > (:lastPrice, :lastId), which Postgres supports natively; on databases without row-value comparison it expands to price > :p OR (price = :p AND id > :i), which needs care to stay index-friendly.

Mutability means a row whose price changes between requests can appear twice or vanish from the sequence; that is inherent to any pagination over a live table, and I document it rather than fight it.

If the business needs a stable list, I snapshot: sort by an immutable column, or materialize the result set with a version stamp for the duration of the browsing session.

Drill · Caching & the HTTP edge

These questions test whether you treat caches and HTTP clients as engineered components with failure modes, budgets, and honesty about staleness — not as free speed.

Q283. "In-process Caffeine or shared Redis — how do you decide? Give me your decision ladder with rough numbers."

Reveal answer

Strong answer My ladder starts at rung zero: no cache until a measurement shows a repeated expensive read — a cache is a consistency liability, so it must earn its place.

Rung one is in-process Caffeine: reads cost well under a microsecond with no network hop, but every one of my 30 instances holds its own copy, which means up to 30× the fill traffic against the source, per-node inconsistency between fills, and the data must fit comfortably in each heap.

That suits small, hot, read-mostly data where node-to-node staleness is harmless.

Rung two is shared Redis: roughly half a millisecond to a millisecond per access over the network plus serialization cost, but one consistent copy for the fleet, capacity beyond any heap, and warmth that survives my deploys — worth it when the data is big, the fill is expensive, or instances must agree.

For scale, a typical primary-key database read is 5–10 ms, so both rungs are big wins; the ladder decides which liabilities you take on.

Layering both — Caffeine in front of Redis — I do only with an invalidation channel such as Redis pub/sub, because two cache layers means two staleness problems.

Land it Caffeine buys nanoseconds and costs consistency; Redis buys consistency and costs a network hop — I pick the rung whose costs the use case can actually afford, and no rung at all until a measurement demands one.

Likely follow-ups
"How do you size a Caffeine cache, and what happens when you get it wrong?"

By the working set, not by the total data. I start with hit ratio measured against a few candidate sizes in a replay of production keys, or simply deploy with recordStats() and watch hitRate() and evictionCount() as I adjust maximumSize.

When entries vary in size I use maximumWeight with a weigher that returns approximate bytes.

Too small shows as a high eviction count with a hit ratio that climbs steeply when I add capacity; too large shows as heap pressure, longer garbage collection pauses, and eventually an OutOfMemoryError, because Caffeine holds strong references by default.

The safety net is a heap budget: a cache should be a modest fraction of the heap, say under 20 percent, and I confirm with a heap histogram, jcmd <pid> GC.class_histogram, that the cached value class is where I expect it to be.

"With 30 instances each holding a Caffeine copy, how do you keep them from disagreeing for long?"

With a short TTL as the floor and an invalidation broadcast as the accelerator. The TTL bounds the disagreement: with expireAfterWrite(60, SECONDS) no node serves data older than a minute.

The broadcast shrinks the usual case: on a write, the writing instance publishes the key on a Redis pub/sub channel or a Kafka topic, and every instance's subscriber calls cache.invalidate(key), so the fleet converges within milliseconds.

Pub/sub is fire-and-forget, so a message can be missed by an instance that was reconnecting, which is why the TTL stays.

I verify convergence with a metric: each instance stamps cached values with their load time, and I alert if the age at serve time ever exceeds the TTL, which would mean expiry is misconfigured.

"What are the failure modes of Redis as a cache that Caffeine does not have?"

Network and serialization ones. A Redis call can time out, so every cache read needs a short timeout, around 50 to 100 milliseconds, and a fallback to the source, otherwise a slow cache makes every request slow.

Serialization is CPU and a compatibility contract: a change to the cached class can make old entries undeserializable after a deploy, so I version keys with the class version or use a schema-tolerant format such as JSON with unknown fields ignored.

Hot keys concentrate on one shard, so a single very popular key can saturate one Redis node while others idle. Eviction policy matters too: maxmemory-policy allkeys-lru for a pure cache, because the default noeviction turns a full cache into write errors.

And a Redis outage is a stampede on the database unless the client degrades gracefully.

"What would you cut from the two-layer design under time pressure?"

The Caffeine layer. Under time pressure I ship Redis alone with a TTL, because it is one consistency model, one invalidation path, and one metric to watch, and it already removes the expensive database read.

The in-process layer is an optimization that buys sub-millisecond reads at the price of a second staleness problem and an invalidation channel that has to be built, tested, and monitored.

I would keep a note that the Redis round trip is roughly a millisecond per access, and revisit the local layer only when a profile shows Redis latency or bandwidth on the critical path.

The one exception is a tiny, essentially static dataset such as feature flags or configuration, where a local cache with a 30-second TTL and no invalidation is simpler than Redis in the first place.

Q284. "TTL expiry or explicit invalidation — which do you trust, and what question do you ask the business first?"

Reveal answer

Strong answer The first question is never technical: it is "how stale is this data allowed to be?" — because a cache is a promise to serve old data, and only the business can price that.

A product description stale for five minutes is free; an account balance stale for five seconds may be an incident.

A TTL — time to live, the duration an entry may be served before it expires — is simple and self-healing: the worst case is bounded staleness, and bugs fix themselves at expiry.

Explicit invalidation gives freshness but is famously one of the two hard problems: every write path must remember to invalidate, a missed path means unbounded staleness, and in a distributed system the delete can race a concurrent read that then re-populates the cache with the old value.

My honest practice: choose the TTL from the business's staleness tolerance, add explicit invalidation only on the writes where freshness genuinely matters, and keep the TTL on anyway as the safety net under the invalidation I will inevitably miss somewhere.

Land it TTL bounds your worst case and invalidation improves your average case — run both, and let the business, not the engineer, set the staleness number.

Likely follow-ups
"Walk me through the race where delete-then-read repopulates stale data, and how you close it."

The sequence is: request A misses the cache and reads the old value from the database; request B writes the new value to the database and deletes the cache key; then A, which was slow, writes its stale old value into the cache, where it now lives for a full TTL. The window is narrow but real under load. Closing it: write the cache entry with a compare-and-set that includes a version, for example the row's updated_at or a version column, and refuse to overwrite a newer version with an older one; or use a delayed double delete, where the writer deletes the key, commits, and deletes again half a second later to catch the straggler; or lease-based fills, where a miss takes a short lease token and the fill only lands if the lease is still valid. The version approach is the one I trust, because it is correct rather than probabilistic.

"Should invalidation happen before or after the database commit?"

After the commit, and reliably.

Invalidate before the commit and a concurrent reader refills the cache with the pre-commit value; invalidate after the commit inside the same request and a crash between the two leaves the cache stale for a full TTL. The dependable version is to make the invalidation part of the transaction's outcome: in Spring, a @TransactionalEventListener(phase = AFTER_COMMIT) that publishes the invalidation, or, for stronger guarantees, an outbox row written in the same transaction that a relay turns into a cache-invalidation message.

I never invalidate on rollback. And I keep the TTL as insurance regardless, because "after commit, reliably" is still only as reliable as the message delivery path.

"How do you choose the TTL number itself for a given kind of data?"

From two numbers the business and the data give me. The staleness tolerance is the ceiling: if the product owner says a price may be wrong for at most 60 seconds, the TTL cannot exceed 60.

The re-access interval is the floor for usefulness: if the same key is typically requested every 20 seconds, a 10-second TTL misses almost every time and the cache does nothing.

Between those I pick the value that gives an acceptable hit ratio, which I measure by deploying with stats on and comparing hit ratio at a few candidates.

I add 10 to 20 percent random jitter to whatever I pick so keys do not expire in waves. And I write the number down next to its reason, because a TTL without a stated reason gets copied into the next cache unexamined.

"What would you do differently if you were designing the caching layer from scratch today?"

I would put the invalidation contract in the data layer, not in the callers. Every write to a cacheable aggregate goes through one repository method that commits and then emits a versioned change event, and every cache fill records the version it loaded.

That gives both TTL and invalidation for free to every consumer, and the version check makes the delete-then-read race impossible by construction.

I would use Caffeine's refreshAfterWrite for hot keys so they never expire in a caller's face, and I would size every cache with a heap budget from day one.

And I would measure the staleness actually served, by comparing the served version to the current version on a sampled basis, so the business gets a real number rather than a theoretical bound.

Q285 · Scenario. "Every ten minutes, like clockwork, the database gets hammered and latency spikes. You find a popular cache key with a ten-minute TTL. Explain the mechanism and your fixes."

Reveal answer

Strong answer This is a cache stampede. The hot key expires, and in that instant every concurrent request misses together — five hundred callers all run the same expensive query at once, the database saturates, queries slow down, which keeps the cache empty longer and stacks up even more concurrent fills. The periodicity is the tell: spikes aligned to the TTL, with the slow-query log full of one identical statement. Fixes, layered:

  1. Jitter the TTLs — ten minutes ± a random 10–20% — so many keys stop expiring in synchronized waves. Necessary, but it does not save a single very hot key.
  2. Single-flight the fill: only one caller computes the value per key while the rest wait for that result. Caffeine's loading cache does this per key natively; with Redis I take a short lock (SET key NX PX with a token) so exactly one instance refills while others serve the stale value or wait briefly.
  3. Refresh ahead: renew the entry before it expires while still serving the old value — Caffeine's refreshAfterWrite — so the hot key simply never goes empty under traffic.

Prevention: alert on cache-miss rate spikes and on that key's fill duration, because a stampede gets worse precisely when the underlying query gets slower.

Land it Expiry is a synchronization event — jitter breaks the synchronization across keys, single-flight caps concurrency per key at one, and refresh-ahead means the hottest keys never expire in anyone's face at all.

Likely follow-ups
"You added jitter and the spikes persist, just less regular. What next?"

Then it is one very hot key rather than a wave of many keys, and jitter cannot help a single key.

I confirm by looking at the slow-query log during a spike: if it is hundreds of copies of the same statement with the same parameters, that is a single-key stampede. The fix is single-flight per key.

With Caffeine, cache.get(key, loader) already guarantees one loader per key while the others wait.

With Redis, I take a short lock with SET lock:{key} token NX PX 5000; the winner recomputes and writes the value, the losers either wait a few hundred milliseconds and retry the cache read, or serve the previous value if I keep a soft-expired copy.

I would also check whether the value is expensive because the query is unindexed, since a 2-second fill is the root of a bad stampede.

"How does Caffeine's refreshAfterWrite actually behave, and where does it fall short?"

With refreshAfterWrite(8, MINUTES) and expireAfterWrite(10, MINUTES), an entry older than eight minutes is still returned immediately on the next read, and that read triggers an asynchronous reload through the CacheLoader.asyncReload method on the cache's executor; the old value serves until the new one arrives.

It falls short in two ways. First, refresh is triggered by a read, so a key that nobody reads between minutes eight and ten expires normally and the next reader pays a full miss; refresh-ahead only helps keys that are hot.

Second, a failed reload logs a warning and keeps the old value, which is usually desirable, but it means an outage of the source makes the cache silently stale beyond the refresh interval until hard expiry, so I alert on reload failures via stats().loadFailureCount().

"What is the equivalent protection at the Redis layer with multiple instances?"

Probabilistic early expiration or a lock. The lock version I described uses SET NX PX.

The probabilistic version, sometimes called XFetch, has each reader recompute early with a probability that rises as the entry nears expiry, scaled by how long the recompute takes; it needs no lock and spreads the refresh across instances.

Practically, I store the value with its logical expiry and a small delta in the same hash, and a reader whose random draw falls inside the window recomputes and rewrites. Both approaches serve the old value during the recompute.

The lock is simpler to reason about; the probabilistic approach avoids the failure mode where the lock holder dies and everyone waits for the lock's expiry. I pair either with a hard TTL so nothing lives forever.

"What breaks at 10 times the traffic even with all three fixes in place?"

The miss path for cold keys and the fill duration.

Single-flight caps fills at one per key, but with 10 times the traffic there are more distinct keys becoming hot, so the database sees ten times the fill rate for the long tail, and if that tail is unindexed, the database saturates on tail fills rather than on the hot key.

The waiting side also grows: a thousand callers waiting on one fill for a 2-second query all hold a request thread, so a slow fill under single-flight becomes a thread-pool exhaustion problem.

The answers are a bulkhead on the fill path, a timeout on the wait with a stale-if-available fallback, and, structurally, making the underlying query fast enough that a fill costs tens of milliseconds, at which point stampedes stop mattering.

Q286 · Scenario. "The team added Redis caching and declared victory, but the hit ratio is 30%. What do you investigate, and is this cache even helping?"

Reveal answer

Strong answer First I make the number trustworthy — Caffeine's recordStats() or Redis's keyspace_hits/keyspace_misses — and then I ask why 70% of lookups find nothing. The usual causes, in the order I check them:

  1. Keys too fine-grained: a key like user + filter + sort + page explodes into millions of combinations, most requested exactly once. A key that never repeats can never hit — I look at key cardinality versus request volume, and coarsen: cache the shared expensive sub-result (the product data), not the personalized final response.
  2. TTL shorter than the natural re-access interval: if callers return every 15 minutes and the TTL is 5, every visit misses. Compare TTL to observed re-access times.
  3. Cache too small for the working set: entries evicted before their second use — the eviction counter tells this story immediately.

And I answer the "is it helping" question with a measurement, not sentiment: at 30% hits, 70% of requests pay the Redis round trip and serialization plus the database query. I compare endpoint p95 with the cache bypassed; a cache like this can genuinely be net negative, and celebrating it because "we have caching now" is how it survives.

Land it A hit ratio is a design report card — fix key granularity, TTL, and sizing, and if the p95 with the cache off is not clearly worse, delete the cache and keep the simplicity.

Likely follow-ups
"How do you actually measure key cardinality and re-access interval from a live Redis?"

Without scanning the whole keyspace in production.

For cardinality, INFO keyspace gives the total key count per database, and a sampled SCAN with a pattern gives the count per key family, which I compare to request volume; a million keys for a hundred thousand requests a day means most keys are written once and never read.

For re-access, I turn on the client-side metrics: a Micrometer counter per key family for hits and misses, and, for a sample of keys, OBJECT IDLETIME key, which returns seconds since the key was last touched; a histogram of idle times against the TTL tells me instantly whether the TTL is shorter than the typical gap between visits.

The redis-cli --hotkeys and --memkeys tools give the same picture offline from a replica.

"You coarsened the keys and the hit ratio jumped to 85 percent, but p95 barely moved. Why?"

Because the hit ratio was never the metric that mattered; the latency of the cached path and what the cache actually saved were.

Possibilities: the cached sub-result was cheap all along and the real cost was elsewhere, such as serialization of a large personalized response or a second uncached query; the Redis round trip plus deserialization of a big value is nearly as slow as the database read it replaced, common when values are hundreds of kilobytes; or the p95 is dominated by the 15 percent of misses, which now take longer because the coarser value is bigger to build.

A trace with spans for the cache call, the database call, and serialization separates these in one request. If the cache saves 3 milliseconds per hit at a cost of 1 millisecond per call, it is real but small, and I say so.

"How do you run the 'cache bypassed' comparison safely in production?"

As a controlled experiment, not a flag flip.

I add a bypass switch keyed by a small percentage of requests, chosen by a hash of the request ID so the same user sees consistent behavior, and I start at 1 percent so the database sees a negligible load change.

I record endpoint latency tagged with the bypass flag and compare p50, p95, and p99 over an hour, plus database CPU and query rate. If the database can absorb it I step up to 10 percent.

The comparison must run at the same time of day as normal traffic, because a cache's value depends on the concurrency it deflects.

If the bypassed p95 is within noise of the cached p95, the cache is not earning its complexity and I remove it; if it is clearly worse, I have a number for the design review.

"When is a 30 percent hit ratio actually fine?"

When the hits are expensive and the misses are cheap. If the cached operation is a 500-millisecond aggregation, saving it on 30 percent of requests removes 150 milliseconds from the average and the cache is an obvious win even though it misses most of the time.

It is also fine when the cache's purpose is protection rather than speed, for example absorbing a hot key that would otherwise take the database down during a spike, where the hit ratio during the spike is what matters, not the daily average.

The number to look at is saved time per request, hit ratio times miss cost, minus cache overhead per call.

A 30 percent hit ratio with a 2-millisecond miss cost and a 1-millisecond Redis call is net negative; the same ratio with a 500-millisecond miss cost is excellent.

Q287. "What is negative caching, when do you need it, and how can it hurt you?"

Reveal answer

Strong answer Negative caching means caching the absence of a thing — storing "user 123: not found" so the next lookup for it is a cache hit instead of a database query.

You need it because misses for nonexistent keys bypass a normal cache entirely: crawlers, retry loops, typos, and attackers probing IDs generate floods of lookups that all fall through to the database — the cache-penetration pattern — and no positive cache helps, because there is nothing to cache.

The harm is poisoning by staleness or by bugs: cache "not found" and then the item is created a second later, and you serve 404s for real data until the negative entry dies; a bug or an attacker that plants wrong negatives makes existing data invisible.

Discipline: give negative entries a much shorter TTL than positives — seconds, not minutes; invalidate the negative entry on the create path explicitly; and bound the negative cache's size separately so a flood of junk keys cannot evict your real entries.

Land it Cache the "no" as well as the "yes", but make the "no" expire fast and die on create — a stale positive shows old data, a stale negative makes real data vanish, and the second is worse.

Likely follow-ups
"How do you implement negative entries in Caffeine and in Redis without confusing them with real values?"

With a sentinel and separate policies.

In Caffeine, a Cache<Long, Optional<User>> where Optional.empty() is the negative entry works, but a single cache has a single expiry, so for a shorter negative TTL I either use a second cache dedicated to misses with its own expireAfterWrite and maximumSize, or a custom Expiry implementation that returns a short duration when the value is empty and a long one otherwise.

In Redis, I store a reserved sentinel string such as __NULL__ with its own EX of a few seconds, and the client maps that string back to "not found" before returning.

The sentinel must be something the real value type cannot produce, and the deserializer must check for it before parsing, or a real payload that happens to be empty gets misread.

"Cache penetration by an attacker probing random IDs: does negative caching alone stop it?"

No, because random IDs never repeat, so every probe is a fresh miss and negative entries never get hit. Negative caching helps against repeated misses; against unique misses I need a filter that rejects impossible keys before they reach any cache.

A Bloom filter, a compact probabilistic set that answers "definitely not present" or "possibly present", built from the existing IDs and refreshed periodically, lets me reject the overwhelming majority of probes in memory with no database call. Guava and Redis modules both provide one.

On top of that, rate limiting per client on the lookup endpoint, and validation of the ID format so malformed keys are rejected at the edge. Negative caching then handles the legitimate case of a deleted or not-yet-created item being asked for repeatedly.

"Why is a stale negative worse than a stale positive? Convince me."

Because of what the user experiences and how the bug is found. A stale positive serves yesterday's product description; the page renders, the user rarely notices, and it self-corrects at expiry.

A stale negative tells the user their newly created order does not exist, the client shows an error or a 404, and support gets a ticket.

It also breaks flows that create and then immediately read, which is exactly the pattern of every form submission followed by a redirect to the detail page.

And it is harder to diagnose, because the database clearly has the row, the code path looks correct, and the answer lives in a cache entry that expired before anyone looked.

That asymmetry is why I give negatives a TTL measured in seconds and invalidate them explicitly on every create path.

"How would you bound the size of the negative cache separately, and what number would you pick?"

With its own maximumSize in Caffeine, or in Redis with a key prefix and a short TTL so the volume is self-limiting.

The number comes from the miss rate times the negative TTL: if legitimate misses arrive at 200 per second and the negative TTL is 10 seconds, the steady state is about 2,000 entries, so I would cap at, say, 10,000 to allow bursts, which is a few megabytes.

The cap is a defense against a flood of junk keys, not a tuning knob; under a flood, the negative cache fills, starts evicting, and the flood falls through to the Bloom filter and rate limiter, while the positive cache, sized separately, is untouched.

I put the negative cache's eviction count and size on the dashboard, because a sudden rise there is often the first sign of a probing attack.

Q288 · Scenario. "The recommendations service went down slow — 60-second responses — and suddenly your entire API returned errors, including endpoints that never call recommendations. Post-mortem it."

Reveal answer

The real test Whether you know the three distinct timeouts by name, know the defaults are broken, and can explain the thread-starvation chain.

Strong answer The chain: the HTTP client calling recommendations had no read timeout — several classic Java clients default to infinite — so each calling thread blocked in a socket read for the full 60 seconds.

Tomcat has around 200 request threads; at even a modest call rate they were all parked on that one dependency within a minute, and every unrelated endpoint then failed for lack of a thread.

A thread dump during the incident would show the signature: nearly every worker thread blocked in a socket read against the same host. The fix is to configure all three timeouts, which do different jobs:

  1. Connect timeout — how long to wait to establish the TCP connection; fails fast on a dead host. Around 1 second.
  2. Read (response) timeout — the maximum silence while waiting for data; this is the one that was missing. Set from the dependency's p99 plus margin — for example 2 seconds — never from hope.
  3. Pool-acquire timeout — how long to wait to borrow a pooled client connection; if infinite, pool exhaustion masquerades as hanging requests. A few hundred milliseconds.
RestClientConfig.java
var settings = ClientHttpRequestFactorySettings.defaults()
    .withConnectTimeout(Duration.ofSeconds(1))   // TCP establishment
    .withReadTimeout(Duration.ofSeconds(2));     // max silence on the socket
RestClient client = RestClient.builder()
    .requestFactory(ClientHttpRequestFactories.get(settings))
    .build();
// and on the pooling connection manager, never leave the
// pool-acquire wait infinite:
// requestConfig.setConnectionRequestTimeout(Timeout.ofMillis(500));

Prevention: every remote call gets explicit timeouts in code review, each timeout shorter than what our own callers give us, and a bulkhead or circuit breaker so one dependency cannot claim every thread again.

Going deeper Two things to keep current as of Aug 2026.

First, the Spring API: ClientHttpRequestFactories and ClientHttpRequestFactorySettings were deprecated in Spring Boot 3.4 in favor of ClientHttpRequestFactoryBuilder, and Boot 3.4 and later also expose the same three timeouts as properties, so a service can set spring.http.client.connect-timeout=1s and spring.http.client.read-timeout=2s and have every auto-configured RestClient inherit them.

Second, the fourth timeout: a read timeout bounds silence between bytes, not the whole exchange, so a server that trickles one byte every second never trips it.

For a true deadline I add a per-call overall timeout, either the client's own request-level timeout where supported, or an orTimeout on the async call, or a Resilience4j TimeLimiter.

The verification for the whole configuration is a test that points the client at a socket that accepts and never responds, and asserts the call fails within the configured budget.

Land it A missing timeout converts someone else's slowness into your outage — the read timeout is the contract that says how long their problem is allowed to be my problem.

Likely follow-ups
"You set all three timeouts and the outage recurred. What was still missing?"

The concurrency bound. Timeouts shorten how long each thread is stuck; they do not limit how many threads can be stuck at once.

If the dependency now takes 2 seconds instead of 60, and 200 threads each call it at 100 requests per second, Little's law says 200 threads are still occupied, which is the whole pool.

So the second layer is a bulkhead: a Semaphore or Resilience4j Bulkhead with, say, 20 permits around that call, so at most 20 threads can be inside it.

The third layer is the circuit breaker, so after the failure rate crosses a threshold the calls stop entirely and fail in microseconds.

A thread dump during the recurrence tells me which layer is missing: 200 threads blocked for 2 seconds each in the same socket read means the timeout worked and the bulkhead is absent.

"How do you choose the read timeout number without guessing?"

From the dependency's measured latency distribution and my own budget.

I pull the p99 and p99.9 of successful calls to that dependency from the last two weeks, say 400 and 900 milliseconds, and set the read timeout a bit above the p99.9, so 1 to 1.5 seconds, which cuts off only the genuinely pathological calls.

Then I check the constraint from above: my own callers give me perhaps 3 seconds, and I make two dependent calls, so the sum of my timeouts plus processing must fit inside 3 seconds, which may force a tighter number.

If the two constraints conflict, the design is wrong, not the timeout; I need a cache, a fallback, or a shorter chain. The number gets a comment with both figures, and a dashboard shows how often it actually fires.

"How would you have caught this before it became an incident?"

Three ways.

A static check: a build-time rule, ArchUnit or a custom Error Prone check, that fails on any RestClient, RestTemplate, WebClient, or HttpClient constructed without an explicit timeout configuration; I have seen teams do this with a wrapper factory that is the only permitted way to create a client.

A chaos test: a staging exercise where the recommendations stub is made to hang, with a pass criterion that unrelated endpoints keep their p99 within budget.

And a metric: Tomcat's busy-thread gauge, tomcat.threads.busy, alerting at 80 percent of server.tomcat.threads.max, because threads filling up is the early signal in this failure, minutes before the first 503.

"What would you cut under time pressure, the timeout, the bulkhead, or the breaker?"

The breaker, then the bulkhead, never the timeout. The read timeout is a one-line configuration change and it removes the unbounded case, which is the difference between a degraded feature and a dead service; it ships in the first hour.

A bulkhead is a semaphore around one call, maybe ten lines, and it ships the same day.

The circuit breaker needs a library, thresholds tuned to the dependency's normal failure rate, a fallback that makes sense, and tests for the half-open behavior, so it is the one I schedule rather than rush, because a badly tuned breaker that trips on a normal error rate causes its own outage.

The order of value per hour of work is timeout, bulkhead, breaker, and that is the order I ship them.

Q289. "Why does HTTP connection reuse matter so much for service-to-service calls, and what breaks when teams forget it?"

Reveal answer

Strong answer A fresh HTTPS connection pays a TCP handshake — one network round trip — plus a TLS handshake (Transport Layer Security, the encryption layer), which costs another round trip or two and real CPU for the key exchange.

Depending on network distance that is 10 to 100 milliseconds of tax before the first request byte, on every single call.

Keep-alive plus a client connection pool — Apache HttpClient's pooling connection manager with sensible maxTotal and per-route limits — pays it once and reuses the warm connection for thousands of requests.

When teams forget, the symptoms are distinctive: latency that is always "base plus a fixed 30–80 ms", surprisingly high CPU attributed to TLS, and under load, ephemeral-port exhaustion with piles of connections in TIME_WAIT. The operational trap worth naming: the server closes idle connections on its own keep-alive timeout, and a client that reuses a connection the server just closed gets stale-connection errors — so evict idle client connections slightly earlier than the server does, and enable validate-after-inactivity.

Land it Handshakes are a per-connection cost, so the whole game is amortization — pool the connections, and align the client's idle eviction just inside the server's, or reuse itself becomes a new error source.

Likely follow-ups
"What are the actual numbers you set on the pooling connection manager, and why?"

For Apache HttpClient 5, four settings.

setMaxTotal and setDefaultMaxPerRoute: the per-route limit is the important one, because the default of 5 per route silently serializes calls to a busy dependency; I set it from Little's law, call rate times p99 latency plus headroom, for example 100 per second times 0.2 seconds gives 20, so 40.

setConnectionRequestTimeout around 500 milliseconds so a full pool fails fast rather than hanging. setValidateAfterInactivity around 1 to 2 seconds so a connection idle longer than that is checked before reuse.

And an idle eviction, evictIdleConnections(Timeout.ofSeconds(30)), set below the server's keep-alive timeout, which for Tomcat defaults to 60 seconds and for many load balancers is similar. I read the server's number rather than assume it.

"How do you diagnose 'NoHttpResponseException' or connection reset errors at low frequency?"

That signature is almost always a reused connection the server or a middlebox had already closed. The server closes idle connections at its keep-alive timeout; the client, unaware, sends the next request on a dead socket and gets no response or a reset.

I confirm by correlating: the errors cluster on the first request after an idle gap, and the gap matches the server's keep-alive timeout.

The fix is to evict idle connections from the client pool slightly before the server does, and to enable validate-after-inactivity so a connection idle for more than a second or two is checked before reuse.

Retrying idempotent requests once on this specific exception is also reasonable, and Apache's default retry strategy does exactly that for requests that never reached the server.

"Where does TIME_WAIT come from, and how do you see it?"

TIME_WAIT is the state a TCP socket sits in for about 60 seconds after the side that closed first finishes, so that stray packets from the old connection cannot be confused with a new one.

If my client opens and closes a connection per request at 500 requests per second, that is 30,000 sockets in TIME_WAIT, and each consumes an ephemeral port on the client, of which Linux has about 28,000 by default in net.ipv4.ip_local_port_range.

When they run out, new connections fail with "cannot assign requested address". I see it with ss -s or ss -tan state time-wait | wc -l on the host.

The real fix is connection reuse; the kernel knobs such as tcp_tw_reuse are a stopgap that treats the symptom.

"Does the JDK's own HttpClient pool connections, and does it need the same care?"

Yes, java.net.http.HttpClient keeps a connection pool internally, with keep-alive for HTTP/1.1 and one multiplexed connection per host for HTTP/2, so a single shared instance gets reuse for free; the classic mistake is creating a new HttpClient per request, which discards the pool every time.

The knobs are fewer and mostly system properties: jdk.httpclient.keepalive.timeout, defaulting to 30 seconds as of recent JDKs, controls idle eviction, and jdk.httpclient.connectionPoolSize caps the pool, with zero meaning unbounded. There is no per-route limit, so the bound on concurrency has to come from my own semaphore.

As of Aug 2026 it also has no built-in validate-after-inactivity, so the idle timeout is what keeps it from reusing a server-closed socket.

Q290. "What does HTTP/2 multiplexing actually buy you — the honest version, not the conference-talk version?"

Reveal answer

Strong answer Multiplexing means many concurrent request/response streams share one TCP connection, so requests no longer queue behind each other at the HTTP layer the way HTTP/1.1 forces — with HTTP/1.1 a connection handles one request at a time, so concurrency means many connections, each with its own handshake and socket.

HTTP/2 also compresses headers. The honest accounting: the win is real when you make many small concurrent calls to the same host — fan-out APIs, gRPC (which is built on HTTP/2) — because you get high concurrency over few warm connections.

It does nothing for one large sequential call, and it does not remove head-of-line blocking at the TCP layer: one lost packet still stalls every stream on the connection, which is the problem HTTP/3 over QUIC addresses.

And for internal service-to-service traffic that already runs a warm HTTP/1.1 connection pool on a clean network, the measured gain is often modest — so I treat it as a measurement question, not an upgrade ritual.

Land it HTTP/2 is concurrency over fewer connections — a clear win for chatty fan-out and gRPC, a shrug for big sequential transfers over an already-warm pool, and only a benchmark tells you which one you are.

Likely follow-ups
"How would you benchmark HTTP/1.1 versus HTTP/2 for your own service-to-service traffic?"

With the real client library, the real payload sizes, and a realistic concurrency, not a synthetic tool that hides the client's connection strategy.

I run the same fan-out workload twice against the same server, once with HttpClient.Version.HTTP_1_1 and a warm pool sized for the concurrency, once with HTTP_2, and record p50, p95, and p99 latency, connection count on the server, and CPU on both sides.

Three observations decide it: if the HTTP/1.1 pool was undersized, HTTP/2 wins by a mile because it removes queueing for a free connection, which is a pool-sizing problem in disguise; if the pool was sized well, the difference is usually small; and if the payloads are large, HTTP/2's per-connection flow control window can actually throttle throughput unless tuned.

I publish the numbers with the configuration so the decision is reproducible.

"What is TCP head-of-line blocking concretely, and how bad is it in a datacenter?"

TCP delivers bytes in order, so if one packet is lost, every byte after it, including bytes belonging to other HTTP/2 streams on that connection, waits in the receive buffer until the retransmission arrives, which takes at least one round trip.

In a datacenter with 0.2 millisecond round trips and packet loss around 0.01 percent it is nearly invisible.

Over the public internet or a lossy mobile network with 50 millisecond round trips and 1 percent loss, a single connection carrying 50 streams stalls all 50 on every loss, which can make HTTP/2 slower than several HTTP/1.1 connections.

That is the specific problem HTTP/3 fixes by running over QUIC, where each stream is retransmitted independently. So my honest rule is: HTTP/2 inside the datacenter, and measure before choosing between 2 and 3 at the public edge.

"What does HTTP/2 change about connection pool sizing and about thread usage?"

The pool shrinks to about one connection per host, and the concurrency limit moves to the server's advertised SETTINGS_MAX_CONCURRENT_STREAMS, commonly 100 or 128 per connection.

If I need more concurrent calls than that to one host, the client must open a second connection, and not every client does that automatically, so a fan-out that exceeds the stream limit queues silently.

Thread usage does not change by itself: a blocking call on HTTP/2 still parks a thread for the duration. What changes is failure blast radius, because one connection reset now fails a hundred in-flight requests at once, which is the opposite of the connection-per-request world.

So I keep a small number of connections rather than exactly one, and I make sure the retry policy handles a burst of simultaneous failures without a storm.

"For gRPC specifically, what do you have to configure that people forget?"

Keep-alive and load balancing.

gRPC holds long-lived HTTP/2 connections, so an intermediary such as a load balancer or NAT that drops idle connections leaves the client with a dead channel; the fix is client keep-alive pings, keepAliveTime and keepAliveTimeout on the channel builder, aligned with the server's permitKeepAliveTime so the server does not reject them.

Load balancing is the bigger surprise: a layer-4 load balancer sees one long-lived connection and pins all of a client's traffic to one backend, so scaling out the server does nothing.

The fix is client-side load balancing with a round-robin policy and DNS or service discovery that returns all backends, or a layer-7 proxy such as Envoy that balances per request. I also set maxInboundMessageSize deliberately, because the 4 MB default surprises teams that send large batches.

Q291. "When would you turn response compression on, and when is it actively a mistake?"

Reveal answer

Strong answer Compression trades CPU and a little latency for fewer bytes on the wire.

It wins when payloads are large and the network is slow or metered: JSON is repetitive text and gzip typically shrinks it 5–10×, so a 400 KB response to a mobile client over the public internet is an easy yes — the transfer-time saving dwarfs the compression cost.

It is a mistake in two cases. First, small payloads: compressing a 300-byte response saves almost nothing while paying CPU and header overhead on every request, which is why Spring's server.compression.min-response-size defaults to 2 KB — below the threshold, don't.

Second, already-compressed content — images, video, archives — where gzip burns CPU to save roughly zero bytes.

For internal service-to-service traffic on a 10-gigabit datacenter network, bandwidth is rarely the constraint and CPU often is, so I frequently leave compression off internally and enable it at the edge where responses cross the real internet.

Land it Compress where bytes are expensive and payloads are big — at the public edge — and skip it for small or already-compressed responses, where it is pure CPU tax.

Likely follow-ups
"How do you turn it on in Spring Boot, and how do you confirm it is actually happening?"

Three properties: server.compression.enabled=true, server.compression.min-response-size=2KB, and server.compression.mime-types, which defaults to text, XML, and JSON types and must include anything else I want compressed. The container then compresses only when the client sent Accept-Encoding: gzip and the response is above the threshold.

Confirmation is a request with curl -H 'Accept-Encoding: gzip' -sD - -o /dev/null and a look for Content-Encoding: gzip in the headers, plus Vary: Accept-Encoding, which must be present so caches keep compressed and uncompressed copies apart.

I also compare the body size with and without the header to see the actual ratio. A missing Vary header is the bug I look for first, because it makes a CDN serve gzip bytes to a client that cannot decode them.

"Where should compression live: the application, a reverse proxy, or the CDN?"

As close to the client as possible, and once.

If a CDN or edge proxy fronts the service, it should compress, because it has the spare CPU, can cache the compressed body, and can negotiate Brotli, which shrinks text 15 to 20 percent better than gzip; the application then sends plain bytes over the internal network where bandwidth is cheap.

Compressing in the application makes sense when there is no edge, or when the internal hop is genuinely slow, such as cross-region.

What I avoid is double compression: an application that gzips and a proxy that gzips again wastes CPU and produces a body the client cannot decode if the headers get mangled.

And I make sure the proxy does not silently decompress and recompress, which happens when it needs to inspect bodies for logging or security rules.

"What is the concrete CPU cost of gzip at the numbers you gave?"

gzip at its default level 6 compresses text at very roughly 50 to 100 megabytes per second per core in Java's Deflater, so a 400 KB JSON response costs around 4 to 8 milliseconds of CPU. At 1,000 such responses per second that is 4 to 8 full cores, which is real money and real latency.

Level 1 is two to three times faster with a modestly worse ratio, and is usually the right choice for dynamic responses; level 9 is much slower for a few percent better ratio and belongs to static assets compressed once at build time.

Decompression is cheap, several hundred megabytes per second. I measure it in a profile before and after enabling compression, because the Deflater frames are easy to spot, and I set the level explicitly rather than accepting the default.

"Is there a security concern with compressing responses?"

Yes, for responses that mix a secret with attacker-influenced content over TLS.

The BREACH attack lets an attacker who can inject text into a page and observe the compressed size infer a secret in the same response, such as a CSRF token, because compression shrinks more when the injected text matches the secret.

The defenses are: never reflect user input into a response that also contains a secret; randomize or mask per-request secrets, which modern CSRF implementations do; or disable compression on those specific endpoints.

For plain JSON APIs with bearer-token authentication and no reflected input, the risk is minimal, but I check the two conditions, secret plus reflection in the same body, before turning compression on for HTML pages.

Q292 · Scenario. "A profiler shows 35% of your service's CPU inside Jackson. You find new ObjectMapper() in a request-scoped helper. Explain the cost and your fixes."

Reveal answer

Strong answer ObjectMapper — Jackson's serializer object — does expensive reflective introspection of each class the first time it sees it, then caches that metadata for every later use.

Constructing a new mapper per request throws the cache away, so every request re-pays class introspection and floods the allocator with metadata objects; in a flame graph it shows up as exactly this — a fat tower of Jackson introspection methods.

The fix costs one line: share a single configured instance, which is thread-safe once configuration stops — in Spring, inject the auto-configured mapper instead of constructing one. With reuse in place, the same profile typically shows Jackson dropping from tens of percent to low single digits.

If serialization is still hot after that, the next steps are: serialize purpose-built DTOs instead of wide object graphs so there is simply less to write; prefer records, which serialize cheaply and predictably; and consider the Blackbird module (successor to Afterburner), which replaces reflective property access with generated code.

Each step gets verified the same way it was found — with the profiler, not by feel.

Land it ObjectMapper is designed to be built once and shared forever — per-request construction is the single most common self-inflicted serialization cost, and the fix is deleting a new.

Likely follow-ups
"You shared one ObjectMapper and Jackson is still at 20 percent of CPU. What is next?"

Then serialization is doing too much work per request rather than repeated setup. I look at what is being serialized: a flame graph grouped by the serialized class tells me whether one wide graph, often an entity with nested collections, dominates.

Fixes in order: return a purpose-built DTO with only the fields the response needs; avoid pretty-printing in production; ensure I am writing to the output stream rather than to a String first, which doubles the work and the allocation; and check for a custom serializer or a @JsonFilter that does reflective work per call.

If the shape is already lean, the remaining lever is the encoder: Jackson's Blackbird module replaces reflection with generated accessors, and for a hot internal endpoint a binary format such as Protobuf or CBOR cuts both CPU and bytes.

"What configuration on ObjectMapper is not thread-safe, and how do you handle per-request variations?"

Configuration methods such as configure, registerModule, setSerializationInclusion, and setDateFormat mutate the mapper and are not safe to call once it is in use. The mapper is thread-safe only for readValue, writeValue, and related calls after configuration is finished.

For per-request variation, Jackson provides cheap derived objects: mapper.writer() and mapper.reader() return immutable ObjectWriter and ObjectReader instances that share the mapper's caches, and I can call writer.with(feature) or writer.withView(View.class) to get a variant without touching the shared mapper.

So the pattern is one mapper configured at startup, held as a bean, and lightweight writers and readers derived per use case, which as of Aug 2026 is also the direction Jackson 3 took by making the mapper fully immutable after build.

"How much does Blackbird actually buy, and what are its risks?"

In Jackson's own and independent benchmarks, Blackbird typically speeds serialization and deserialization of plain beans by 20 to 40 percent by generating accessor code with LambdaMetafactory instead of reflective Field.get and Method.invoke calls. It is a drop-in module, mapper.registerModule(new BlackbirdModule()).

The risks are: it needs the classes it accelerates to be accessible from its generated code, which under the module system means opening packages or keeping DTOs public; some exotic features fall back to the reflective path silently, so the gain may be smaller than expected; and it adds one more thing that can break on a Jackson upgrade.

I measure with the same profile that found the problem and keep it only if the gain is visible in production CPU.

"How would you prevent per-request ObjectMapper construction from coming back?"

With a build-time rule and a runtime signal. The build rule is an ArchUnit test or an Error Prone check that fails on new ObjectMapper() outside a single configuration package, which is a few lines and catches it in the pull request.

The runtime signal is a JFR allocation profile in staging, because a new mapper per request shows up as a top allocator of Jackson internal classes such as SerializerCache; I keep a dashboard of allocation rate per request so a regression is visible as a step change.

And I make the correct path the easy path: the shared mapper is a bean, and utilities that need JSON take it as a constructor argument rather than building their own.

Code review catches the rest, and the profile that found this incident is attached to the review guideline.

Q293 · Scenario. "An endpoint returns JPA entities directly as JSON. It is fast in tests, but for one big customer it takes 6 seconds and fires hundreds of queries. Explain and fix."

Reveal answer

Strong answer The serializer walks the entire object graph of whatever it is given. Handed a live entity, it touches every mapped association — and each lazy one either fires a query at serialization time (with open-session-in-view enabled, silently) or throws LazyInitializationException (with it off).

The big customer has 5,000 order lines where the test fixture had three, so serialization becomes a hidden N+1 storm in the rendering phase, invisible in small-data tests.

Entities as API responses also leak internal columns the moment someone adds one, couple the wire contract to the schema so refactors break clients, and loop forever on bidirectional relations until someone patches it with annotation hacks.

The fix is the boundary rule: the web layer speaks DTOs only.

I project them in the query — JPQL constructor expressions or interface projections — so the database returns exactly the fields the response needs, the fetch shape is explicit, and nothing lazy exists to trigger.

@JsonView can filter fields on an entity, but it only hides output — the graph still gets walked — so it is the weaker tool. Prevention: an architecture test that no controller signature references an @Entity type.

Land it An entity is a database session artifact and a DTO is a wire contract — serializing the former hands your query plan to Jackson, and the big-customer incident is the invoice.

Likely follow-ups
"You switched to DTOs and the endpoint is still slow for that customer. What next?"

Then the query itself is the problem rather than serialization, and I check the SQL that the projection generates.

If the DTO includes a collection, such as order lines, a naive JPQL projection may still issue one query per order, so I look at the Hibernate statistics, hibernate.generate_statistics=true, and the query count per request; anything above a handful is a fetch problem.

The fix is either a single query with a join and manual grouping in Java, or two queries, one for the orders and one for all lines with an IN on the order IDs, which Hibernate can do with @BatchSize or a JOIN FETCH.

Then I check the response size: 5,000 lines is a large body, so pagination or a summary endpoint may be the honest fix. The rule is to count queries first, then bytes.

"What exactly does open-session-in-view do, and would you turn it off?"

Open-session-in-view, on by default in Spring Boot as spring.jpa.open-in-view=true, keeps the JPA persistence context open for the whole web request, including view rendering and JSON serialization, so lazy associations can be loaded after the service method's transaction has ended.

It hides LazyInitializationException, but at a cost: it turns serialization into a source of unplanned queries, and it holds a database connection for the entire request duration, including the time spent writing the response to a slow client, which shrinks the effective connection pool.

I turn it off in every new service, which makes lazy-loading bugs fail loudly in tests where they belong. Boot itself logs a warning at startup when it is left on by default, which is a clear signal of the framework authors' opinion.

"Write me the projection query for this case."

Two shapes. The constructor expression: select new com.shop.api.OrderSummary(o.id, o.createdAt, o.status, o.totalAmount) from Order o where o.customerId = :customerId, which requires a matching public constructor, and returns exactly four columns per row and no managed entities.

The interface projection: an interface OrderSummary with getters getId(), getCreatedAt(), and so on, and a repository method List<OrderSummary> findByCustomerId(Long customerId); Spring Data derives the select list from the getter names, and as long as the getters map to direct columns it is a closed projection with no extra queries.

For the lines, a second query select new ...LineSummary(l.order.id, l.sku, l.qty) from OrderLine l where l.order.id in :orderIds and grouping in Java. Both end up as plain records, which serialize cheaply.

"How do you write the architecture test that stops entities leaking into controllers?"

With ArchUnit, in about ten lines. Something like: noMethods().that().areDeclaredInClassesThat().areAnnotatedWith(RestController.class).should().haveRawReturnType(annotatedWith(Entity.class)), and a companion rule that no return type is a collection or ResponseEntity parameterized by an entity, which needs a custom condition that inspects generic type arguments.

A third rule forbids controller parameters of entity types, because binding JSON straight into an entity is the write-side version of the same leak. The test runs with the unit tests, so the pull request fails before review.

I also enforce the package direction: api may depend on service, but nothing in api may depend on domain.entity, which catches the leak even when someone wraps the entity in a new class.

Drill · Async, resilience & staying up

This group tests whether you know when concurrency actually buys latency, and whether you design services that degrade on purpose instead of collapsing by accident.

Q294. "When does going async actually make an endpoint faster — and when is it just complexity? Give me a worked example."

Reveal answer

Strong answer Async buys latency exactly when the work is independent and can overlap. My page endpoint needs a profile (80 ms), orders (120 ms), and recommendations (100 ms) from three separate services. Sequentially that is the sum — 300 ms. Fanned out with CompletableFuture — Java's handle to a result that will arrive later — it is the maximum: about 120 ms.

FanOut.java
// dedicated bounded pool — never the common pool for blocking I/O
ExecutorService pool = Executors.newFixedThreadPool(30);

CompletableFuture<Profile> profile =
    CompletableFuture.supplyAsync(() -> profileClient.fetch(id), pool);
CompletableFuture<List<Order>> orders =
    CompletableFuture.supplyAsync(() -> orderClient.fetch(id), pool);
CompletableFuture<Recs> recs =
    CompletableFuture.supplyAsync(() -> recsClient.fetch(id), pool);

CompletableFuture.allOf(profile, orders, recs).join();
// latency ≈ max(80, 120, 100) ≈ 120 ms, not 300 ms
return new PageDto(profile.join(), orders.join(), recs.join());

When it does not help: a dependent chain — call A, use its result to call B — has the same critical path async or not, and a single database call gains nothing by being wrapped in a future; you add thread hops, harder stack traces, and trickier error handling for zero latency. The other honesty: async does not create capacity — the same total work happens on some thread. It shortens latency for fan-out; freeing threads during waits is a different tool, namely reactive stacks or virtual threads. And blocking calls go on a dedicated bounded pool, never the shared ForkJoin common pool, so a slow dependency cannot starve everything else that uses it.

Land it Parallelize only what is independent — latency becomes the max instead of the sum — and leave sequential chains sequential, because complexity that buys no milliseconds is pure debt.

Likely follow-ups
"You said async does not create capacity. Then what do virtual threads or reactive actually change?"

They change what a waiting request costs. In the fan-out above, every in-flight call holds a platform thread for its duration, so 1,000 concurrent page requests need 3,000 threads, which is gigabytes of stack and heavy scheduling.

A virtual thread that blocks on a socket unmounts from its carrier and costs a few hundred bytes of heap while it waits, so the same 3,000 waits run on a dozen carrier threads.

Reactive stacks achieve the same by never blocking: the request is a chain of callbacks driven by a small event loop.

Neither makes the downstream faster or the CPU work smaller; they make waiting nearly free, which raises the number of concurrent requests a box can hold.

As of Aug 2026, with JDK 21 or later, virtual threads give that benefit with ordinary blocking code, which is why I reach for them before a reactive rewrite.

"Rewrite the fan-out with StructuredTaskScope and tell me what it fixes."

On JDK 25, where it is final: try (var scope = StructuredTaskScope.open()) { var profile = scope.fork(() -> profileClient.fetch(id)); var orders = scope.fork(() -> orderClient.fetch(id)); var recs = scope.fork(() -> recsClient.fetch(id)); scope.join(); return new PageDto(profile.get(), orders.get(), recs.get()); }. Each fork runs on its own virtual thread.

What it fixes: if one fetch throws, the default joiner cancels the other two and join throws, so no work leaks past the request; if the request thread is interrupted, for example by a timeout, every subtask is interrupted too; and the subtasks cannot outlive the try block, so the "abandoned HTTP call keeps running" problem disappears.

A deadline is scope.join() with a configured timeout on open. It reads like sequential code and is harder to get wrong than the allOf version.

"How do you prove the fan-out saved latency in production and not just in a benchmark?"

With a trace.

Each downstream call becomes a span, and in a tool like Jaeger or Tempo the three spans should visibly overlap under the parent span; if they are laid end to end, the fan-out is not happening, usually because something upstream is calling join() too early or the pool is saturated and the tasks queued.

Then I compare the endpoint's p50 and p95 before and after: the expected p50 drop is from roughly the sum to roughly the max, so 300 to 120 milliseconds in the example.

I also watch the pool's queue-depth metric, because a fan-out at 3 calls per request triples the pool's load and a pool that was fine at 1x can queue at 3x, which quietly puts the sum back.

Finally I check downstream error rates, because tripling concurrency can trip their rate limits.

"What breaks at 10 times the traffic with this fan-out?"

The 30-thread pool first.

At 10x, 3 calls per request at 120 milliseconds each and, say, 500 requests per second is 180 in flight, so a 30-thread pool queues six deep and the latency win vanishes; the fix is to size by Little's law or switch to virtual threads.

Next, the downstream connection pools and the downstreams themselves see 3x the calls they used to, so they need to be sized or bulkheaded per dependency.

Then tail latency: with three calls the chance of at least one slow one triples, so p99 degrades faster than p50.

And the failure blast radius grows: without per-branch fallbacks, any one of three dependencies failing fails the page, so the page's availability is the product of the three.

At 10x I would also add a short cache on recommendations, because it is the least personal and most expensive of the three.

Q295 · Scenario. "A downstream slowed for 20 minutes. Your service 'handled it' — no errors — then died with OutOfMemoryError. You find an unbounded work queue. Reconstruct the failure and redesign it."

Reveal answer

Strong answer The queue absorbed the imbalance instead of reporting it. Producers enqueued 500 items per second; the degraded consumer drained 200; the queue grew by 300 per second.

At a couple of kilobytes per item that is tens of megabytes a minute — the heap filled, garbage collection thrashed, and the process died.

Worse, most queued items were dead work: their callers had timed out long ago, so the service was burning memory to eventually perform work nobody was waiting for. "No errors" was the disease, not the success.

Backpressure is the cure: making the slowdown visible to whoever is sending work, instead of hiding it in memory. The redesign:

  1. Bound the queue — an ArrayBlockingQueue behind the executor, sized from Little's law: acceptable wait time × drain rate, not "big".
  2. Decide the full-queue policy explicitly: reject new work fast with 429 or 503 — failing in a millisecond is kinder than timing out in thirty — or apply CallerRunsPolicy to slow the producer down. Never the default unbounded growth.
  3. Shed load by value when saturated: drop the retry-able and the low-priority first, keep the checkout traffic.
  4. Cap total in-flight work with a semaphore so the bound holds end-to-end, and alert on queue depth and queue age — age tells you when you are queueing already-dead work.

Land it An unbounded queue converts a temporary latency problem into a fatal memory problem on a delay — a bounded queue that rejects early keeps the failure small, visible, and honest.

Likely follow-ups
"You bounded the queue and now the producer is a Kafka consumer that gets rebalanced. What happened?"

The bound worked and the backpressure landed on a thread that could not afford it.

With CallerRunsPolicy or a blocking put, the consumer's poll loop stops calling poll() while it waits; after max.poll.interval.ms, which defaults to five minutes, the broker assumes the consumer died, kicks it out of the group, and rebalances partitions, so records get reprocessed by another instance while this one is still working.

The right shape for a consumer is: pause the partitions with consumer.pause() when the local queue is above a high-water mark, keep calling poll() so the heartbeat and poll interval stay healthy, and resume() when the queue drains below a low-water mark.

That is backpressure expressed in Kafka's own vocabulary, and it holds the offset uncommitted until the work is done.

"How do you measure queue age, and why is it better than queue depth?"

Queue age is how long the oldest item has been waiting, which I get by timestamping each item at enqueue and recording the difference when a worker dequeues it, or by peeking at the head item's timestamp on a sampling schedule.

Depth tells me how many items are waiting; age tells me whether they are still worth doing.

A queue of 5,000 items draining in two seconds is fine; a queue of 50 items whose head has waited 40 seconds means every one of them has outlived its caller's timeout and the workers are processing garbage.

So I alert on age against the caller's timeout, and I go further: workers check the item's age before starting it and drop anything already past its deadline, which is cheap and immediately shrinks the dead work during a slowdown. Depth stays on the dashboard as a capacity signal.

"How would you shed load by value, concretely?"

Every item carries a priority when it is created, derived from the request, for example checkout and payment as high, search as medium, and analytics and recommendation refresh as low.

The queue is a PriorityBlockingQueue ordered by priority then enqueue time, but that alone is unbounded, so I wrap it with a semaphore for the bound, and the rejection handler drops the lowest-priority item present rather than the newest.

Under saturation, low-priority work is refused at intake with a fast 503 or simply skipped for items that are safe to lose, and the metrics show shedding by priority.

The subtle part is fairness within a priority: an item's time in queue must eventually count, or medium-priority work starves during a long high-priority burst, so I age items into a higher priority after a threshold.

"In a greenfield design, how would you avoid the in-memory queue altogether?"

By making the imbalance durable and visible instead of buffered in the heap.

The producer writes to a persistent log such as Kafka or a database outbox, which absorbs the temporary imbalance on disk with a retention window measured in hours, not in heap bytes; the consumer processes at its own pace and the lag, measured in messages and seconds, becomes the backpressure signal that dashboards and autoscalers act on.

If the caller needs a synchronous answer, the design instead fails fast at intake with a bounded in-flight count, using an admission semaphore, and returns 429 or 503 with Retry-After.

What I would not build is a large in-memory buffer between a synchronous caller and a slow downstream, because it combines the worst of both: the caller waits, the memory grows, and the work is often dead by the time it runs.

Q296. "What does a circuit breaker actually protect — and walk me through its states with Resilience4j."

Reveal answer

The real test Whether you know the breaker protects the caller, not the callee — most candidates get this backwards.

Strong answer A circuit breaker is a wrapper around calls to a dependency that stops calling it once it is clearly unhealthy.

The thing it protects is your service: when a downstream is failing or slow, every attempted call still costs you a thread parked for the full timeout, a pooled connection, and your caller's latency budget — the breaker converts those expensive slow failures into instant cheap ones.

It barely helps the downstream; that is a side effect.

The states: closed is normal operation while failure and slow-call rates are tracked over a sliding window; when a threshold trips, it goes open and calls fail immediately or take a fallback; after a wait it goes half-open, letting a small number of probe calls through — if they succeed it closes, if not it re-opens.

In Resilience4j that is a CircuitBreaker with failureRateThreshold(50), slowCallDurationThreshold and slowCallRateThreshold — slow counts as bad, which matters because slow is what eats threads — waitDurationInOpenState, and permittedNumberOfCallsInHalfOpenState. The fallback should degrade meaningfully: cached data, a default, a trimmed response.

Land it The breaker's job is to keep your threads out of a black hole — even with no fallback but a fast error, trading a 2-second failure for a 1-millisecond one keeps the rest of your service alive.

Likely follow-ups
"How do you choose the thresholds so the breaker does not trip on normal error rates?"

From the dependency's baseline.

I pull two weeks of its error rate and latency: if it normally runs at 2 percent errors and a p99 of 300 milliseconds, then failureRateThreshold(50) is comfortably above the noise and slowCallDurationThreshold(Duration.ofSeconds(1)) with slowCallRateThreshold(50) catches a real degradation without tripping on ordinary tails.

The window matters as much: slidingWindowType(COUNT_BASED) with slidingWindowSize(100) and minimumNumberOfCalls(20) means the breaker will not decide on fewer than 20 calls, so a low-traffic dependency does not trip on two failures.

I also decide which exceptions count with recordExceptions and ignoreExceptions, because a 404 or a validation error from the downstream is not a failure of the downstream. Then I watch the breaker's state-transition metric for a week before trusting it.

"The breaker is open but the dependency recovered minutes ago. Why, and how do you tune half-open?"

Because waitDurationInOpenState is the only clock that moves the breaker from open to half-open, and if it is set to five minutes, that is the minimum time to notice recovery.

In half-open, permittedNumberOfCallsInHalfOpenState, say 10, probe calls go through, and if their failure rate is under the threshold the breaker closes; if the traffic is low, those 10 calls can take a long time to arrive, so I set maxWaitDurationInHalfOpenState to bound it.

My tuning is: open duration of 10 to 30 seconds, which is fast to recover and slow enough not to hammer, and automaticTransitionFromOpenToHalfOpenEnabled(true) so the transition does not wait for a call to arrive.

I verify with the state-transition events Resilience4j publishes, plotted against the dependency's own health.

"What fallback do you return, and how do you stop the fallback from hiding the outage?"

The fallback should be the best answer I can give without the dependency, and it should be visibly a fallback.

For recommendations, that is a cached or popularity-based list; for pricing, there may be no safe fallback and the honest answer is a fast error for that one feature.

To keep the outage visible I do three things: count fallbacks as a metric tagged by dependency, and alert when the rate rises, because a silent fallback at 100 percent is an outage nobody is fixing; mark the response, for example a degraded: ["recommendations"] field or a header, so clients and support can see it; and never fall back on writes, where a fallback would mean pretending an order was placed.

The breaker keeps the service up; the metrics and the marking keep the humans honest about what is down.

"Where does the breaker sit relative to retries, timeouts, and the bulkhead?"

In Resilience4j's decorator order, from the outside in: retry, then circuit breaker, then rate limiter, then time limiter, then bulkhead, then the call.

Read from the call outward: the timeout bounds one attempt, the bulkhead caps how many attempts run at once, the breaker sees each attempt's outcome and can refuse the next, and the retry wraps the whole thing so a refused attempt from an open breaker counts as a failure and the retry backs off or gives up.

That ordering means an open breaker suppresses retries instead of retries hammering an open breaker, and slow calls bounded by the timeout are what feed the breaker's slow-call rate.

The annotation-based configuration applies this order automatically; with the functional API I compose the decorators in that order by hand and I write a test that asserts an open breaker results in exactly one fast failure per call.

Q297. "Explain bulkhead isolation and tie it to what you would see in a thread dump without it."

Reveal answer

Strong answer A bulkhead — named for the watertight compartments that keep one breach from sinking a whole ship — gives each downstream dependency its own bounded compartment of concurrency: a dedicated thread pool, or more cheaply a semaphore capping concurrent calls.

Without bulkheads, the incident signature in a thread dump is unmistakable: all 200 worker threads blocked in socket reads against one slow host, and every endpoint dead, including the ones that never touch that host.

With a 20-permit bulkhead on that dependency, at most 20 threads can be stuck there; the 21st caller fails fast with a bulkhead-full error, and the other 180 threads keep serving everything else.

In Resilience4j that is Bulkhead for the semaphore flavor — my default, since it adds no thread-hop cost — or ThreadPoolBulkhead when I want full pool isolation.

I size each compartment with Little's law from that dependency's own traffic: its call rate times its p99 latency, plus headroom.

Bulkheads pair with the circuit breaker: the bulkhead caps how much of me a bad dependency can hold at once, the breaker decides to stop calling it altogether.

Land it The bulkhead turns "one slow dependency drowned the service" into "one feature degraded while everything else stayed up" — which is the difference between an incident report and a footnote.

Likely follow-ups
"Semaphore bulkhead or thread-pool bulkhead: when does the thread pool version earn its cost?"

The semaphore version caps concurrency but the call runs on the caller's thread, so a slow dependency still holds one of my request threads for each permit, up to the permit count, which is fine when that count is small.

The thread-pool version runs the call on a dedicated pool and the caller waits on a future, which adds a thread hop but gives two things the semaphore cannot: a queue with its own bound for short bursts, and a hard timeout that returns the caller's thread even if the call ignores interruption, since the abandoned call only occupies the bulkhead's own thread.

It earns its cost when the dependency's calls cannot be reliably timed out, or when I need to isolate a dependency's CPU work from request threads.

As of Aug 2026, with virtual threads, a semaphore plus a virtual thread per call gets most of that benefit without the pool.

"How do you size the compartment, and what happens when it is too small?"

From the dependency's own traffic with Little's law: 50 calls per second times a p99 of 200 milliseconds is 10 in flight, so 20 permits gives 2x headroom.

Too small shows up as bulkhead-full rejections during ordinary peaks, which the metric resilience4j.bulkhead.available.concurrent.calls hitting zero makes obvious; I would rather see a few rejections at peak than size for the worst case and lose the protection.

The check is that the sum of all bulkheads is less than the total request threads, otherwise all dependencies going slow together can still exhaust the pool. With Tomcat's default of 200 threads and five dependencies, that means around 20 to 30 each.

A bulkhead sized at 150 for one dependency is not a bulkhead; it is the old outage with a smaller number.

"Walk me through the thread dump with a bulkhead in place versus without."

Without a bulkhead during the incident, jcmd <pid> Thread.print shows 200 threads named http-nio-8080-exec-N, nearly all in java.net.SocketInputStream.socketRead0 or its NIO equivalent, with the same HTTP client frames and the same host in the stack, and the Tomcat busy-thread gauge at maximum.

With a 20-permit semaphore bulkhead, the same dump shows exactly 20 threads in that socket read, a handful of threads in Semaphore.tryAcquire for a few milliseconds before failing fast, and the remaining 170 or so threads either idle in the pool's take() or serving other endpoints.

The bulkhead-full exception count rises in the logs, which is the visible signal that the compartment did its job. That difference in the dump is how I know in the first minute of an incident whether isolation held.

"What would you cut under time pressure: bulkheads on every dependency, or one on the risky dependency?"

One on the risky dependency, immediately, with a note to finish the rest.

The dependency that has already caused an incident, or the one with the worst p99 and the least ownership, gets a semaphore bulkhead that afternoon, because a single well-placed compartment removes the most likely repeat.

Then I add the others in order of risk over the following weeks, ideally through a shared client factory so each new dependency gets a bulkhead by default rather than by memory.

What I do not cut is the metric: a bulkhead without a rejection counter is a limit nobody can see, and the first time it rejects during a normal peak it will be blamed for an outage it prevented. Bulkhead, counter, alert, in that order, per dependency.

Q298. "What is your retry policy discipline — and show me the math for how retries turn an outage into a bigger outage."

Reveal answer

Strong answer Rules first: retry only idempotent operations — ones safe to repeat because doing them twice leaves the same result as once, like a GET or a PUT of the same body — and never blind-retry a POST that charges or creates.

Back off exponentially with jitter — 100 ms, 200, 400, each with a random offset — so a thousand failed callers do not return in one synchronized wave.

Cap attempts low, and enforce a retry budget: retries as a whole may not exceed some fraction, say 10%, of normal traffic.

The amplification math is the reason for all of it: three layers that each retry 3 times means one failing bottom-level call can be attempted 3 × 3 × 3 = 27 times.

A fleet doing 1,000 requests per second with naive triple retries hits a struggling dependency with 3,000–4,000 requests per second — at the exact moment it is trying to recover, guaranteeing it cannot. That is a retry storm, and it is self-inflicted.

So retries live at one layer only, sit behind the circuit breaker so an open circuit suppresses them entirely, and retry only on errors that can plausibly succeed on a second attempt — a timeout or a 503, never a 400.

Land it A retry is extra load aimed at something already failing — idempotent-only, jittered backoff, one layer, and a budget, or your resilience feature becomes the second wave of the outage.

Likely follow-ups
"How do you implement a retry budget, and what does Resilience4j give you out of the box?"

Resilience4j's Retry gives attempts, backoff with IntervalFunction.ofExponentialRandomBackoff(100ms, 2.0, 0.5) for jitter, and exception filters, but not a fleet-wide budget.

A budget is a token bucket shared across the service: each first attempt adds a fraction of a token, say 0.1, each retry spends one token, and a retry is only permitted if a token is available, which caps retries at 10 percent of first attempts over any window.

I implement it as a small class around Bucket4j or an AtomicLong with periodic decay, wired into the retry's predicate. Envoy and gRPC have this built in as retry budgets, which is a good reason to push retries into the service mesh when one exists.

The metric I export is retries permitted versus denied, because denied retries rising is the early sign of a dependency in trouble.

"Which HTTP status codes and exceptions do you retry, and which never?"

Retry: connection refused and connect timeouts, since nothing reached the server; 503 Service Unavailable and 429 Too Many Requests, honoring Retry-After; and 502 or 504 from a proxy.

Retry with care: a read timeout on an idempotent method, because the request may have been processed and the response lost, which is safe only for GET, PUT, and DELETE, or for a POST carrying an idempotency key.

Never: 400, 401, 403, 404, 409, and 422, because the same request will fail the same way; 500 is a judgment call, usually not, since a server bug does not fix itself in 200 milliseconds.

In code that is a predicate over the exception and status, and a single shared policy class so the rules are not re-invented per client with subtle differences.

"Show me the math for jitter: why does exponential backoff alone not prevent the wave?"

Suppose 1,000 clients fail at the same instant and each waits exactly 100, 200, then 400 milliseconds. They retry in three perfectly synchronized waves of 1,000 at 100, 300, and 700 milliseconds, so the dependency sees the same spike three more times, just spread out.

With full jitter, each client waits a uniform random duration between zero and the exponential ceiling, so the first wave of 1,000 is spread across 100 milliseconds at roughly 10 per millisecond, the second across 200, the third across 400, and the peak load shrinks by an order of magnitude while the average wait stays the same.

The formula I use is sleep = random(0, min(cap, base * 2^attempt)), which is the "full jitter" variant that measured best in the well-known AWS analysis; equal jitter, which keeps half the delay fixed, is a reasonable alternative.

"Where do retries live in a system with a service mesh or a gateway that already retries?"

At exactly one layer, and the mesh is usually the right one because it can enforce a fleet-wide budget and sees every hop.

If Envoy or the gateway retries, the application client's retry is set to zero attempts, otherwise the multiplication starts again: an application retry of 3 times a mesh retry of 3 is 9 attempts per call, and a two-hop chain makes it 81.

I make the decision explicit in a table: which layer retries, with what budget, for which status codes, and I check it in review of any new client.

The application keeps responsibility for idempotency keys and for retry-safe semantics, because the mesh cannot know whether a POST is safe. And the circuit breaker stays in the application, since it needs to know the fallback.

Q299 · Scenario. "A customer was charged twice. Logs show their client timed out and retried, and both attempts succeeded server-side. Design the fix properly."

Reveal answer

Strong answer The root cause is that a client timeout is not a server failure: the first charge succeeded after the client stopped waiting, so the retry was a second, legitimate-looking request. Since the network can always lose the response, retries are inevitable — the operation itself must become idempotent. The mechanism is an idempotency key:

  1. The client generates a unique key per logical operation — one UUID per checkout attempt, reused across all retries of that attempt — and sends it, Stripe-style, in an Idempotency-Key header.
  2. The server persists the key in the same database transaction as the charge, protected by a unique constraint. That placement is the crux: the key and the money move atomically, so there is no window where the charge exists but the key does not.
  3. A retry hits the unique constraint; instead of executing again, the server returns the stored outcome of the first attempt — same status, same response body. The client cannot tell the difference, which is the point.
  4. Operational details: scope keys per operation type, expire them after a retention window, and store the response payload alongside the key so replays are complete.

A Redis SET NX check can absorb cheap duplicate reads, but the guarantee lives in the database constraint — cache entries can vanish; unique indexes do not.

Land it You cannot stop clients from retrying, so you make retries harmless — the idempotency key committed atomically with the business write is what turns "at least once" delivery into "exactly one effect".

Likely follow-ups
"The retry arrives while the first attempt is still in progress. What does the server return?"

That is the concurrent-duplicate case and it needs a decision.

The first request has inserted its key row but not yet committed, so the retry's insert blocks on the unique index in most databases until the first transaction finishes, then fails with a constraint violation, at which point the server reads the stored outcome and returns it, which is correct but ties up a request thread for the duration.

The alternative Stripe uses is to return 409 Conflict immediately when a key is in progress, and let the client retry after a short delay.

To do that I insert the key in its own short transaction with a status of "in progress" before doing the work, then update it to "completed" with the response in the same transaction as the charge.

A lock timeout on the key row, a second or two, prevents the blocking variant from piling up threads.

"What if the first attempt failed halfway, after the key was stored but before the charge committed?"

If the key and the charge are in the same transaction, that cannot happen: a failure rolls back both, the key does not exist, and the retry is a clean first attempt, which is exactly why the atomicity matters.

With the two-phase "in progress" variant, it can happen, so the stored status must distinguish in-progress from completed, and an in-progress row older than some threshold, say a minute, is treated as abandoned: the retry takes over the key and runs the operation, ideally by updating the row's status with a compare-and-set so two retries cannot both take over.

The charge itself must then also be idempotent at the payment provider using the same key forwarded as their idempotency key, so a takeover that re-sends the charge cannot double-bill. Idempotency is only as good as the weakest link in the chain.

"What do you store with the key, and how long do you keep it?"

The key, a scope such as the customer or API client ID so two clients cannot collide on the same UUID, the operation type, a hash of the request body, the response status and body, and timestamps.

The request hash is important: if a retry arrives with the same key but a different body, that is a client bug, and the server returns 422 rather than replaying an outcome for a different request.

Retention is a business question about how long a client might plausibly retry; 24 hours covers any sane client, and Stripe keeps them for 24 hours as well.

A scheduled job deletes expired rows, or the table is partitioned by day so expiry is a partition drop. Storing the response body means replays are byte-identical, which is what makes the retry invisible to the client.

"Does this design change if the charge goes through a message queue instead of a synchronous call?"

The same idea moves to the consumer.

A queue is at-least-once by nature, so the consumer will eventually see the same message twice after a crash or a rebalance, and the message must carry a stable idempotency key, usually the order ID or a client-generated UUID, not the broker's offset.

The consumer inserts the key with a unique constraint in the same transaction as the charge, exactly as before, and a duplicate message hits the constraint and is acknowledged without re-executing.

The additional detail is the outbox on the producer side, so the message is written in the same transaction as the order and published by a relay, which removes the window where the order exists but the message was lost.

So the answer is: nothing about the guarantee changes, only where the unique constraint is enforced.

Q300. "Explain token-bucket rate limiting in plain language — and what a well-behaved API returns when the limit is hit."

Reveal answer

Strong answer Picture a bucket holding up to, say, 100 tokens, refilled at a steady 10 tokens per second. Every request must take a token; if the bucket is empty, the request is refused.

The refill rate caps the sustained average — 10 per second — while the bucket's capacity permits honest bursts: a client quiet for a while can briefly spend up to 100 at once, which matches how real traffic arrives, and is why token bucket beats a rigid fixed-window counter.

When the limit is hit, a well-behaved API returns 429 Too Many Requests with a Retry-After header saying when to come back — and our own clients must actually honor that header rather than hammering, or the limiter just becomes a retry storm generator.

Placement: at the gateway for per-client fairness and quota, and a second limiter inside the service for self-protection, since the gateway can be bypassed by internal callers.

In a fleet, per-instance local buckets are cheap but approximate — total allowance scales with instance count — while a Redis-backed shared bucket (Bucket4j supports both; Resilience4j's RateLimiter covers in-process) is exact but costs a network hop per decision.

Land it Token bucket caps the average while forgiving bursts, and the contract on refusal is 429 plus Retry-After — a limiter without an honored Retry-After just converts overload into a synchronized retry wave.

Likely follow-ups
"How does a Redis-backed shared bucket stay atomic across 30 instances?"

With a Lua script executed by EVAL, which Redis runs atomically on a single thread.

The script reads the bucket's stored token count and last-refill timestamp from a hash, computes the refill as elapsed time times rate capped at capacity, subtracts the requested tokens if enough are available, writes the new state back, and returns allowed or denied plus the wait time.

Because the whole read-compute-write is one script, two instances cannot both see the same token. Bucket4j's Redis integration does exactly this, and the cost is one round trip per decision, around half a millisecond.

For very high request rates I batch: each instance fetches a small allotment of tokens, say 20 at a time, and spends them locally, which cuts round trips by 20x at the cost of slight burstiness.

"Why token bucket rather than sliding window or leaky bucket?"

They answer slightly different questions. A fixed window counts requests per calendar minute and allows a 2x burst across the window boundary, which is its known flaw.

A sliding window log records timestamps and is exact but costs memory per request; a sliding window counter approximates it cheaply and is what many gateways use for fairness accounting.

Leaky bucket smooths output to a constant rate, which suits shaping traffic to a downstream that must not see bursts. Token bucket permits bursts up to capacity while capping the average, which matches how clients naturally behave and is the friendliest for API quotas.

So I use token bucket for per-client limits at the gateway, sliding window counter where I need accurate accounting for billing, and leaky bucket when protecting a downstream that cannot absorb bursts.

"How do you compute the Retry-After value, and how do you test the limiter?"

The value is the time until enough tokens exist for the request: tokens needed minus tokens available, divided by the refill rate, rounded up to whole seconds, since Retry-After is in seconds or an HTTP date.

With 10 tokens per second and an empty bucket, one request waits one second. I also add X-RateLimit-Limit and X-RateLimit-Remaining headers so clients can pace themselves before hitting the limit.

Testing is deterministic with an injected clock: fill the bucket, fire capacity plus one requests in a loop, assert the last one gets 429 with the computed Retry-After, advance the fake clock by that amount, and assert the next request succeeds.

A load test then checks the fleet-wide limiter actually holds at the configured rate across instances, which is where local-versus-shared bugs appear.

"What breaks at 10 times the traffic, and what would you design differently from scratch?"

The shared bucket's round trip becomes the bottleneck: at 50,000 decisions per second, one Redis call each is a lot of load on a single key, which lives on one shard, so the limiter itself becomes the hot spot.

The fixes are the batched token allotment I described, sharding the bucket per client so keys spread across shards, or accepting approximate local buckets with a periodic reconciliation.

From scratch, I would put per-client limiting in the gateway or mesh, where it belongs and where the implementation is already distributed, and keep only a cheap local self-protection limiter in the service, sized to what one instance can handle.

And I would make limits a per-client configuration with tiers rather than one global number, because the first request after launch is always "can customer X have more".

10 · RecapWhat Passing This Drill Means

  • You can explain the equals/hashCode contract from the HashMap bucket math up — and spot the broken-key bug in review before it ships
  • You can describe what a monitor is, what synchronized and volatile each guarantee, and reason with happens-before instead of folklore
  • You can size a thread pool from load numbers, and explain why the queue choice changes everything
  • You can take three thread dumps and walk from a frozen service to the owning thread and the fix
  • You can tell a memory leak from an undersized heap, and drive the diagnosis from GC logs to a MAT dominator tree
  • You can tune an API's latency with measurements — percentiles, traces, pool metrics — instead of guesses
  • You answer scenario questions in diagnosis order: symptom, evidence, cause, fix, prevention
🧠 Flex your memory

Close the page and sketch, from memory: the full submission algorithm of a ThreadPoolExecutor (core → queue → max → reject), and the three-dumps-ten-seconds-apart thread-dump workflow. Then reach back to Chapter E1: what were the four rules the from-zero primer gave for writing an immutable class — and which two of them exist purely for the concurrency reasons this drill made concrete?