Java Materials
← Core Java · Chapter 17

Synchronizers and thread-local state

Choose a synchronizer by the protocol you want. A completion latch counts outcomes, a barrier waits for peers to reach a point, and a semaphore caps concurrent holders. They are not interchangeable just because all can block.

Completion, rendezvous and phased work

Definition:

A synchronizer coordinates when threads can proceed without polling blindly.

Explanation:

CountDownLatch is one-shot and callers can use it to observe completion without assuming success.

Illustration image:

Completion, rendezvous and phased work. Two registered tasks · Worker A counts down · Worker B counts down · Waiter continuesCompletion, rendezvous and phased workSource or actorTwo registered tasksFirst boundaryWorker A counts downInspected stateWorker B counts downObservable effectWaiter continues
Two registered tasks · Worker A counts down · Worker B counts down · Waiter continues

Example:

Worked Java example · see surrounding context in notes
var completed = new java.util.concurrent.CountDownLatch(2);
Runnable task = () -> {
    try { loadShard(); }
    finally { completed.countDown(); }
};

Expected behavior. Two task exits unblock a waiter. Record exceptions separately because countdown does not report success.

Internal working:

CyclicBarrier is reusable for a fixed party count, and a failed wait can break the current generation. Phaser supports dynamic registration and per-phase advancement; deregister workers that will not participate again.

Interview questions:

Does CountDownLatch report whether all tasks succeeded?

No. It reports that the count reached zero. Collect task failures independently.

Permit ownership and bounded downstream work

Definition:

A semaphore bounds how many tasks hold access permits at one time.

Explanation:

A Semaphore caps concurrently held permits, not operations per second.

Illustration image:

Permit ownership and bounded downstream work. Four available permits · Task acquires one · Three remain · Finally restores onePermit ownership and bounded downstream workSource or actorFour available permitsFirst boundaryTask acquires oneInspected stateThree remainObservable effectFinally restores one
Four available permits · Task acquires one · Three remain · Finally restores one

Example:

Worked Java example · see surrounding context in notes
if (!permits.tryAcquire(50, java.util.concurrent.TimeUnit.MILLISECONDS)) {
    throw new IllegalStateException("downstream busy");
}
try { return client.fetch(); }
finally { permits.release(); }

Expected behavior. A task that failed to acquire a permit never executes the fetch and never increments the permit count.

Internal working:

Use tryAcquire with a deadline when the caller has a latency budget. A permit acquired by one action must not be released twice. Exchanger is a pairwise rendezvous for swapping payloads; use timed exchange when one participant can disappear.

Interview questions:

Why release only after successful acquisition?

A release after interrupted or timed-out acquisition would increase available capacity incorrectly.

ThreadLocal, pooled reuse and propagation

Definition:

ThreadLocal associates a value with a thread rather than with a logical request.

Explanation:

A pooled worker can serve many request identities.

Illustration image:

ThreadLocal, pooled reuse and propagation. Worker serves A · Install request ID A · Run A then clean up · Worker serves BThreadLocal, pooled reuse and propagationSource or actorWorker serves AFirst boundaryInstall request ID AInspected stateRun A then clean upObservable effectWorker serves B
Worker serves A · Install request ID A · Run A then clean up · Worker serves B

Example:

Worked Java example · see surrounding context in notes
static void runWithId(ThreadLocal<String> requestId, String id, Runnable task) {
    String prior = requestId.get();
    requestId.set(id);
    try { task.run(); }
    finally { if (prior == null) requestId.remove(); else requestId.set(prior); }
}

Expected behavior. The outer context is restored on nested use, including when task.run throws.

Internal working:

Without cleanup the next task may see previous data or retain it indefinitely. InheritableThreadLocal copies at thread creation, so it cannot transfer metadata to an existing worker per task. Propagate immutable request context explicitly or with a supported tracing context wrapper.

Interview questions:

What can go wrong if a pool worker keeps request context?

The next request may observe or retain the previous user’s data. Restore or remove it in finally.

Reference subtopics

Latch, barrier and phaser

CountDownLatch is one-shot; countDown in finally where the signal denotes termination, and track task errors separately. CyclicBarrier can rendezvous the same number of participants repeatedly; interruption or timeout can break a generation. Phaser supports dynamic registration and phases, making it useful for iterative work with changing participants. Deregister participants that exit.

Semaphore and Exchanger

Acquire a permit before touching a scarce resource and release only if acquisition succeeded. A semaphore does not track owner identity; releasing twice grows capacity incorrectly. Exchanger hands one value between two rendezvousing threads; use timeouts when a peer can disappear.

ThreadLocal and propagation

ThreadLocal attaches state to a thread, not a request. Pooled reuse can leak identity or keep old values alive. remove in finally. InheritableThreadLocal copies context at thread creation, so an existing executor worker will not inherit a new submission’s context. Capture immutable request metadata at submission and explicitly restore it with a supported logging or tracing integration.

Run the complete Java labs ↗ · Java reference ↗