Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ConcurrentHashMap — a concurrent key–value map

ConcurrentHashMap lets multiple threads safely use a shared map. Atomic operations for a key do not, however, turn a sequence of calls into a transaction.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

ConcurrentHashMap<K, V> map = new ConcurrentHashMap<>();
map.put(key, value);
map.get(key);
map.merge(key, value, remappingFunction);
map.computeIfAbsent(key, mappingFunction);
map.forEach((k, v) -> { /* action */ });

java.util.concurrent.ConcurrentHashMap is a thread-safe hash map implementing ConcurrentMap. It does not use one exclusion lock governing all access. It disallows null keys and values.

ConcurrentHashMap.put inserts or replaces a value and returns the previous value, or null if absent. ConcurrentHashMap.get returns the value or null. A sequence of get and put is not atomic: concurrent increments can lose updates.

ConcurrentHashMap.merge atomically inserts the supplied value for an absent key or combines the old and supplied values; a null result removes the entry. ConcurrentHashMap.computeIfAbsent atomically computes a missing value; a null result is not stored. Functions should be short and must not modify this map, because computations can block updates.

ConcurrentHashMap.forEach performs an action for entries without guaranteeing order. During concurrent changes, traversal is weakly consistent, not an atomic snapshot of the entire map. Map safety does not make mutable objects stored as values thread-safe.

Examples

import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

public class Main {
    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
        counts.put("java", 1);
        counts.merge("java", 1, Integer::sum);
        counts.computeIfAbsent("sql", key -> 0);
        System.out.println(counts.get("java"));

        TreeMap<String, Integer> sorted = new TreeMap<>();
        counts.forEach((key, value) -> sorted.put(key, value));
        System.out.println(sorted);
    }
}

Result

2
{java=2, sql=0}

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources