Skip to main content
ConcurrentHashMap · Topic 2 of 6

merge and compute

Definition​

merge and compute update the value for one key as a single atomic step, so several threads can safely count or update without losing changes. A separate get followed by put is two steps and can lose updates.

Example code​

Four threads counting into one map

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Demo {
public static void main(String[] args) throws Exception {
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
ExecutorService pool = Executors.newFixedThreadPool(4);

for (int t = 0; t < 4; t++) {
pool.submit(() -> {
for (int i = 0; i < 10_000; i++) {
counts.merge("visits", 1, Integer::sum); // atomic read-modify-write
}
});
}
pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);

System.out.println(counts.get("visits")); // always 40000

counts.compute("visits", (key, old) -> old == null ? 1 : old * 2); // atomic custom update
System.out.println(counts.get("visits"));
}
}

// Output:
// 40000
// 80000

Finished this page? Track your progress (saved only in your browser).