How do compute and computeIfPresent differ from computeIfAbsent, and when would you use each?
answer
- IfAbsent: miss only, Function(key)
- IfPresent: hit only, BiFunction(key,value)
- compute: always, BiFunction(key, value-or-null)
- compute, computeIfPresent: return null removes
- ConcurrentHashMap: atomic read-modify-write
basics
~20 scomputeIfAbsent runs only when the key is missing or mapped to null, computeIfPresent only when it has a non-null value, and compute always, receiving the current value or null. Returning null removes the mapping, except in computeIfAbsent, which records nothing.
solid answer
~40 sThe three 'compute' methods share a remapping shape but differ on when the function fires and what it sees. `computeIfAbsent(k, fn)` takes a `Function<K,V>` and runs only on a miss. `computeIfPresent(k, fn)` takes a `BiFunction<K,V,V>` (key + current value) and runs only when the key has a non-null value; returning null removes the entry. `compute(k, fn)` also takes a `BiFunction` but **always** runs, receiving the existing value or null for an absent key — letting you handle both insert and update in one function; returning null removes/declines the entry. Use computeIfAbsent for lazy initialization (multimaps), computeIfPresent for 'update only what exists' (e.g., decrement a stock count and drop it at zero), and compute for unconditional upsert logic. On ConcurrentHashMap all three are atomic per key, so the read-modify-write is race-free.
go deeper
Can state that the three differ by when the function runs (absent / present / always).
Knows the function signatures, that compute always runs, and the return-null-removes rule.
Applies them correctly for upsert/decrement-and-remove and explains atomicity on ConcurrentHashMap.
Designs accumulation on concurrent maps, knows which maps may retry the function (ConcurrentMap's default compute and computeIfPresent, not ConcurrentHashMap), and weighs delete-by-null pitfalls in shared maps.
### The shared idea: remapping All three methods compute a **new value** for a key from a function and install it. They differ in (a) **when** the function runs and (b) **what arguments** it gets. For `compute` and `computeIfPresent`, **if the function returns null, the mapping is removed** (or, for an absent key, stays absent) — the 'delete by returning null' rule. `computeIfAbsent` never removes: a null result records nothing, so a key mapped to null stays mapped to null. Atomicity is no part of the `Map` contract: each default implementation "makes no guarantees about synchronization or atomicity properties", and a map that provides it must document it. ### computeIfAbsent(key, Function<K,V>) Runs the function **only if the key is absent** (or mapped to null). The function receives just the **key**. Used for lazy initialization — see the multimap pattern. If the key is present, the function does not run and the existing value is returned. ### computeIfPresent(key, BiFunction<K,V,V>) Runs the function **only if the key has a non-null value**. The function receives **(key, currentValue)** and returns the new value. If it returns null, the entry is **removed**. If the key is absent, nothing happens and it returns null. Typical use: modify something that must already exist, e.g. ```java stock.computeIfPresent(sku, (k, qty) -> qty > 1 ? qty - 1 : null); // remove at zero ``` ### compute(key, BiFunction<K,V,V>) **Always** runs. The function receives **(key, currentValueOrNull)** — null if the key is absent — so it must handle both the insert and update cases. Returning a value installs it; returning null removes the key (or leaves it absent). This is the general-purpose 'upsert'. Example, append to a running total whether or not it existed: ```java map.compute(k, (key, v) -> (v == null ? 0 : v) + delta); ``` ### Comparison table | Method | Function type | Runs when | Sees current value? | |---|---|---|---| | computeIfAbsent | Function<K,V> | key absent | no (key only) | | computeIfPresent | BiFunction<K,V,V> | key present | yes | | compute | BiFunction<K,V,V> | always | yes (or null) | ### Atomicity on ConcurrentHashMap On `ConcurrentHashMap`, each of these performs the entire **read-modify-write atomically** for that key — no other thread can interleave between reading the old value and writing the new one. That makes them the correct tool for concurrent counters and accumulators (versus `get` then `put`, which has a race). Keep the function short, since other threads' updates to that bin may block while it runs, and it must not modify the map. ### The delete-by-null rule and retries Because returning null deletes, be deliberate: a function that can return null on compute/computeIfPresent will *remove* entries — sometimes desired (clean up at zero), sometimes a surprise. Whether the function can run twice depends on the map: - **`ConcurrentHashMap`** documents `compute` as invoking it "exactly once per invocation of this method", and `computeIfAbsent` and `computeIfPresent` as once or not at all. Run eight threads on JDK 27 and the count is 1,600,000 function calls for 1,600,000 `compute` calls. - **`ConcurrentMap`'s default `compute` and `computeIfPresent`** can retry: "the remapping function may be called multiple times". Its default `computeIfAbsent` has no retry loop. - **`ConcurrentSkipListMap`** says the function is "*NOT* guaranteed to be applied once atomically". So code typed against `ConcurrentMap` should keep the function free of observable side effects.
- What happens if a compute function returns null?The mapping for that key is removed (or, if the key was absent, no mapping is created). This is the shared delete-by-null rule across compute/computeIfPresent.
- Why are compute methods preferred over get-then-put on a ConcurrentHashMap?They perform the read-modify-write atomically for the key, eliminating the race where two threads read the same old value and one overwrites the other's update.
- Thinking compute skips absent keys (it always runs)
- Forgetting that returning null removes the mapping
- Expecting computeIfPresent to insert a new key
- Using get-then-put for concurrent counters instead of compute
- Map.compute and Map.computeIfPresent
- Java 1.8
Assumes JDK 27; these are Map default methods since Java 8, and the contract, on ConcurrentHashMap too, reads the same at JDK 25.
context
- Map (Java SE 27 & JDK 27)docs.oracle.com
- ConcurrentHashMap (Java SE 27 & JDK 27)docs.oracle.com
- ConcurrentMap (Java SE 27 & JDK 27)docs.oracle.com