When multiple threads access a collection at the same time, you ned thread-safe data structure to avoid:
- race conditions,
- ConcurrentModificationException,
- corrupted data.
Synchronized Collections (Legacy)
These are wrapper methods from Collections utility class.
List<String> syncList = Collections.synchronizedList(new ArrayList<>());
Feature | Behavior |
---|---|
Thread-safe? | β Yes (synchronized blocks) |
Performance | β Slower (global locking) |
Fail-safe Iterator | β No (ConcurrentModificationException) |
Synchronized wrappers use coarse-grained locking - one thread at a time.
Concurrent Collections (Modern)
These are built-in thread-safe classes from java.util.concurrent
.
Collection Type | Class Name | Notes |
---|---|---|
Map | ConcurrentHashMap | No locking entire map, segment-based |
List | CopyOnWriteArrayList | Copy-on-write on mutation (read-heavy use) |
Set | CopyOnWriteArraySet | Same idea, based on CopyOnWriteArrayList |
Queue | ConcurrentLinkedQueue | Non-blocking, lock-free queue |
Example
Map<String, Integer> map = new ConcurrentHashMap<>();
map.put("A", 1);
map.put("B", 2);
Use Case
Situation | Use This |
---|---|
Multi-threaded legacy code | Collections.synchronizedX |
High-performance apps | ConcurrentHashMap, etc. |
Read-heavy, write-rare | CopyOnWriteArrayList |
Blocking queues | ArrayBlockingQueue, etc. |
Tip
Be ready to:
- explain why regular ArrayList/HashMap isnβt thread-safe,
- compare synchronizedList() vs CopyOnWriteArrayList,
- know that iterating over synchronized collections still need external synchronization.
Parent: _Collections