Syntax
counts.merge(key, 1, Integer::sum)Examples
Atomic Concurrent Map Updates
Save as Main.java and run with a Java 17+ JDK: java Main.java.
import java.util.concurrent.ConcurrentHashMap;
public class Main {
public static void main(String[] args) throws Exception {
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
Thread a = new Thread(() -> { for (int i = 0; i < 1000; i++) counts.merge("hits", 1, Integer::sum); });
Thread b = new Thread(() -> { for (int i = 0; i < 1000; i++) counts.merge("hits", 1, Integer::sum); });
a.start(); b.start();
a.join(); b.join();
System.out.println(counts.get("hits"));
}
}- Expected output: 2000
- Both workers update the same key. Atomic merging prevents lost increments; joining ensures printing happens after both finish.
Best practices
- Keep remapping functions short and avoid recursively updating the same map.
- Do not infer atomicity across multiple keys from single-key guarantees.
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification