Saturday, August 24, 2024

Top 5 Concurrent Collections Java Programmer Should Learn (with Examples)

Several new Collection classes are added in Java 5 and Java 6 especially concurrent alternatives of standard synchronized ArrayList, Hashtable and  synchronized HashMap collection classes. Many Java programmer still not familiar with these new collection classes from the java.util.concurrent package and misses a whole new set of functionality which can be utilized to build more scalable and high-performance Java application. In this Java tutorial, we will some of the useful collection classes like ConcurrentHashMap, BlockingQueue which provides some of the very useful functionalities to build concurrent Java applications.

By the way, this is not a comprehensive article explaining each feature of all these concurrent collections, Instead, I will just try to list out why they are there, which Collection class they replace, or provides an alternative for. 

The idea is to keep it short and simple while highlighting key points of those useful java.util.concurrent collections.

And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.





5 Concurrent Collections Every Java Programmer should learn

Here is my list of top 5 Concurrent Collections that I think every Java programmer should know, both beginners and experienced. These are very popular classes and you will often use them in your program. Having a good knowledge of these Concurrent collection classes will help you to write better code in Java. 

1. ConcurrentHashMap

ConcurrentHashMap is undoubtedly the most popular collection class introduced in Java 5 and most of us are already using it. ConcurrentHashMap provides a concurrent alternative to Hashtable or Synchronized Map classes with the aim to support a higher level of concurrency by implementing fined-grained locking. 

Multiple readers can access the Map concurrently  while a portion of Map gets locked for write operation depends upon concurrency level of Map.

The ConcurrentHashMap provides better scalability than their synchronized counterpart. Iterator of ConcurrentHashMap are fail-safe iterators that don't throw ConcurrencModificationException thus eliminates another requirement of locking during iteration which results in further scalability and performance.

If you want to learn more about ConcurrentHashMap and how to use it in Java then I highly recommend you to join a comprehensive Java collections course like Java Fundamentals: Collections by Richard Warburton on Pluralsight, it's a great course to learn about essential Collection classes and interface in Java. 

5 best Concurrent Collections for Java developers

By the way, you would need a Pluralsight membership to watch this course which costs around $29 per month or $199 per year (30% discount now). I highly recommend this subscription to all programmers as it provides instant access to more than 7000+ online courses to learn any tech skill. Alternatively, you can also use their 10-day-free-trial to watch this course for FREE.



2. CopyOnWriteArrayList and CopyOnWriteArraySet

CopyOnWriteArrayList is a concurrent alternative of synchronized List. CopyOnWriteArrayList provides better concurrency than synchronized List by allowing multiple concurrent readers and replacing the whole list on write operation. 

Yes, write operation is costly on CopyOnWriteArrayList but it performs better when there are multiple readers, and the requirement of iteration is more than writing. Since CopyOnWriteArrayList Iterator also doesn't throw ConcurrencModificationException it eliminates the need to lock the collection during iteration. 

Remember both ConcurrentHashMap and CopyOnWriteArrayList doesn't provide the same level of locking as Synchronized Collection and achieves thread-safety by their locking and mutability strategy. So they perform better if requirements suit their nature.

Similarly, CopyOnWriteArraySet is a concurrent replacement to Synchronized Set. See Java Application Performance and Memory Management course on Udemy to learn how to use CopyOnWriteArrayList to write high-performance Java applications. 

CopyOnArrayList in Java


3. BlockingQueue

BlockingQueue is also one of the better-known collection classes in Java 5. BlockingQueue makes it easy to implement producer-consumer design pattern by providing inbuilt blocking support for the put() and take() method. put() method will block if the Queue is full while the take() method will block if the Queue is empty. 

Java 5 API provides two concrete implementation of BlockingQueue in form of ArrayBlockingQueue and LinkedBlockingQueue, both of them implement FIFO ordering of elements. ArrayBlockingQueue is backed by Array and it's bounded in nature while LinkedBlockingQueue is optionally bounded. 

Consider using BlockingQueue to solve the producer-consumer problem in Java instead of writing your won wait-notify code. Java 5 also provides PriorityBlockingQueue, another implementation of BlockingQueue which is ordered on priority and useful if you want to process elements on order other than FIFO.

If you want to learn more about BlockingQueue from an interview point of view then you can also check out Java Interview Guide: 200+ Interview Questions and Answers course on Udemy to not just learn about BlockingQueue but also other useful Java concept for interviews. 

Blocking in Java with Producer Consumer pattern






4. Deque and BlockingDeque

Deque interface is added in Java 6 and it extends Queue interface to support insertion and removal from both ends of Queue referred to as head and tail. Java6 also provides a concurrent implementation of Deque like ArrayDeque and LinkedBlockingDeque

Deque Can be used efficiently to increase parallelism in the program by allowing a set of worker thread to help each other by taking some of the workloads from other thread by utilizing Deque double end consumption property. 

So if all Thread has their own set of task Queue and they are consuming from the head; helper the thread can also share some workload via consumption from the tail.

Deque or double ended queue in Java





5. ConcurrentSkipListMap and ConcurrentSkipListSet

Just like ConcurrentHashMap provides a concurrent alternative of synchronized HashMap. ConcurrentSkipListMap and ConcurrentSkipListSet provide concurrent alternative for synchronized version of SortedMap and SortedSet

For example instead of using TreeMap or TreeSet wrapped inside synchronized Collection, You can consider using ConcurrentSkipListMap or ConcurrentSkipListSet from java.util.concurrent package.

They also implement NavigableMap and NavigableSet to add additional navigation methods we have seen in our post How to use NavigableMap in Java.

oncurrentSkipListMap and ConcurrentSkipListSet  in Java




Java Concurrent Collections from JDK 5 and 6 Example TutorialThat’s all on this list of the important concurrent Collection classes for Java developers. They have been added on java.util.concurrent package as a concurrent alternative of their synchronized counterpart. It’s a good idea to learn these Collection classes along with other popular classes from the Java Collection Framework to become a better Java developer this year. 


Related Java Collection Tutorials from Javarevisited Blog

6 comments:

  1. Nice Stuff ..could you provide some programs using the above concurrent collection classes like producer & consumer by using BlockingQue.

    ReplyDelete
  2. ConcurrentHashMaps also consume a lot of memory compared to a regular HashMap (1,7kb for an empty CCH as described here: http://www.javatuning.com/concurrenthashmap-fat-memory-footprint/).

    ReplyDelete
  3. Also worth mentioning the Guava library set that adds a few more thread safe collections

    ReplyDelete
  4. Are concurrent collections are same as thread safe collection in Java? What is different between older thread safe collection e.g. Vector and Hashtable and new thread-safe collection classes like CopyOnWriteArrayList and ConcurrentHashMap?

    ReplyDelete
  5. explained very well, but take care of spelling mistakes.

    ReplyDelete