Please enable JavaScript.
Coggle requires JavaScript to display documents.
5.2 Concurrent Collections - Coggle Diagram
5.2 Concurrent Collections
Overview & Benefits
Introduced in Java 5.0 as an improvement over synchronized collections
Key differences from synchronized collections:
Better concurrency & scalability (no collection-wide locking)
Higher throughput with multiple threads
Key classes:
ConcurrentHashMap (replacement for synchronized Map)
CopyOnWriteArrayList (replacement for synchronized List)
Queue and BlockingQueue for element processing
ConcurrentHashMap
Improves on HashMap & synchronizedMap:
Uses lock striping for finer-grained locking
Allows multiple concurrent readers & limited writers
Weakly consistent iterators (do not throw ConcurrentModificationException)
Trade-offs:
size() and isEmpty() return approximate values
Cannot lock the entire map for exclusive access
Additional Atomic Map Operations
Since ConcurrentHashMap cannot be locked, atomic operations are provided:
putIfAbsent()
removeIfEqual()
replaceIfEqual()
Defined in ConcurrentMap interface
CopyOnWriteArrayList
Alternative to synchronized List, better for cases with frequent iteration & infrequent modification
Thread safety mechanism:
Modifications create a new copy of the collection
Iterators never throw ConcurrentModificationException
Trade-off:
High cost of copying entire array on modification
Best use case:
Event-notification systems where listeners rarely change
Queue & BlockingQueue
Queue: Temporarily holds elements for processing
Examples: ConcurrentLinkedQueue (FIFO), PriorityQueue (non-concurrent)
Non-blocking operations (returns null if empty)
BlockingQueue: Adds blocking insertion & retrieval
Useful for producer-consumer patterns
Blocks retrieval if empty, insertion if full
ConcurrentSkipListMap & ConcurrentSkipListSet
Introduced in Java 6
Thread-safe alternatives to TreeMap & TreeSet
Maintain sorted order while allowing concurrent access