intermediateConcurrency Utilities

What are ConcurrentHashMap's compute methods, and why should you prefer them over a separate get and put?

Calling get(key) followed later by put(key, newVal) is not atomic as a pair -- another thread can modify the value in between your get and your put, silently causing a lost update. ConcurrentHashMap instead provides several atomic compound methods. compute(k, (k, v) -> newV) performs an atomic read-modify-write in a single call. computeIfAbsent(k, k -> v) computes and inserts a value only if the key is not already present, which is useful for lazily populated caches. computeIfPresent(k, (k, v) -> newV) updates the value only if the key is already present. merge(k, v, biFunction) inserts v if the key is absent, or otherwise applies the given function to combine the old and new values -- for example, a thread-safe word-count increment can be written concisely as map.merge(word, 1, Integer::sum). All of these methods guarantee atomicity without the caller needing any external synchronization.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to What is the poison pill pattern, and when and how do you use it?← Back to all Java Concurrency & Multithreading questions