Sub topic 12
Concurrent Collections: ConcurrentHashMap and Others
Earlier chapters showed how to protect your own data with synchronized and atomic classes. Most programs keep their data in collections, though: lists, maps, and queues. This chapter covers the collections Java provides that are already safe for many threads to use at once.
Why Normal Collections Break
A collection is an object that holds a group of other objects. Examples are ArrayList, HashMap, and HashSet.
These classes are not thread-safe. Thread-safe code still works correctly when many threads call it at the same time. If two threads add to a plain HashMap together, the map can lose entries, throw an exception, or end up with a broken internal structure.
You could wrap every call in a synchronized block, and that works. The cost is that only one thread can touch the map at a time, even when the threads are working on unrelated keys. The package java.util.concurrent has a better option.
What a Concurrent Collection Is
A concurrent collection is a collection built so that many threads can use it at once without you adding locks. Inside, it uses fine-grained locking and atomic operations, which lets threads that touch different parts of the collection work in parallel.
The most widely used one is ConcurrentHashMap. It works like a HashMap, but you can share it between threads safely.
The Trap: Check-Then-Act
Using a thread-safe map does not make all of your code safe. Each single call such as get or put is safe. A sequence of calls is not.
A check-then-act sequence is code that first checks something and then acts based on what it found. Here is a word counter that makes this mistake:
import java.util.concurrent.ConcurrentHashMap;
public class BrokenWordCounts {
private final ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
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
}
}
public int countOf(String word) {
return counts.getOrDefault(word, 0);
}
}Every call goes to a thread-safe map, and the code still has a race. Another thread can change the map between the get and the put. This is the same read-modify-write problem as count++ from the atomicity chapter, spread across two method calls.
The Fix: Atomic Map Methods
ConcurrentHashMap has methods that do the whole check-then-act as one atomic step. Atomic means no other thread can see or change the entry partway through.
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);
}
}merge(word, 1, Integer::sum) means: "If word is missing, store 1. If it is present, add 1 to the old value." The map does this while it holds a lock on that one entry, so no other thread can slip in between.
This program shows that the fix works. Put it in the same folder as WordCounts.java:
public class WordCountDemo {
public static void main(String[] args) throws InterruptedException {
WordCounts counts = new WordCounts();
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
counts.record("java");
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counts.countOf("java"));
}
}It always prints 200000. If you swap in BrokenWordCounts, you will often see a smaller number.
Other atomic methods
| Method | What it does in one atomic step | Typical use |
|---|---|---|
| `putIfAbsent(k, v)` | Stores `v` only if `k` has no value | Register something once |
| `computeIfAbsent(k, f)` | If `k` is missing, runs `f` and stores the result | Build a cache entry or a list on first use |
| `computeIfPresent(k, f)` | If `k` exists, replaces its value with `f`'s result | Update only existing entries |
| `compute(k, f)` | Always runs `f` with the old value (or `null`) | General update |
| `merge(k, v, f)` | Stores `v` if missing, otherwise combines old and `v` with `f` | Counters and totals |
| `replace(k, old, new)` | Changes the value only if it still equals `old` | Safe "compare then change" |
Here is a common pattern for grouping items into lists:
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class Groups {
private final ConcurrentHashMap<String, List<String>> groups = new ConcurrentHashMap<>();
public void add(String group, String member) {
groups.computeIfAbsent(group, g -> new CopyOnWriteArrayList<>()).add(member);
}
public List<String> members(String group) {
return groups.getOrDefault(group, List.of());
}
}The inner list has to be thread-safe too, because several threads may add to the same group's list. That is why it is a CopyOnWriteArrayList, which the next sections cover.
Edge Cases to Know
- Keep functions short. The function you pass to
computeormergeruns while part of the map is locked. Avoid slow work inside it, and never modify the same map from inside it. - Iteration does not throw. Looping over a
HashMapwhile another thread changes it can throwConcurrentModificationException. AConcurrentHashMapiterator is weakly consistent: it never throws, but it may or may not show changes made during the loop. size()is approximate while updates happen. If other threads are adding entries, the number can be out of date by the time you use it. Don't writeif (map.size() < 100) map.put(...)and expect a hard limit.- Compound actions across two keys are not atomic. Moving a value from key A to key B takes two operations. If that pair must be atomic, you need your own lock.
Other Concurrent Collections
CopyOnWriteArrayList
A CopyOnWriteArrayList makes a fresh copy of its internal array on every write. Reads never lock and never throw during iteration. Writes are slow, because each one copies the whole list. Use it when reads far outnumber writes, such as a list of event listeners.
BlockingQueue
A queue is a collection where items go in at one end and come out at the other. A BlockingQueue adds waiting: take() waits until an item exists, and put() waits when a bounded queue is full. It is the simplest way to pass work from one thread to another.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class QueueDemo {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 3; i++) {
queue.put("job " + i);
}
queue.put("DONE");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread consumer = new Thread(() -> {
try {
String job;
while (!(job = queue.take()).equals("DONE")) {
System.out.println("Handled " + job);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
consumer.start();
producer.join();
consumer.join();
}
}Choosing one
| Need | Use |
|---|---|
| Shared map, many readers and writers | `ConcurrentHashMap` |
| Shared set | `ConcurrentHashMap.newKeySet()` |
| List read often, changed rarely | `CopyOnWriteArrayList` |
| Hand work from one thread to another | `ArrayBlockingQueue` or `LinkedBlockingQueue` |
| Sorted map shared by threads | `ConcurrentSkipListMap` |
Exercises
Exercise
A teammate writes if (!map.containsKey(id)) { map.put(id, new Session()); } using a ConcurrentHashMap. Is this safe? If not, how would you fix it?
Show answer
It is not safe. It is a check-then-act sequence, so two threads can both see the key as missing and both put a Session, and one overwrites the other. Use map.computeIfAbsent(id, k -> new Session()) so the check and the insert happen as one atomic step.
Exercise
Why does counts.put("a", null) fail on a ConcurrentHashMap, and what could you store instead to mean "no value yet"?
Show answer
ConcurrentHashMap rejects null keys and values because get returning null must clearly mean "no entry." Store a placeholder value such as 0 or Optional.empty(), or don't insert the key until you have a real value.
Exercise
You have a list of listeners that is read every time an event fires (thousands of times per second) and changed only when the app starts. Which collection fits, and why?
Show answer
CopyOnWriteArrayList. Reads and iteration need no lock and never throw ConcurrentModificationException. The cost of copying on each write doesn't matter here because writes are rare.