Concurrency and correctness
Protect compound operations, not just individual fields.
Explore the design exercises →
Concurrency correctness is about complete operations over shared state. Begin with the invariant and the point at which competing commands become ordered. Then reason about cancellation, retries, deadlines and external effects separately; a thread-safe collection does not make a multi-step workflow atomic.
Learning goals
- Choose an atomic owner and identify each command linearization point.
- Compare locks, version checks and conditional database writes.
- Test races and uncertain external results with deterministic coordination.
What, when, why and how
Atomic check-and-update
- what
- The eligibility check and all invariant-preserving writes have one indivisible conflict decision.
- when
- Two callers compete for a last seat, wallet funds or an inventory allocation.
- why
- Thread-safe get and put still allow both callers to observe the same old state.
- how
- Keep validation and mutation in one synchronized owner, transactional conditional update or compare-and-set loop. State exactly when the operation takes effect.
Worked example: Both callers see one seat; only the conditional available→held transition may win. Multi-seat groups require one transaction for the entire set.
Common mistake: volatile gives visibility for a field, not atomicity for a compound check/decrement across several fields.
Locks, ordering and callbacks
- what
- Locks serialize a consistency boundary; stable ordering prevents cycles when several locks are needed.
- when
- A transfer needs two accounts or a reservation spans several stock rows.
- why
- Opposing lock order can deadlock; arbitrary user/network callbacks can block the owner indefinitely.
- how
- Acquire affected resources in stable identity order. Prepare local command intent under ownership, release it, call the adapter, then correlate evidence under ownership again.
Worked example: Transfer A→B and B→A both lock min(A,B) then max(A,B). No HTTP request occurs inside that critical section.
Common mistake: A reentrant monitor permits nested same-thread entry; it does not prevent cross-thread dependency deadlocks.
Optimistic versions and fencing
- what
- An expected version detects stale intent; a fencing token identifies the current ownership epoch.
- when
- Clients act on snapshots or old workers finish after a lease expires.
- why
- Turn/state validation alone may accept commands based on obsolete assumptions.
- how
- Compare version and mutate atomically; return conflict for a stale command. Issue a new token on each worker claim and reject old-token completion.
Worked example: Two moves at version 0 race: one commits version 1. A retired workflow token cannot advance the replacement attempt.
Common mistake: A local token cannot stop a stale external provider write unless the destination enforces the token/key or is reconciled.
Idempotency and retry evidence
- what
- A stable logical operation identity plus immutable request fingerprint prevents repeating an accepted effect.
- when
- Responses are lost and callers retry after later state changes.
- why
- A random new ID per retry duplicates work; blindly accepting one reused key changes its meaning.
- how
- Resolve the key before repeating mutation, verify kind/inputs, store accepted result together with effect, and define retention/replay behavior.
Worked example: Repeat shipment S with identical quantities changes no stock; S with a different quantity rejects. Current-view retries may return later reservation state.
Common mistake: An in-memory key map disappears on crash. Durable effects require durable atomic deduplication over the retry horizon.
Clocks, deadlines and leases
- what
- A deadline decides when authority ends; elapsed clocks differ from wall-clock/calendar time.
- when
- Holds expire, tasks are delayed or workers own leases.
- why
- Unspecified exact boundaries and clock rollback cause nondeterministic eligibility.
- how
- Declare trusted time and compare now>=deadline consistently. Inject clocks for tests. Persist absolute instants for restartable schedules; do not persist a process-local monotonic tick as a global instant.
Worked example: At the exact seat hold deadline a fresh confirm cannot steal inventory. A delayed scheduler wakes when a fake clock advances.
Common mistake: A lease timeout proves reporting authority expired, not that the worker stopped or the remote side effect failed.
Cancellation and unknown outcomes
- what
- Cancellation is a request to stop future/in-flight work; UNKNOWN records missing evidence.
- when
- A task is interrupted or a payment/notification response is lost.
- why
- A cancelled future cannot undo a charge, and an ignored interrupt cannot kill a running body.
- how
- Separate QUEUED cancellation from CANCEL_REQUESTED running work. Await actual local exit. For remote uncertainty reconcile stable operation identity before retry/compensation unless safe idempotency is established.
Worked example: Running task catches interruption and keeps waiting: state remains CANCEL_REQUESTED until it exits.
Common mistake: Reporting CANCELLED immediately can release capacity or refund while the original effect still runs.
Backpressure and resource ownership
- what
- Bound accepted pending work and active execution independently.
- when
- A slow handler/loader/provider can accumulate requests.
- why
- An unbounded queue converts latency into memory exhaustion; count bounds do not cap large payload bytes.
- how
- Choose reject/block/drop/spool policy explicitly. Count detached but still-running cache loads against active work. Define shutdown admission and drain behavior.
Worked example: Event Bus drops new work only for the full subscriber queue. Scheduler queue capacity is separate from worker count.
Common mistake: Removing an item from a map does not free a resource if its detached thread/socket is still active.
Deterministic race and failure tests
- what
- Coordinate contenders and assert observable invariants, rather than hoping timing exposes a bug.
- when
- Testing ownership races, stale completion and slow adapters.
- why
- Thread.sleep-based tests can pass without reaching the dangerous interleaving.
- how
- Use latches/barriers to align starts and pause callbacks. Bound waits, surface worker exceptions and assert both outcomes plus final state. Use an independent oracle for arithmetic/replay where practical.
Worked example: Two last-unit reservations start together; exactly one wins and reserved<=onHand remains true. Pause a loader, put a new value, then release old work and prove it cannot overwrite.
Common mistake: Passing one controlled interleaving is evidence for that scenario, not a proof of all possible schedules.
One local atomic owner
Illustrative Java 21 snippet; the linked exercises contain complete executable references and tests.
The successful decrement is the local linearization point. Both eligibility check and mutation share one monitor, and reads have the same visibility boundary. This small demonstration has no reservation identity, release, multi-SKU transaction or durability; the Inventory exercise adds those contracts. Replacing the long with AtomicLong would need a correct CAS loop, not separate get/set.
Worked design exercise
Design a safe test for cancellation of a running task that ignores its first interrupt.
- Task signals an entered latch, then waits on a second release gate.
- Wait for entered before requesting cancellation.
- Task catches the interrupt and signals observed; assert scheduler still reports CANCEL_REQUESTED.
- Release the gate and await actual exit; assert CANCELLED.
- Submit another task and prove it does not inherit the old interrupt flag.
Compare your reasoning with the worked answer
The two gates force the exact interval between cancellation intent and local termination. Bounded waits prevent a hung test. Remote side effects remain a different contract: task termination alone does not prove a provider action was undone.
Engineer to Staff follow-ups
Engineer: Why not use a concurrent map for every field?
Atomic methods on separate entries do not preserve invariants spanning multiple reads/writes. Choose a compound owner.
Senior: How do you avoid stale cleanup releasing a new owner?
Condition cleanup on the original reservation/claim identity and expected state/version, then release only resources still owned by it.
Staff: What survives a crash?
Only durably committed facts. Persist state/outbox/idempotency together, rebuild projections and reconcile remote unknowns; local locks and futures disappear.
Apply it in design exercises
- Task Scheduler: interruption and termination →
- Cache: stale-loader fencing →
- Workflow Engine: leases and unknown effects →
For each exercise, derive the object owner, schema keys/relationships and transaction boundary before revealing the reference.