Concurrent collections are introduced in java 5 to increase scalable multithreaded java applications.
Prior to java 5, if you have to deal with collections in multithreaded application you either used synchronized collections or regular collections.
Both of these can be synchronized where HashTable and vector are already synchronized and arrayList and HashMap can be synchronized using utility class under java.collections package.
Before java 5, if one thread is reading a collection resource and the same time when second thread tries to update it then you get “ConcurrentModificationException” which is not desirable.
To overcome this problem, the concept of concurrency come into picture. It provides the following methods:
- Concurrent HashMap.
ConcurrentHashMap uses concept of lock stripping so while one thread is iterating the collection and another thread is updating the collection, they will sync up at some point.
Where, CopyOnWriteArrayList and CopyOnWriteArrayList keeping cloning the collection every time when a write is made to the collection and then at some point they will sync up.
So using concurrent collections, we can use collections across multiple threads.
Note: use concurrent collections when you are using less writes and more read through the collection object.
When you are using a lot of writes in application you will clone every time the collection object which will degrade the performance of the program.