1. Why regular collections are not suitable for multithreading
Let’s recall how we worked with collections in our main application (for example, a chat room):
List<String> messages = new ArrayList<>();
messages.add("Hi!");
messages.add("How are you?");
In a single-threaded program, everything is fine. But if multiple threads simultaneously add, remove, or read elements from the same collection—welcome to the world of race conditions, inconsistent state, and mysterious bugs.
For example, one thread adds an element, another removes one, a third iterates—and suddenly you get ConcurrentModificationException, sometimes even ArrayIndexOutOfBoundsException, or just a “corrupted” collection.
A classic:
List<String> list = new ArrayList<>();
Runnable writer = () -> {
for (int i = 0; i < 1000; i++) {
list.add("msg-" + i);
}
};
Runnable reader = () -> {
for (String msg : list) {
// ...
}
};
// Start writer and reader in different threads — you'll get bugs!
Takeaway: Regular collections (ArrayList, HashMap, HashSet, etc.) are NOT thread-safe. You must not use them from multiple threads without additional synchronization (synchronized, locks, etc.).
2. What thread-safe collections Java provides
Java does not leave you on your own. For multithreaded tasks, the java.util.concurrent package has a whole collection of collections (sorry for the tautology) that you can safely use from multiple threads.
Core thread-safe collections:
| Collection | Where to use | Features |
|---|---|---|
|
Map, cache, frequent access | High performance, no global lock |
|
List, infrequent writes, frequent reads | Fast reads, slow writes |
|
Set, infrequent writes, frequent reads | Same idea as the copy-on-write list |
|
Queue, FIFO | Fast, non-blocking, task queues |
|
Sorted map (NavigableMap) | Thread-safe counterpart to TreeMap |
|
Sorted set | Thread-safe counterpart to TreeSet |
|
Blocking queues (thread pools) | Interface, many implementations |
Important! The old good Collections.synchronizedList(list) and friends are not the same as the modern collections from java.util.concurrent. Details—just below.
3. ConcurrentHashMap: your friend in the multithreaded world
ConcurrentHashMap<K, V> is essentially the same HashMap, just powered up for multithreading. It allows multiple threads to safely read and write data at the same time without locking the entire map.
With a regular HashMap, if you want thread-safe access, you have to lock the whole structure—and it immediately turns into a bottleneck: while one thread works, the others wait.
ConcurrentHashMap solves this problem more intelligently. In early versions, the map was divided into segments with separate locks; in newer implementations, lightweight atomic operations (CAS) are used at the level of individual buckets. Thanks to this, threads can safely work in parallel if they don’t touch the same data.
Example of using ConcurrentHashMap
import java.util.concurrent.ConcurrentHashMap;
public class ChatStats {
private final ConcurrentHashMap<String, Integer> userMessageCount = new ConcurrentHashMap<>();
public void increment(String user) {
// Atomically increment the value
userMessageCount.merge(user, 1, Integer::sum);
}
public int getCount(String user) {
return userMessageCount.getOrDefault(user, 0);
}
}
What matters here:
- You can call the methods from different threads—everything will be correct.
- The merge method is atomic: if several threads increment the counter at the same time, the result will be correct.
- Reads do not require additional synchronization.
How is ConcurrentHashMap better than synchronizedMap?
Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
When you use synchronizedMap, any operation—read, write, or delete—locks the whole map. While one thread is working with the data, the others have to wait their turn.
ConcurrentHashMap is arranged much more elegantly: it allows multiple threads to read and even modify data at the same time, provided they are not addressing the same parts of the map (buckets). As a result, in real multithreaded systems it shows significantly better performance—sometimes the difference is an order of magnitude or more.
4. CopyOnWriteArrayList and CopyOnWriteArraySet
CopyOnWriteArrayList and CopyOnWriteArraySet are special collections that, on every modification (for example, on add() or remove()), create a new copy of the entire array. On the other hand, reading from them happens without any synchronization and is fully thread-safe.
Imagine you have a guest list for a party. Every time someone comes or leaves, you rewrite the list from scratch and hand out fresh copies to everyone. A bit wasteful, but nobody gets confused about who’s currently there.
When this is truly convenient
- Reads occur frequently, while writes are rare.
- A classic case is a list of event listeners: handlers are added infrequently, but events arrive constantly.
Example: chat listeners
import java.util.concurrent.CopyOnWriteArrayList;
public class ChatRoom {
private final CopyOnWriteArrayList<ChatListener> listeners = new CopyOnWriteArrayList<>();
public void addListener(ChatListener listener) {
listeners.add(listener);
}
public void removeListener(ChatListener listener) {
listeners.remove(listener);
}
public void sendMessage(String message) {
// Thread-safe even if someone subscribes/unsubscribes right now
for (ChatListener listener : listeners) {
listener.onMessage(message);
}
}
}
Important characteristics:
- Iterating over CopyOnWriteArrayList will never throw ConcurrentModificationException.
- Modifications (add/remove) are expensive in time and memory (the entire array is copied!).
- Do not use it for large collections with frequent modifications.
5. Other thread-safe collections
ConcurrentLinkedQueue
ConcurrentLinkedQueue is a non-blocking FIFO queue. It allows multiple threads to safely add and remove elements simultaneously without explicit locks. It’s often used to pass tasks between threads—fast and without bottlenecks.
import java.util.concurrent.ConcurrentLinkedQueue;
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
queue.add("task1");
String task = queue.poll(); // returns null if the queue is empty
ConcurrentSkipListMap and ConcurrentSkipListSet
- Thread-safe counterparts to TreeMap and TreeSet.
- Elements are always sorted.
- Used when maintaining key order is important.
import java.util.concurrent.ConcurrentSkipListMap;
ConcurrentSkipListMap<Integer, String> sortedMap = new ConcurrentSkipListMap<>();
sortedMap.put(10, "a");
sortedMap.put(2, "b");
System.out.println(sortedMap.firstEntry()); // 2=b
BlockingQueue and its implementations
- An interface for queues that support blocking operations (wait until an element appears/space is available).
- Implementations: ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, etc.
- Used in thread pools, for the producer–consumer pattern.
import java.util.concurrent.ArrayBlockingQueue;
ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(10);
blockingQueue.put("task"); // Blocks if the queue is full
String t = blockingQueue.take(); // Blocks if the queue is empty
6. Examples: safe operations with collections
Example 1: Thread-safe map for counting messages
import java.util.concurrent.ConcurrentHashMap;
ConcurrentHashMap<String, Integer> messageCount = new ConcurrentHashMap<>();
// Thread 1
messageCount.put("Anna", 1);
// Thread 2
messageCount.put("Anna", messageCount.getOrDefault("Anna", 0) + 1); // Not atomic!
// Correct (atomic):
messageCount.merge("Anna", 1, Integer::sum);
Example 2: Iteration over CopyOnWriteArrayList
import java.util.concurrent.CopyOnWriteArrayList;
CopyOnWriteArrayList<String> users = new CopyOnWriteArrayList<>();
users.add("Anton");
users.add("Maria");
for (String user : users) {
System.out.println(user);
users.remove(user); // Will not throw ConcurrentModificationException!
}
System.out.println(users); // []
Example 3: A task queue between threads
import java.util.concurrent.ConcurrentLinkedQueue;
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
// Producer thread
queue.add("task-1");
// Consumer thread
String task = queue.poll(); // null if empty
7. Useful nuances
When (and why) to use thread-safe collections
Using thread-safe collections makes sense if:
- The same collection is shared between multiple threads.
- You don’t want to manually synchronize each operation.
- It’s important to avoid race conditions and consistency bugs.
Typical scenarios:
- A cache in a multithreaded system (for example, ConcurrentHashMap for storing user sessions).
- Task queues between threads (ConcurrentLinkedQueue, BlockingQueue).
- Lists of event listeners (CopyOnWriteArrayList).
- Multithreaded data processing (for example, MapReduce-style).
Limitations and pitfalls
- Operations spanning multiple elements are not atomic. A pattern like if (!map.containsKey(k)) map.put(k, v) is not atomic. Use putIfAbsent, computeIfAbsent, merge.
- CopyOnWriteArrayList is inefficient with frequent modifications. For large sizes and frequent add/remove, the overhead skyrockets.
- Iteration over ConcurrentHashMap is “weak.” Traversal gives a weakly consistent snapshot: you may not see some concurrent changes.
- Thread-safe collections don’t solve all synchronization problems. If your logic touches several collections/variables at once, you’ll need external synchronization (synchronized, locks, atomic classes).
8. Common mistakes when working with thread-safe collections
Error #1: Expecting magic from thread-safe collections. “Since a collection is thread-safe, I can do anything and ignore synchronization.” Unfortunately, sequences of multiple operations (check + insert) are not atomic. Use specialized methods: putIfAbsent, compute, merge.
Error #2: Using CopyOnWriteArrayList for large, frequently modified collections. It’s great for listener lists, but with 10,000+ elements and frequent changes you’ll incur high memory and time costs.
Error #3: ConcurrentModificationException when using regular collections. You iterate over an ArrayList or HashMap while another thread modifies the collection—expect a ConcurrentModificationException. Use specialized collections or lock access manually.
Error #4: Forgetting about the atomicity of complex operations. If you need to modify several collections at once or perform a series of related actions, thread-safe collections won’t help. Apply external synchronization or transactional logic.
Error #5: Mistakes when iterating over ConcurrentHashMap. Iteration is weakly consistent: you cannot use the iterator as a “snapshot” of the map’s state. For a consistent snapshot, copy the data into a separate structure.
GO TO FULL VERSION