Concurrent collections are data structures in Java that are intended for usage in multi-threaded concurrent situations. They enable thread-safe operations that allow several threads to access and modify data simultaneously without requiring explicit synchronization.
Need For Concurrent Collections
- Because the Collection framework is non-synchronized, most Collection classes are not thread-safe.
- HashMap, like ArrayList and LinkedList, is non-synchronized.
- Suppose many threads do any operation on an item at the same time. The data will then be out of sync, resulting in data redundancy.
- We can't change the collection while iterating over the Collection object. When we attempt to change the collection, we get a ConcurrentModificationException. Non-synchronized groups are thus unsuitable for multi-threaded applications.
In the java.util.concurrent package, various built-in concurrent collection classes can be used to create concurrent algorithms effectively. Concurrent collections that are often used in Java include:
- CopyOnWriteArrayList: This thread-safe array list implementation supports concurrent reads and changes. It makes a fresh copy of the underlying array whenever a change is made, ensuring that changes do not interfere with ongoing iterations by other threads.
- CopyOnWriteArraySet: A thread-safe set implementation that supports concurrent reads and changes. It internally stores the elements in a CopyOnWriteArrayList, ensuring that changes do not interfere with ongoing iterations by other threads.
- ConcurrentHashMap: This thread-safe hash map implementation allows for concurrent changes. It has comparable functionality to HashMap, but it also has methods for simultaneous access, such as replace(), compute(), and merge().