
Concurrent collections in Java are designed with the goal of allowing many threads to access the same data in a synchronized manner. In other words, Concurrent collections in Java allow many threads to access the same data synchronously.
If you’re familiar with Java Collections, you’re probably aware that most Collection classes aren’t thread-safe by default. Take, for example, Java’s ArrayList, LinkedList, HashMap classes. We must manually make the collection thread-safe if we want it to be thread-safe.
If we iterate the collection class, if multiple threads are working on it, and if another thread tries to modify the collection, we get ConcurrentModificationException. This is due to the fact that the class is not thread-safe. For programmers developing multithreaded applications, this was a major concern.
However, the java.util.concurrent package has a set of thread-safe collection classes. These thread-safe classes help developers avoid the issues mentioned above.
Table of Contents
Advantages of using concurrent classes
- Concurrent classes provide unique locking system.
- All concurrent classes are guaranteed to be thread safe.
- The performance of concurrent classes are much better than that of traditional thread-safe classes.
- We can update the data while iterating the collection elements, so we will not get ConcurrentModificationException.
Top Concurrent Collections in Java
- ConcurrentHashMap
- CopyOnWriteArrayList
- CopyOnWriteArraySet
ConcurrentHashMap in Java with example
The most popular class is ConcurrentHashMap, which is thread-safe and uses segment locking rather than whole-object locking. It can manage a lot of concurrency and can be used instead of Hashtable and SynchronizedMap.
ConcurrentHashMap has a higher scalability than the synchronised version. There is no need to lock during iteration, which improves scalability and speed.
Internally, the entire ConcurrentHashMap object will be partitioned into many pieces, each with its own lock. It is based on the locking of bucket levels.
In ConcurrentHashMap, null entries are not permitted for both the key and the value.
ConcurrentHashMap example
import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapDemo { public static void main(String[] args) { ConcurrentHashMap<String, String> cmap = new ConcurrentHashMap<String, String>(); cmap.put("Key 1", "Value 1"); cmap.put("Key 2", "Value 2"); cmap.put("Key 3", "Value 3"); for (Map.Entry<String, String> map : cmap.entrySet()) { System.out.println(map.getKey() + " " + map.getValue()); } } }
Output: Key 1 Value 1 Key 2 Value 2 Key 3 Value 3
CopyOnWriteArrayList in java with example
CopyOnWriteArrayList is a thread-safe alternative to synchronized ArrayList. It creates a clone copy of the list when we perform update operation.
Because each update action will result in a cloned copy of the list, it is never suggested to use it because it is inefficient in terms of performance.
CopyOnWriteArrayList allows the duplicate and heterogenous object. You can insert null values and the insertion order is preserved.
import java.util.concurrent.CopyOnWriteArrayList; public class CopyOnWriteArrayListDemo { public static void main(String[] args) { CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>(); list.add("Concurrent Collections"); list.add("Traditional Collections"); System.out.println(list); } }
Output: [Concurrent Collections, Traditional Collections]
CopyOnWriteArraySet in Java with example
CopyOnWriteArraySet is a thread-safe alternative to synchronized HashSet. It creates a clone copy of the set when we perform update operation.
Duplicate elements are not allowed in CopyOnWriteArraySet, however heterogeneous elements are allowed.
import java.util.Iterator; import java.util.concurrent.CopyOnWriteArraySet; public class CopyOnWriteArraySetDemo { public static void main(String[] args) { CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<String>(); set.add("First Element"); set.add("Second Element"); set.add("Third Element"); Iterator<String> iterator = set.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
Output: First Element Second Element Third Element
In conclusion, Hope you got some idea about Concurrent Collections, When to use it?, Why should you use it?
Also Read: Java fork/join for parallel programming