Java Materials
← Core Java · Chapter 20

Production diagnosis, testing and coding labs

Diagnose by matching symptoms to evidence. A deadlock dump shows a wait cycle and lock owners; starvation can show queues stuck without a lock cycle. Queue growth adds waiting latency and retains tasks in memory. A hot CPU can mean useful work, a spin loop or a CAS hotspot; compare sampled stacks, throughput and JFR events rather than trusting thread state alone.

Incident triage from symptoms and evidence

Definition:

Production triage matches a system symptom to evidence that can confirm or reject a hypothesis.

Explanation:

Deadlock is a lock ownership cycle.

Illustration image:

Incident triage from symptoms and evidence. Latency rises · Inspect queue age · Sample stacks and locks · Verify fix under loadIncident triage from symptoms and evidenceSource or actorLatency risesFirst boundaryInspect queue ageInspected stateSample stacks and locksObservable effectVerify fix under load
Latency rises · Inspect queue age · Sample stacks and locks · Verify fix under load

Example:

Shell / diagnostic commands
jcmd PID Thread.print -l
jcmd PID JFR.start name=incident duration=45s filename=incident.jfr

Expected behavior. In the dump, match waiting threads to actual lock owners; in JFR, compare hot stacks and allocation rather than counting RUNNABLE lines.

Internal working:

Pool exhaustion can exist without a cycle. Queue growth raises latency and retains task objects even when CPU is low. Sustained CPU may mean useful work, spinning or CAS retries. Review thread dumps in a series and correlate with metrics and JFR before adjusting thread counts or heap.

Interview questions:

How can you distinguish worker starvation from a deadlock?

Check queue age and worker stacks for tasks waiting on their own pool. Examine lock ownership for a cycle before calling it deadlock.

Deterministic tests and benchmarks

Definition:

A deterministic concurrency test coordinates observable points and asserts an invariant.

Explanation:

Use latches or barriers to make a race test contend intentionally and assert conserved balances, no duplicate IDs or exact final counters.

Illustration image:

Deterministic tests and benchmarks. Workers ready · Latch opens · Opposing transfers run · Total balance unchangedDeterministic tests and benchmarksSource or actorWorkers readyFirst boundaryLatch opensInspected stateOpposing transfers runObservable effectTotal balance unchanged
Workers ready · Latch opens · Opposing transfers run · Total balance unchanged

Example:

Worked Java example · see surrounding context in notes
var start = new java.util.concurrent.CountDownLatch(1);
var first = pool.submit(() -> { start.await(); transfer(a,b,1); return null; });
var second = pool.submit(() -> { start.await(); transfer(b,a,1); return null; });
start.countDown();
first.get(2, java.util.concurrent.TimeUnit.SECONDS);
second.get(2, java.util.concurrent.TimeUnit.SECONDS);

Expected behavior. Both tasks must complete; also verify balances remain nonnegative and the combined amount is unchanged.

Internal working:

A test passing once is not proof of correctness under every schedule. Use JMH with warm-up, forks and visible results for performance; report configuration and compare distributions under realistic contention.

Interview questions:

Why avoid using sleep to order test threads?

A sleep is a timing guess. Barriers or latches expose explicit ordering and bounded waits catch failures.

Single-flight cache and failure ownership

Definition:

A single-flight cache coalesces concurrent loads for the same key into one shared operation.

Explanation:

Use putIfAbsent to install an in-flight result and run expensive loading outside the map remapping function.

Illustration image:

Single-flight cache and failure ownership. First caller installs future · Other callers share future · Load succeeds or fails · Remove failed entry by identitySingle-flight cache and failure ownershipSource or actorFirst caller installs futureFirst boundaryOther callers share futureInspected stateLoad succeeds or failsObservable effectRemove failed entry by identity
First caller installs future · Other callers share future · Load succeeds or fails · Remove failed entry by identity

Example:

Worked Java example · see surrounding context in notes
var candidate = new java.util.concurrent.CompletableFuture<Value>();
var prior = map.putIfAbsent(key, candidate);
if (prior != null) return prior.join();
try { candidate.complete(load(key)); }
catch (RuntimeException failure) {
    candidate.completeExceptionally(failure);
    map.remove(key, candidate);
}
return candidate.join();

Expected behavior. One owner loads the key at a time in this sketch; the full lab also handles Error so waiters do not remain stuck.

Internal working:

Waiters may share a completed or failed future. Delete a failed mapping conditionally so a stale failure cannot evict a replacement. Plan bounded retention, retry backoff and interruption behavior separately. A single-flight cache inside one JVM is not distributed idempotency.

Interview questions:

Why remove a failed entry conditionally?

A stale loader must not delete a different entry installed by a later request.

Reference subtopics

Testing and benchmarks

Use latches, barriers and bounded waits to make execution order intentional. Assert invariants rather than assuming a sleep reaches a particular state. Use JMH with warm-up, forks and meaningful result consumption. Keep setup distinct from measured work, record variability and measure on representative hardware and load.

Producer–consumer and counters

Work through a bounded BlockingQueue and make producer and consumer shutdown coordinated. Avoid inserting a sentinel that can block indefinitely if the consumer stopped; define the drain and cancellation policy. Compare merge for exact per-key updates with LongAdder metrics under contention and verify final counts after workers join.

Transfers and parallel APIs

Acquire multiple account locks in a stable ID order and handle self-transfers. Never hold account locks while invoking another service. Start three independent calls before waiting, bound the overall deadline, and decide which failures permit partial responses. Client-specific deadlines and idempotency still matter.

Virtual-thread service and cache loading

Use a virtual thread per request and a semaphore or connection pool for downstream capacity. When caching, deduplicate in-flight loads by key using an installed Future or library support. Remove a failed in-flight result conditionally so it cannot remove a newer load, then apply bounded retries or a short failure TTL when appropriate.

Run the complete Java labs ↗ · Java reference ↗