java.util.concurrent package contains some additions to the Java Collections Framework. They are known as Java Concurrent Collections.
Concurrent Collections only consist of synchronized classes. Therefore we don’t have to take care of Thread-safety.
In the Traditional Collections, if a thread is iterating a Collection object and if another thread tries to add a new element in that iterating object simultaneously then we will get ConcurrentModificationException. However, we won’t get any Runtime Exception if we are Working with Concurrent Collections Classes.
Following are the concurrent collection classes –
- It is a first-in-first-out data structure.
- The blocking queue blocks or times out when you attempt to add to a full queue or retrieve it from an empty queue.
- While adding an element, if there is no space it can wait till it becomes available.
- When retrieving an element, it will wait until an element is available if it is empty.
- Types of blocking queue –
- ArrayBlockingQueue – It is a blocking queue class based on bounded Java Array. Once it’s instantiated, it cannot be resized.
- SynchronousQueue – It is a blocking queue class with a capacity of zero always.
- PriorityBlockingQueue – It is a priority queue based blocking queue. It is an unbounded concurrent collection.
- LinkedBlockingQueue – It is an optionally bounded concurrent collection. In addition, it orders elements based on the FIFO order.
- It is a queue where the only delay expired elements can be taken out. In addition, its an unbounded concurrent collection.
- It is an interface that extends BlockingQueue and adds the operations of Deque.
- LinkedBlockingDeque is an implementation class of BlockingDequeue.
- It is a concurrent collection interface.
- It extends the BlockingQueue.
- In addition, it adds a method where the producer will wait for the consumer to receive elements.
- LinkedTransferQueue is an implementation class of TransferQueue.
- ConcurrentMap is a Java concurrent collection interface and a type of Map.
- Above all, it guarantees thread safety and atomicity.
- Types of a concurrent map –
- ConcurrentHashMap –
- ConcurrentHashMap is an implementation class of ConcurrentMap.
- It allows concurrent writer and reader threads. In other words, it allows one thread to modify the map & the other thread to read values from the map at the same time.
- It has following atomic operations like
- putIfAbsent(key, value)
- remove(key, value)
- replace(key, value)
- replace(key, oldValue, newValue)
- ConcurrentNavigableMap – It is a Java concurrent collection interface that extends ConcurrentMap and adds operations of NavigableMap.
- ConcurrentSkipListMap – It is an implementation class of ConcurrentNavigableMap.
- ConcurrentHashMap –