1. Introduction
Java provides several concurrent collections under the java.util.concurrent package, which are designed for multi-threaded environments. These collections are optimized for thread safety and provide better performance compared to traditional synchronized collections.
2. ConcurrentHashMap
Functions:
put(K key, V value): Inserts a key-value pair into the map.get(Object key): Retrieves the value associated with the given key.remove(Object key): Removes the entry for the given key.compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction): Updates the value associated with the key using the provided function.forEach(long parallelismThreshold, BiConsumer<? super K, ? super V> action): Applies the given action for each entry, in parallel if necessary.
Internal Working:
- In Java 7, it used Segmented Locking, where the map was divided into multiple segments to allow concurrent updates.
- In Java 8, it uses CAS (Compare-And-Swap) operations and fine-grained locks on individual buckets for better performance.
- It supports full concurrency for read operations and limited concurrency for write operations.
3. CopyOnWriteArrayList
Functions:
add(E e): Appends the specified element to the list.get(int index): Retrieves the element at the specified index.set(int index, E element): Replaces the element at the specified index.remove(Object o): Removes the specified element.iterator(): Returns an iterator that does not throwConcurrentModificationException.
Internal Working:
- It creates a new copy of the array every time an update operation occurs.
- Read operations do not require synchronization as they work on a snapshot.
- Suitable for scenarios where reads are frequent and writes are infrequent.
4. CopyOnWriteArraySet
Functions:
add(E e): Adds the specified element if it is not already present.remove(Object o): Removes the specified element.contains(Object o): Checks if the set contains the specified element.
Internal Working:
- Internally backed by
CopyOnWriteArrayList. - Maintains unique elements using a copy-on-write mechanism.
5. ConcurrentLinkedQueue
Functions:
offer(E e): Inserts the specified element.poll(): Retrieves and removes the head of the queue.peek(): Retrieves, but does not remove, the head of the queue.isEmpty(): Checks if the queue is empty.
Internal Working:
- Uses a lock-free linked node structure.
- Uses CAS operations for insertions and removals.
- Ideal for non-blocking producer-consumer scenarios.
6. ConcurrentLinkedDeque
Functions:
addFirst(E e): Inserts an element at the front.addLast(E e): Inserts an element at the end.pollFirst(): Retrieves and removes the first element.pollLast(): Retrieves and removes the last element.
Internal Working:
- Similar to
ConcurrentLinkedQueuebut supports operations on both ends. - Uses a lock-free doubly linked list.
7. BlockingQueue Implementations
Types of BlockingQueue:
| Queue Type | Ordering | Blocking Behavior |
|---|---|---|
ArrayBlockingQueue | FIFO | Fixed-size queue |
LinkedBlockingQueue | FIFO | Bounded/unbounded queue |
PriorityBlockingQueue | Priority-based | Unbounded queue with custom ordering |
DelayQueue | Time-based order | Holds elements until expiration |
SynchronousQueue | No storage | Direct hand-off between threads |
Functions:
put(E e): Inserts an element, waiting if necessary.take(): Retrieves and removes the head, waiting if necessary.offer(E e, long timeout, TimeUnit unit): Inserts an element with a timeout.
Internal Working:
- Uses locks or condition variables for synchronization.
ArrayBlockingQueueuses a fixed-size array.LinkedBlockingQueueuses a linked list structure.PriorityBlockingQueueuses a heap-based priority ordering.
8. ConcurrentSkipListMap
Functions:
put(K key, V value): Inserts an element in sorted order.get(Object key): Retrieves the value for the specified key.higherKey(K key): Returns the least key greater than the given key.lowerKey(K key): Returns the greatest key less than the given key.
Internal Working:
- Implements a Skip List data structure.
- Provides logarithmic time complexity for search, insert, and delete operations.
- Uses lock-free algorithms for efficient concurrent access.
9. Summary
| Collection | Alternative to | Key Feature |
|---|---|---|
ConcurrentHashMap | HashMap | High-performance, lock-free reads |
CopyOnWriteArrayList | ArrayList | Best for read-heavy workloads |
CopyOnWriteArraySet | HashSet | Thread-safe set operations |
ConcurrentLinkedQueue | Queue | Non-blocking, lock-free queue |
ConcurrentLinkedDeque | Deque | Double-ended, non-blocking queue |
BlockingQueue | Queue | Blocks on full/empty conditions |
ConcurrentSkipListMap | TreeMap | Sorted map with concurrency |
These concurrent collections help in achieving thread safety, performance improvements, and efficient multi-threaded operations in Java applications.