wasAsked.

Explain Java collection choices for concurrent read-and-write workloads and their performance tradeoffs.

BrowserStack · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, Software Engineering

Community answers

Posted by wasAsked editorial collection

Choose based on read/write ratio, ordering needs and contention. Maps - ConcurrentHashMap: the default for concurrent key-value access. Lock-free reads and fine-grained locking on writes (per bin), with atomic operations such as computeIfAbsent, merge and compute. Note that computeIfAbsent holds a lock on that bin while the function runs, so keep the function fast and non-blocking. - Collections.synchronizedMap / Hashtable: one lock for everything, so all reads and writes contend. Generally avoid for busy workloads. - ConcurrentSkipListMap: thread-safe and sorted (navigable), O(log n), useful for ordered keys or range queries. Lists and sets - CopyOnWriteArrayList / CopyOnWriteArraySet: each write copies the whole array, while reads and iteration need no locks and never throw ConcurrentModificationException. Ideal for read-mostly data such as listener lists or configuration; terrible for frequent writes or large lists. - Collections.synchronizedList: simple single lock; iteration still needs manual synchronisation. - ConcurrentHashMap.newKeySet() for a concurrent hash set; ConcurrentSkipListSet for a sorted one. Queues (producer-consumer) - ConcurrentLinkedQueue / ConcurrentLinkedDeque: lock-free and non-blocking, unbounded. - ArrayBlockingQueue: bounded, single lock, provides backpressure. - LinkedBlockingQueue: optionally bounded, separate locks for put and take, so producers and consumers contend less. - LinkedTransferQueue, PriorityBlockingQueue, DelayQueue and SynchronousQueue for specialised cases. - Prefer bounded queues so a slow consumer causes backpressure instead of OutOfMemoryError. Immutable and snapshot approaches - Read-mostly configuration: build an immutable map (Map.copyOf) and replace the reference atomically (a volatile field or AtomicReference). Readers never lock and always see a consistent snapshot. Counters and statistics - AtomicLong for moderate contention; LongAdder for highly contended counters (it spreads updates across cells and sums on read). Performance trade-offs summary - Read-heavy, rarely changing: immutable snapshot or CopyOnWrite. - Mixed reads and writes on keys: ConcurrentHashMap. - Ordered data: ConcurrentSkipListMap (slower than a hash map). - Hand-off between threads: blocking queues with bounds. Also remember: thread-safe collections make single operations safe, but compound operations ("check then put") still need atomic methods (putIfAbsent, compute) or external locking. Measure with JMH under realistic contention before optimising.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics