ConcurrentHashMap makes each single-key operation atomic, yet multi-key invariants and aggregate reads can still be wrong under concurrency. Where are the atomicity boundaries, and how do you design around them?
answer
- Atomic = single call, single key
- Not atomic: call sequences, multi-key updates
- size()/bulk reads are weakly consistent estimates
- Collapse invariant into one immutable value + compute
- Couple keys -> lock readers take too / AtomicReference / DB
basics
~20 sEach single operation (get, put, merge, etc.) is atomic, but a series of operations or anything spanning multiple keys is not. size() and bulk reads are only approximate while the map changes. For cross-key or whole-map consistency you need your own coordination, a snapshot, or a different design.
solid answer
~50 sConcurrentHashMap guarantees atomicity at the granularity of a single method call on a single key—putIfAbsent, merge, compute all read-modify-write that one key indivisibly. It does NOT guarantee: (1) atomicity across a sequence of calls; (2) consistency across multiple keys, since no call updates two keys as one transaction; (3) exact aggregate results—size()/mappingCount() are estimates under mutation, bulk operations (forEach, reduce, search) traverse a weakly consistent view, and readers can see part of a putAll or clear. To design around this: keep invariants inside a single key (store a composite immutable value updated via compute); use a transactional store, or one lock that readers as well as writers take, when several keys must change together; get a stable view the same way, because copying a live map is itself weakly consistent; and treat size()/iteration as advisory. The mental model: per-key linearizability, not multi-key serializability.
code
java · 27 linesimport java.util.concurrent.ConcurrentHashMap;
class AtomicityBoundaries {
// Multi-field invariant collapsed into ONE key via an immutable value + compute -> atomic.
record Stats(long count, long sum) {}
static final ConcurrentHashMap<String, Stats> stats = new ConcurrentHashMap<>();
static final ConcurrentHashMap<String, Long> balances = new ConcurrentHashMap<>();
static void add(String key, long value) {
// Updates BOTH fields as one indivisible read-modify-write on this key
stats.compute(key, (k, cur) -> cur == null
? new Stats(1, value)
: new Stats(cur.count() + 1, cur.sum() + value));
}
static void move(String a, String b, long amount) {
// NOT one transaction: a reader can see a debited, b not yet credited.
// Coupled keys need a lock readers take too, one AtomicReference to immutable state, or a transactional store.
balances.merge(a, -amount, Long::sum);
balances.merge(b, amount, Long::sum);
}
static long approximateSize() {
return stats.mappingCount(); // estimate under concurrent mutation; do not gate correctness on it
}
}go deeper
Understands that each CHM operation is individually safe, even if not the boundaries.
Knows get-then-put sequences aren't atomic and that compound methods fix single-key check-then-act, plus that size() can be approximate.
Clearly separates per-key atomicity from multi-key/aggregate consistency, and uses immutable value objects with compute to make multi-field updates atomic.
Frames the guarantee as per-key atomicity vs multi-key serializability, designs invariants to fit one key, knows when to escalate to transactions or to coordination that readers respect too, and treats aggregates and weakly-consistent bulk views as advisory in system design.
## The precise guarantee The compound methods promise atomicity in so many words: "The entire method invocation is performed atomically" on `compute`, `computeIfAbsent` and `merge`. Retrievals promise something different: they "reflect the results of the most recently completed update operations holding upon their onset", and an update **happens-before** any non-null retrieval that reports its value. A good mental model for one key is **linearizability**: each call behaves as if it took effect **instantaneously at some point** between its call and return. That is a model, not a word this class's Javadoc uses. Atomic is also not exclusive: a `get` can overlap a running `compute` and return the earlier value. Everything below falls outside these promises. ## Boundary 1 — sequences of operations are not atomic Two *individually* atomic calls can interleave with another thread's calls: ```java if (map.get(k) == null) map.put(k, v); // even both atomic, the pair is racy map.merge(a, 1, Integer::sum); map.merge(b, 1, Integer::sum); // a and b not updated together ``` There is **no transaction** spanning calls. If your correctness depends on "these two updates happen together," CHM alone cannot give it. ## Boundary 2 — multi-key invariants Suppose an invariant ties two keys (e.g. "`count[A] + count[B]` is constant," or "moving an item from list A to list B"). CHM has **no way** to update both keys atomically. A reader can observe an intermediate state where A is decremented but B not yet incremented. Options: - **Collapse the invariant into one key:** store *both* fields in a single **immutable value object** and update it with `compute`, so the multi-field change is one atomic per-key op. This is the most idiomatic fix. - **External coordination:** guard the multi-key update with your own lock and **take that lock in readers too**, because `get` never waits for it and the class has no "support for locking the entire table in a way that prevents all access" (`synchronized (map)` does not stop its other users). Or use an `AtomicReference` to an immutable snapshot of the whole relevant state, or move to a real transactional store (DB, STM). ## Boundary 3 — aggregate / bulk reads are weakly consistent - **`size()` / `mappingCount()`** are **estimates** under concurrent mutation. CHM counts with a striped `LongAdder`-style counter for scalability, so the returned total is racy. Never base correctness (e.g. capacity enforcement) on it; if it must be exact, put every update and that read behind one lock of yours. - **Aggregate updates are not atomic either.** During `putAll` or `clear`, "concurrent retrievals may reflect insertion or removal of only some entries." - **Iteration and the bulk ops** (`forEach`, `search`, `reduce`, and the keySet/values/entrySet views) traverse a **weakly consistent** view: they never throw `ConcurrentModificationException`, but may reflect insertions/removals that happened during the traversal, possibly visiting some and missing others. They are **not** a consistent point-in-time snapshot of the whole map. - If you truly need a stable snapshot, you must **build one yourself**. `new HashMap<>(map)` walks the same weak view, so the copy is stable only if every writer stops for it (a lock all writers take) or the map is known to be quiescent. Otherwise accept the weak view. ## Design patterns around the boundaries 1. **One key = one consistency unit.** Model each independently-mutated invariant so it lives behind a single key, then use `compute`/`merge` with an **immutable value** for the atomic read-modify-write. Immutability avoids torn reads of the value itself. 2. **Fast remapping functions, free of side effects where you can.** They run under the bin lock, so keep them fast and non-blocking, and never mutate the same map inside them. On this class `compute` and `merge` call the function at most once per call, but `replaceAll` retries and the `ConcurrentMap` default methods say the function "may be called multiple times", so code written against the interface cannot count on once. 3. **Escalate when keys are coupled.** Genuine multi-key transactions need an external mechanism: a coarse lock taken by every reader and writer of those keys, a single `AtomicReference<ImmutableState>` updated via CAS, or a transactional datastore. Don't fake it with multiple CHM calls. 4. **Treat aggregates as advisory.** Use `size()` for metrics/heuristics, not invariants. For exact counts you need quiescence or external coordination. 5. **Know the parallelism knobs.** Bulk ops take a `parallelismThreshold`; below it they run sequentially. Parallel bulk ops still observe a weakly consistent view—parallelism doesn't add consistency. ## The one-line mental model **Model CHM as per-key linearizable (a model, not its stated contract), not multi-key serializable, and with no consistent global snapshots.** Architect each invariant to fit inside one key, or step outside the map for coordination.
- You need to atomically move a value from key A to key B. Can CHM do it?Not as a single atomic step across two keys. Either redesign so both belong to one key (one value object updated via compute), or guard the move with a lock that readers take too, or a transactional store. Two separate CHM calls leave an observable intermediate state, and get never waits for a lock of yours.
- Why store an immutable value object rather than mutating a shared mutable value?Mutating a shared value object outside the map's control can be seen half-updated (torn reads) by lock-free readers. Replacing it wholesale via compute publishes a fully-formed, consistent value atomically per key.
- Assuming a chain of CHM calls is transactional
- Using size() to enforce a hard capacity invariant
- Believing forEach/iteration gives a consistent whole-map snapshot
- Trying to keep a two-key invariant with two separate merge calls
- Thinking parallel bulk operations add consistency
- ConcurrentMap.compute and merge
- Java 1.8
- ConcurrentHashMap forEach, search and reduce
- Java 1.8
context
- ConcurrentHashMap (Java SE 27 & JDK 27)docs.oracle.com
- java.util.concurrent (Java SE 27 & JDK 27)docs.oracle.com