Working with Concurrent Collections
1. Using ConcurrentHashMap
Example: ConcurrentHashMap
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.computeIfAbsent("key", k -> 0);
map.compute("counter", (k, v) -> v == null ? 1 : v + 1);
map.merge("hits", 1, Integer::sum);
map.forEach(4, (k, v) -> ...); // parallelism threshold
| Method | Atomic |
|---|---|
putIfAbsent | Yes |
computeIfAbsent / computeIfPresent / compute | Yes |
merge(k, v, fn) | Yes |
forEach(parallelismThreshold, action) | Bulk parallel |
2. Using ConcurrentLinkedQueue
| Aspect | Detail |
|---|---|
| Type | Unbounded, non-blocking, FIFO |
| Algorithm | Lock-free (Michael-Scott) |
| Methods | offer / poll / peek |
size() | O(n) — avoid |
3. Using BlockingQueue
| Method | Behavior on Empty/Full |
|---|---|
add/remove | Throw exception |
offer/poll | Return false/null |
put/take | Block |
offer(t,u) / poll(t,u) | Timed wait |
4. Using ArrayBlockingQueue
| Aspect | Detail |
|---|---|
| Type | Bounded, array-backed |
| Fairness | Optional FIFO order via constructor |
5. Using LinkedBlockingQueue
| Aspect | Detail |
|---|---|
| Type | Optionally bounded, linked-list |
| Throughput | Higher than ArrayBlockingQueue (separate head/tail locks) |
6. Using PriorityBlockingQueue
| Aspect | Detail |
|---|---|
| Type | Unbounded, ordered by priority |
| Order | Natural or comparator |
| Iteration | NOT in priority order |
7. Using DelayQueue
| Aspect | Detail |
|---|---|
| Element type | Implements Delayed |
| Take blocks | Until delay expires |
| Use case | Scheduled tasks, caches |
8. Using SynchronousQueue
| Aspect | Detail |
|---|---|
| Capacity | Zero — handoff only |
| Behavior | Producer blocks until consumer takes |
| Use case | Cached thread pool |
9. Using CopyOnWriteArrayList
| Aspect | Detail |
|---|---|
| Mutation | Copies underlying array |
| Reads | Lock-free, no ConcurrentModificationException |
| Best for | Read-heavy, rare writes (event listeners) |
10. Using CopyOnWriteArraySet
| Aspect | Detail |
|---|---|
| Backing | CopyOnWriteArrayList |
| Use case | Read-mostly sets |
11. Using ConcurrentSkipListMap
| Aspect | Detail |
|---|---|
| Type | Concurrent sorted map |
| Backing | Skip list |
| Performance | O(log n) operations, scalable |
12. Using ConcurrentSkipListSet
| Aspect | Detail |
|---|---|
| Type | Concurrent sorted set |
| Backing | ConcurrentSkipListMap |
13. Choosing Concurrent Collections
| Need | Use |
|---|---|
| Map (general) | ConcurrentHashMap |
| Sorted map | ConcurrentSkipListMap |
| Producer/consumer | LinkedBlockingQueue |
| Scheduling | DelayQueue / ScheduledExecutorService |
| Read-mostly list | CopyOnWriteArrayList |
| Lock-free FIFO | ConcurrentLinkedQueue |