Working with Concurrent Collections

1. Using ConcurrentHashMap

MethodUse
computeIfAbsent(k, fn)Atomic lazy init
compute(k, biFn)Atomic update
merge(k, v, biFn)Atomic combine
putIfAbsentAtomic put-if-empty
forEach(parallelism, action)Parallel iteration
reduce / searchConcurrent aggregation
NullForbidden as key or value

2. Using CopyOnWriteArrayList

TraitDetail
ReadLock-free, on snapshot
WriteCopies entire array
IteratorSnapshot, no CME
UseMany reads, rare writes (listeners)

3. Using CopyOnWriteArraySet

Backed ByUse
CopyOnWriteArrayListSame characteristics
addO(n) — duplicate check
BestSmall read-heavy sets

4. Using BlockingQueue Interface

MethodBehavior
put(e)Block if full
take()Block if empty
offer(e[, t, u])Timed
poll([t, u])Timed
Throwsadd/remove
Returns specialoffer/poll

5. Using LinkedBlockingQueue

AspectDetail
CapacityOptional (default Integer.MAX)
LocksTwo locks (put/take) → high concurrency
UseProducer-consumer at scale

6. Using ArrayBlockingQueue

AspectDetail
CapacityFixed (required)
LockSingle lock
FairnessOptional (FIFO waiting)
UseBounded back-pressure

7. Using PriorityBlockingQueue

AspectDetail
OrderNatural / Comparator
CapacityUnbounded (grows)
IteratorNo specific order
UsePriority task scheduling

8. Using ConcurrentLinkedQueue

AspectDetail
AlgorithmMichael & Scott lock-free
BlockingNone — non-blocking
size()O(n) — traversal
UseHigh-throughput producer/consumer

9. Using ConcurrentSkipListMap

AspectDetail
OrderSorted (NavigableMap)
OpsO(log n)
ConcurrencyLock-free
UseConcurrent ordered map (range queries)

10. Understanding Performance Trade-offs

CollectionBest ForAvoid When
ConcurrentHashMapHigh-concurrency K/VNeed ordering
CopyOnWrite*Read-mostlyFrequent writes
LinkedBlockingQueueProducer-consumerMemory bounded needed → use ArrayBlockingQueue
ConcurrentLinkedQueueLock-free FIFONeed backpressure
ConcurrentSkipListMapSorted concurrentO(1) lookup needed