Lesson · Executors, Thread Pools & Async Programming
Concurrency Design Guidelines: the rules that prevent the incidents
17 min readConcurrency Design Guidelines
Race conditions, deadlocks and leaks are not separate diseases; they are the same handful of design mistakes wearing different stack traces. These eight rules are ordered by cost, from removing the sharing entirely to the paragraph of documentation that keeps the other seven honest.
Every class has a threading policy
Here is a class that passes its unit test and fails in production: a cache with a plain HashMap, no synchronization, and no comment saying who may call it.
Nothing in that file answers the question a second thread asks the moment it arrives. Every class has an answer; when it is not written down, the answer is whatever the last author assumed, and the failures fall into four families.
public class RateCache { private final Map<String, BigDecimal> rates = new HashMap<>(); // shared, mutable, undocumented public BigDecimal rate(String pair) { BigDecimal cached = rates.get(pair); // two request threads, one plain HashMap if (cached != null) { return cached; } BigDecimal fresh = lookup(pair); // slow provider call, outside any lock rates.put(pair, fresh); return fresh; } private BigDecimal lookup(String pair) { return BigDecimal.ONE; // stand-in for the remote provider } }
- Lost updates: two threads read, both write, one result disappears (the race-conditions lesson).
- Corrupted structures: a resize or a rotation is in progress while another thread walks the same collection.
- Hangs: a lock cycle, a missed signal, a barrier that never fills.
- Resource growth: threads, queues or connections that outlive the load that created them.
A class without a documented threading policy has an undocumented one. The policy is real; it just lives in the last author's head.
The decision order
The rules are a sequence of questions, and each one is cheaper to answer yes to than the one after it. Stop at the first yes that applies: every later answer costs throughput, latency or reasoning power.
- Does the state have to be shared between threads at all? If not, keep it local: a local variable, a per-request object, a single owner.
- Can the shared state be immutable? Then it is published once and shared forever, with no locks anywhere.
- Can it be confined? A copy per thread or per task removes the shared mutable cell instead of guarding it.
- Can a java.util.concurrent type own the sharing? An atomic, a concurrent collection, a queue or an executor already encodes the answer.
- If none of that fits: a lock, encapsulated in a private final field, held briefly, ordered with any other lock, and documented with the policy.
No sharing beats any lock. Every rule after the first is a cost you pay because sharing was unavoidable.
concurrency guidelines · the decision order
stop at the first yes: each step down costs more than the one above
The order is the point. A class that stops at step 1 or 2 has nothing to review; a class that arrives at step 5 owes the next reader a policy paragraph, a lock order and a short critical section.
Rule 1: do not share mutable state
The surest fix for a data race is to delete the shared mutable cell it races on. Three techniques do the deleting, in increasing order of cleverness.
- Immutability: final fields, no mutable internals handed out, and safe publication for the reference itself (the final-field and happens-before lessons cover the construction edges). An immutable object needs no lock, no atomic, and no policy beyond where the reference is published.
- Confinement: the object is reachable from exactly one thread. Locals are the free version; ThreadLocal gives each thread its own copy of what would otherwise be shared (the threadlocal lesson covers the cleanup patterns); a per-task object keeps executor and fork/join work isolated.
- Copy-on-write snapshots: readers hold an immutable snapshot while the writer builds the next one and swaps the reference. Read-mostly configuration and registries fit this shape, and CopyOnWriteArrayList is the packaged version of it.
Confinement is a structure, not a comment. If a second thread can reach the object, you do not have confinement; you have a race with a nice name.
Rule 2: take the library tool before you take a lock
When sharing is unavoidable, reach for java.util.concurrent before reaching for a lock. Those types are tested at a scale a guarded wrapper around a plain collection never sees, and their contracts state exactly what is atomic: ConcurrentHashMap.computeIfAbsent runs the mapping function at most once per key, BlockingQueue.take() parks the consumer, AtomicLong.incrementAndGet cannot lose an update.
A lock around a plain HashMap is easy to write and easy to get subtly wrong: every read and every write must take it, iteration must copy or hold it, and no I/O may run inside it. The concurrent collection deletes all three sentences from the review.
- Atomics and adders for counters and accumulators (the atomics-and-cas lesson).
- Concurrent collections for shared maps, sets and lists, including their atomic compute methods.
- Blocking queues for handoff and backpressure (the blocking-queues lesson).
- Synchronizers for coordination rather than exclusion (the synchronizers lesson).
- Executors for running work, so no class calls new Thread for a request (the thread-pools lesson).
A hand-rolled lock around a plain collection is a cache of bugs. The concurrent version answers the question you were about to be asked in review.
Rules 3 and 4: encapsulate the lock, and give it an order
When a lock is genuinely the answer, four habits keep it from becoming the next incident: the monitor is a private field, the critical section is short, no foreign code runs inside it, and a second lock gets a documented order.
public final class Counter { private final Object lock = new Object(); // private: no outsider can hold this monitor private long count; public void increment() { long next; synchronized (lock) { next = count + 1; // short section: one read, one write, no calls count = next; } notifyListeners(next); // alien code runs outside the lock, always } }
- Encapsulate the monitor. A private final lock object, never this, never a public object. Locking a public object hands your critical section to callers you have never met.
- Keep the critical section short and free of alien code. No I/O, no callbacks, no overridable methods, no listener invocations while holding the lock. The code you do not control can block, take other locks, or call back into you.
- One lock per invariant. One lock is easier to reason about than two. If two must coexist, write their order down and route every caller through it (the deadlock lesson owns the Coffman conditions and the proof that ordering removes the cycle).
- Snapshot, then call. Copy what you need under the lock, leave, then invoke the callback or the I/O. The critical section holds a read and a field assignment, nothing more.
Lock on a private object and the critical section becomes yours. Lock on this or a public object and any caller can hold it, starve it or deadlock it.
Rules 5 to 7: bounds, ownership and cancellation
Three rules cover everything that outlives a single method call: queues, threads and the way a thread is asked to stop.
try { work(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // restore the flag: the caller decides what cancellation means return; }
- Bound every queue. An unbounded queue absorbs overload until the heap runs out, which hides the cause and puts the failure somewhere else. A bound makes the overload visible at the submission point, where blocking, rejecting or shedding are still decisions (the thread-pools lesson covers the policies).
- Prefer executors to raw threads, and own the lifecycle. One component creates the pool, names its threads and shuts it down. A thread dump full of pool-3-thread-7 tells you nothing; http-workers-3 tells you which subsystem is stuck.
- Make cancellation cooperative. A thread stops because it was asked to, not because something was killed. Interrupt is the request: an InterruptedException that is swallowed, or a flag that is not restored, turns a graceful shutdown into a hang (the thread-api lesson covers the flag mechanics).
A boundary you do not set will be found for you. Unbounded queues and unnamed threads turn a load spike into an outage nobody can read.
Rule 8, and the review that catches the rest
The last rule is not paperwork; it is what makes the other seven stick. A policy statement answers four questions in a sentence each: which methods are safe to call from other threads, which state is guarded by which lock, what the lock order is when two are involved, and who owns any thread or pool the class starts.
With the policy written down, review becomes mechanical: every concurrency question in the diff is one of five.
| Rule | Enforced by | The incident it prevents |
|---|---|---|
| 1 · no sharing | immutability, confinement, snapshots | lost updates and every other race |
| 2 · library first | atomics, concurrent collections, queues, executors | subtly wrong hand-rolled guards |
| 3 · encapsulated locks | private final monitor, short sections, no alien calls | deadlocks and latency spikes from foreign code under a lock |
| 4 · lock ordering | one total order shared by every code path | the classic two-lock deadlock |
| 5 · bounded queues | a bound plus an explicit rejection policy | unbounded growth until the heap runs out |
| 6 · executors own threads | named pools with a single lifecycle owner | thread leaks and unreadable dumps |
| 7 · cooperative cancellation | interrupt propagated, or the flag restored | a shutdown that hangs |
| 8 · documented policy | a javadoc paragraph on the class | every future review and incident |
- What is shared? Name every field and static two threads can touch. If the list is empty, the class is easy and the review is done.
- What is the invariant? Say what has to stay true about that shared state.
- What guards it? One tool per invariant: immutability, an atomic, a concurrent type, or a named lock.
- What can block inside the guard? Alien calls, callbacks, I/O and second locks are all disqualifying.
- What is documented? If the policy is not in the javadoc, it is not in the class.
Rule 8 is what keeps the other seven true. A policy sentence in the javadoc turns the next review from an argument about interleavings into a check of four facts.
guidelines lab · name the tool before the lock
pick a workloadthe workload
Five worker threads increment one statistic that a health endpoint reads every second.
the naive choice
int counter++ (or a volatile int)
Lost updates. Read-modify-write is not atomic, and volatile only fixes visibility, so the total comes out short by an unpredictable amount and nothing throws.
the answer
LongAdder
Striped cells spread the contention across cache lines, and sum() reads a consistent total. Use AtomicLong when you also need the exact value at every moment.
rule 1 to rule 2 · the state is shared, so stop sharing it or hand it to a j.u.c. type
The naive column is not a strawman: every failure there has shipped. The rule numbers match the eight rules in the lesson, in the order they are applied.
Testing concurrent code without lying to yourself
Concurrency bugs do not reproduce on demand, so tests have to be designed rather than run until they turn green.
- Deterministic first. A CountDownLatch sequences the interleaving you care about: hold thread B until A is provably between two steps. Inject the executor so the test owns the threads instead of letting production code create them.
- Then stress. Many iterations, many threads, for longer than feels reasonable, because a race needs one specific interleaving. A stress run can prove that a bug exists; it can never prove that one does not.
- Use the specialist tools. jcstress, the OpenJDK concurrency stress harness, is built for memory-model questions and reports outcomes as forbidden or acceptable. SpotBugs and Error Prone catch the classic patterns statically. Thread dumps taken under load show the shape of a hang that no unit test reaches.
- Treat flakiness as signal. A test that fails in one run out of fifty is reporting a race, in the code or in the test. Quarantining it as noise is how the incident gets scheduled for a later date.
A green concurrency suite proves the interleavings you thought of. The tooling exists because the ones that matter are the ones you did not.
synchronized(this) hands your lock to strangers
A public monitor is not a lock you own: any caller, subclass or framework that locks the same object takes part in your critical section, and can hold it as long as it likes. Some objects are shared JVM-wide: string literals are interned, and boxed Integers from -128 to 127 come from a shared cache, so synchronized("abc") locks a monitor every library on the heap can see. The fix is one line: private final Object lock = new Object(). Then the monitor is a field nobody outside the class can reach, and the critical section is yours to reason about.
Interview angles
How do you make a class thread-safe?+
Start by removing the sharing: immutable state, or state confined to one thread. If sharing is unavoidable, put the state behind a java.util.concurrent type. Only then consider a lock, encapsulated in a private final field, with the policy documented in the javadoc.
The order matters because each step costs more than the last. An immutable class needs no locks at all, while a locked class needs a policy about every method that touches the guarded state.
Why is synchronizing on this, a String literal or a boxed Integer dangerous?+
Because the monitor is not private. Any caller or subclass can lock the same object and become part of your critical section, and interns and cached boxes are shared JVM-wide, so those monitors are the most public objects in the process.
The symptom is usually a hang that no source file explains: two unrelated components locking the same interned string, with a lock cycle nobody can see in a single diff.
Common misconception: The object itself is the natural lock, so locking on this is the idiomatic choice.
What is an open call, and why does it matter?+
Calling an overridable or foreign method while holding a lock. The code you do not control can block, take other locks, or call back into you, which turns a short critical section into a deadlock or a latency incident.
The classic shape is a listener invoked inside a synchronized block, which calls back into the class along another path. The fix is the snapshot pattern: take what you need under the lock, release it, then invoke.
How do you test concurrent code?+
Deterministically first, with latches forcing the interleaving you care about and an injected executor so the test owns the threads. Then stress runs and static analysis, with jcstress for memory-model questions. A flaky result is a bug report about the code or the test.
What belongs in a class concurrency policy?+
Which methods are safe to call from other threads, which state is guarded by which lock, the ordering when more than one lock is involved, and who owns the threads or pools the class starts. Write it while writing the class, not after the incident.
Why do bounded queues matter for backpressure?+
An unbounded queue never slows a producer, so overload accumulates silently until the heap runs out, far away from the cause. A bound moves the decision to the submission point, where blocking, rejecting or shedding load can still be chosen deliberately.
Blocking slows the producer, rejecting fails fast, and shedding drops the least valuable work. The point is that one of them was chosen; an unbounded queue chooses none of them and lets the JVM decide with an OutOfMemoryError.
Follow-up: What do you do when the queue is full?