Sub topic 12
Concurrent Collections: ConcurrentHashMap and Others
A collection is an object that holds many values, like a List or a Map. The usual ones, such as HashMap and ArrayList, are not thread-safe. Thread-safe means the code works correctly even when many threads use it at the same time. If two threads change a HashMap together, entries can be lost or the map can break.
Java has a package, java.util.concurrent, full of collections built for many threads. This chapter focuses on ConcurrentHashMap, the one you will use most.
The Check-Then-Act Trap
A check-then-act sequence is code that first looks at a value and then makes a choice based on what it saw. Here is one that counts words:
import java.util.HashMap;
import java.util.Map;
public class UnsafeWordCounts {
private final Map<String, Integer> counts = new HashMap<>();
public void record(String word) {
Integer old = counts.get(word); // check
if (old == null) {
counts.put(word, 1); // act
} else {
counts.put(word, old + 1); // act
}
}
}Two threads can both call get and both see the same old value. Then both call put with the same new value. One count is lost. Swapping HashMap for ConcurrentHashMap does not fix this. Each single call is safe, but the gap between get and put is still open.
Atomic Methods on ConcurrentHashMap
ConcurrentHashMap has methods that do the check and the act as one atomic step. Atomic means no other thread can slip in halfway through. The merge method takes a key, a starting value, and a function. If the key is missing, it stores the starting value. If the key is present, it combines the old value and the new one with the function.
import java.util.concurrent.ConcurrentHashMap;
public class WordCounts {
private final ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
public void record(String word) {
counts.merge(word, 1, Integer::sum);
}
public int countOf(String word) {
return counts.getOrDefault(word, 0);
}
public static void main(String[] args) throws InterruptedException {
WordCounts wc = new WordCounts();
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
wc.record("cat");
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(wc.countOf("cat")); // always 200000
}
}Other useful atomic methods are putIfAbsent, computeIfAbsent, and compute.
Other Concurrent Collections
| Collection | Use it when |
|---|---|
| `ConcurrentHashMap` | Many threads read and update a map |
| `CopyOnWriteArrayList` | A list is read often and changed rarely, like a list of listeners |
| `ConcurrentLinkedQueue` | Threads add and remove items from a queue without waiting |
| `LinkedBlockingQueue` | One thread produces work and another waits to take it |
Exercise
A program uses a ConcurrentHashMap and runs if (!map.containsKey(k)) { map.put(k, v); } on several threads. Is it safe? How would you fix it?
Show answer
It is not safe. Two threads can both see the key missing and both call put, so one value overwrites the other. Use map.putIfAbsent(k, v), which checks and stores in one atomic step.
Exercise
Which collection fits a list of event listeners that is read on every event but changed only when a listener is added?
Show answer
CopyOnWriteArrayList, because reads are fast and need no locking, and the rare writes can afford the cost of copying the list.