Working with Concurrent Collections
1. Using ConcurrentHashMap
| Method | Use |
|---|---|
computeIfAbsent(k, fn) | Atomic lazy init |
compute(k, biFn) | Atomic update |
merge(k, v, biFn) | Atomic combine |
putIfAbsent | Atomic put-if-empty |
forEach(parallelism, action) | Parallel iteration |
reduce / search | Concurrent aggregation |
| Null | Forbidden as key or value |
2. Using CopyOnWriteArrayList
| Trait | Detail |
|---|---|
| Read | Lock-free, on snapshot |
| Write | Copies entire array |
| Iterator | Snapshot, no CME |
| Use | Many reads, rare writes (listeners) |
3. Using CopyOnWriteArraySet
| Backed By | Use |
|---|---|
| CopyOnWriteArrayList | Same characteristics |
| add | O(n) — duplicate check |
| Best | Small read-heavy sets |
4. Using BlockingQueue Interface
| Method | Behavior |
|---|---|
put(e) | Block if full |
take() | Block if empty |
offer(e[, t, u]) | Timed |
poll([t, u]) | Timed |
| Throws | add/remove |
| Returns special | offer/poll |
5. Using LinkedBlockingQueue
| Aspect | Detail |
|---|---|
| Capacity | Optional (default Integer.MAX) |
| Locks | Two locks (put/take) → high concurrency |
| Use | Producer-consumer at scale |
6. Using ArrayBlockingQueue
| Aspect | Detail |
|---|---|
| Capacity | Fixed (required) |
| Lock | Single lock |
| Fairness | Optional (FIFO waiting) |
| Use | Bounded back-pressure |
7. Using PriorityBlockingQueue
| Aspect | Detail |
|---|---|
| Order | Natural / Comparator |
| Capacity | Unbounded (grows) |
| Iterator | No specific order |
| Use | Priority task scheduling |
8. Using ConcurrentLinkedQueue
| Aspect | Detail |
|---|---|
| Algorithm | Michael & Scott lock-free |
| Blocking | None — non-blocking |
| size() | O(n) — traversal |
| Use | High-throughput producer/consumer |
9. Using ConcurrentSkipListMap
| Aspect | Detail |
|---|---|
| Order | Sorted (NavigableMap) |
| Ops | O(log n) |
| Concurrency | Lock-free |
| Use | Concurrent ordered map (range queries) |
10. Understanding Performance Trade-offs
| Collection | Best For | Avoid When |
|---|---|---|
| ConcurrentHashMap | High-concurrency K/V | Need ordering |
| CopyOnWrite* | Read-mostly | Frequent writes |
| LinkedBlockingQueue | Producer-consumer | Memory bounded needed → use ArrayBlockingQueue |
| ConcurrentLinkedQueue | Lock-free FIFO | Need backpressure |
| ConcurrentSkipListMap | Sorted concurrent | O(1) lookup needed |