Codectionary / Developer documentation / Java

Atomic Concurrent Map Updates

ConcurrentHashMap provides thread-safe map operations. merge performs a read/modify/write update atomically for one key, unlike a separate get followed by put. Save as Main.java and run with a Java 17+ JDK: java Main.java.

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"));
  }
}
  1. Expected output: 2000
  2. 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

Specifications & further reading