CodeBlanks Logo Icon CodeBlanks

ConcurrentHashMap

Learn parallel maps with ConcurrentHashMap.

ConcurrentHashMap

ConcurrentHashMap is a thread-safe map. Unlike HashMap, many threads can read and write concurrently; no synchronized lock is needed.

ConcurrentHashMap<String, Integer> map =
    new ConcurrentHashMap<>();
map.put("a", 1);
map.put("b", 2);

Internally it locks in segments, so most operations run in parallel. Methods like computeIfAbsent and merge provide atomic updates. This is ideal for high-volume caches and counters.

Atomic updates

computeIfAbsent computes and inserts the value if the key is absent, atomically. merge combines with the existing value.

map.computeIfAbsent("a", k -> 0);
map.merge("a", 1, Integer::sum);  // 0 + 1 = 1

These methods do insert-if-absent and update patterns without locks. They prevent race conditions; the code is both safer and shorter. This is the standard approach for high-volume counter applications.

Practice Counter with ConcurrentHashMap

Write main in a CounterDemo class; create a ConcurrentHashMap<String, Integer>. Call map.merge("a", 1, Integer::sum) three times. Finally print map.get("a").

Starter code

Main.java
import java.util.concurrent.*;

// Write main in CounterDemo

// Create a ConcurrentHashMap; increment "a" three times with merge; print get

Sample solution

Main.java
import java.util.concurrent.*;

class CounterDemo {
    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
        map.merge("a", 1, Integer::sum);
        map.merge("a", 1, Integer::sum);
        map.merge("a", 1, Integer::sum);
        System.out.println(map.get("a"));
    }
}

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the difference between ConcurrentHashMap and HashMap?

  • It is slower
  • It only accepts String keys
  • It is sorted
  • It is thread-safe Correct answer

Explanation: ConcurrentHashMap is thread-safe.

2 Match ConcurrentHashMap methods

Term Meaning
put Adds a value
get Reads a value
computeIfAbsent Computes if missing
merge Combines

3 Complete the computeIfAbsent call

Question
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.____("a", k -> 0);
Answer
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.computeIfAbsent("a", k -> 0);

Explanation: computeIfAbsent computes if absent.

All lessons in Advanced