Posted on: February 8, 2025 Posted by: rahulgite Comments: 0

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 throw ConcurrentModificationException.

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 ConcurrentLinkedQueue but supports operations on both ends.
  • Uses a lock-free doubly linked list.

7. BlockingQueue Implementations

Types of BlockingQueue:

Queue TypeOrderingBlocking Behavior
ArrayBlockingQueueFIFOFixed-size queue
LinkedBlockingQueueFIFOBounded/unbounded queue
PriorityBlockingQueuePriority-basedUnbounded queue with custom ordering
DelayQueueTime-based orderHolds elements until expiration
SynchronousQueueNo storageDirect 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.
  • ArrayBlockingQueue uses a fixed-size array.
  • LinkedBlockingQueue uses a linked list structure.
  • PriorityBlockingQueue uses 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

CollectionAlternative toKey Feature
ConcurrentHashMapHashMapHigh-performance, lock-free reads
CopyOnWriteArrayListArrayListBest for read-heavy workloads
CopyOnWriteArraySetHashSetThread-safe set operations
ConcurrentLinkedQueueQueueNon-blocking, lock-free queue
ConcurrentLinkedDequeDequeDouble-ended, non-blocking queue
BlockingQueueQueueBlocks on full/empty conditions
ConcurrentSkipListMapTreeMapSorted map with concurrency

These concurrent collections help in achieving thread safety, performance improvements, and efficient multi-threaded operations in Java applications.

Leave a Comment