Concurrent Collections in Java refer to a set of data structures designed to be safely manipulated by multiple threads without external synchronization. These collections are part of the java.util.concurrent
package and are specially built to handle concurrent access efficiently. Some examples of concurrent collections in Java are – ConcurrentHashMap
, ConcurrentLinkedQueue
, BlockingQueue
, etc.
Need of Concurrent Collection in Java
- Traditional collection objects (ArrayList, HashMap, etc) are not thread-safe because these can be accessed by multiple threads simultaneously and there may be a chance of data inconsistency
- Already existing Thread safe collection objects (Vector, HashTable, SynchronizedList, SynchronizedSet, SynchronizedMap) are not up to mark for performance.
- If one thread is interacting traditional collection object other threads are not allowed to modify the collection object simultaneously.
Hence traditional collection objects are not suitable for multi-threaded scalable applications. To overcome these problems concurrent collection is introduced in Java 1.5v.
Difference Between Traditional and Concurrent Collection
- Concurrent collections are always thread-safe
- Compared with traditional thread collections object performance of concurrent collection objects is higher because of different locking mechanisms.
- While one Thread is interacting with concurrent collections other threads are allowed to modify collections safely.
Hence concurrent collection never throw ConcurrentModificationException
Important Concurrent Classes
Sum of the important collection in Java includes-
- ConcurrentHashMap
- CopyOnWriteArrayList
- ConcurrentLinkedQueue
- BlockingQueue