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
MethodAtomic
putIfAbsentYes
computeIfAbsent / computeIfPresent / computeYes
merge(k, v, fn)Yes
forEach(parallelismThreshold, action)Bulk parallel

2. Using ConcurrentLinkedQueue

AspectDetail
TypeUnbounded, non-blocking, FIFO
AlgorithmLock-free (Michael-Scott)
Methodsoffer / poll / peek
size()O(n) — avoid

3. Using BlockingQueue

MethodBehavior on Empty/Full
add/removeThrow exception
offer/pollReturn false/null
put/takeBlock
offer(t,u) / poll(t,u)Timed wait

4. Using ArrayBlockingQueue

AspectDetail
TypeBounded, array-backed
FairnessOptional FIFO order via constructor

5. Using LinkedBlockingQueue

AspectDetail
TypeOptionally bounded, linked-list
ThroughputHigher than ArrayBlockingQueue (separate head/tail locks)

6. Using PriorityBlockingQueue

AspectDetail
TypeUnbounded, ordered by priority
OrderNatural or comparator
IterationNOT in priority order

7. Using DelayQueue

AspectDetail
Element typeImplements Delayed
Take blocksUntil delay expires
Use caseScheduled tasks, caches

8. Using SynchronousQueue

AspectDetail
CapacityZero — handoff only
BehaviorProducer blocks until consumer takes
Use caseCached thread pool

9. Using CopyOnWriteArrayList

AspectDetail
MutationCopies underlying array
ReadsLock-free, no ConcurrentModificationException
Best forRead-heavy, rare writes (event listeners)

10. Using CopyOnWriteArraySet

AspectDetail
BackingCopyOnWriteArrayList
Use caseRead-mostly sets

11. Using ConcurrentSkipListMap

AspectDetail
TypeConcurrent sorted map
BackingSkip list
PerformanceO(log n) operations, scalable

12. Using ConcurrentSkipListSet

AspectDetail
TypeConcurrent sorted set
BackingConcurrentSkipListMap

13. Choosing Concurrent Collections

NeedUse
Map (general)ConcurrentHashMap
Sorted mapConcurrentSkipListMap
Producer/consumerLinkedBlockingQueue
SchedulingDelayQueue / ScheduledExecutorService
Read-mostly listCopyOnWriteArrayList
Lock-free FIFOConcurrentLinkedQueue