What is difference between Synchronized and Concurrent Collections in Java?

Synchronized vs Concurrent Collections
Though both Synchronized and Concurrent Collection classes provide thread-safety, the differences between them comes  in performance, scalability and how they achieve thread-safety. Synchronized collections like synchronized HashMap, Hashtable, HashSet, Vector, and synchronized ArrayList are much slower than their concurrent counterparts e.g. ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteHashSet. Main reason for this slowness is locking; synchronized collections locks the whole collection e.g. whole Map or List while concurrent collection never locks the whole Map or List. They achieve thread safety by using advanced and sophisticated techniques like lock stripping. For example, the ConcurrentHashMap divides the whole map into several segments and locks only the relevant segments, which allows multiple threads to access other segments of same ConcurrentHashMap without locking.

Similarly, CopyOnWriteArrayList allows multiple reader threads to read without synchronization and when a write happens it copies the whole ArrayList and swap with a newer one.

So if you use concurrent collection classes in their favorable conditions e.g. for more reading and fewer updates, they are much more scalable than synchronized collections.

By the way, Collection classes are the heart of Java API though I feel using them judiciously is an art. It's my personal experience where I have improved performance by using ArrayList where legacy codes are unnecessarily used Vector etc. JDK 1.5 introduce some good concurrent collections which are highly efficient for high volume, low latency Java application.



Synchronized Collections vs Concurrent Collections in Java

The synchronized collections classes, Hashtable and Vector, and the synchronized wrapper classes, Collections.synchronizedMap() and Collections.synchronizedList(), provides a basic conditionally thread-safe implementation of Map and List.

However, several factors make them unsuitable for use in highly concurrent applications, most importantly their single collection-wide lock is an impediment to scalability and it often becomes necessary to lock a collection for a considerable time during iteration to prevent ConcurrentModificationException.

The ConcurrentHashMap and CopyOnWriteArrayList implementations provide much higher concurrency and scalability while preserving the thread safety with some minor compromises in their promises to callers.

Difference between Concurrent and Synchronized Collections in Java


The ConcurrentHashMap and CopyOnWriteArrayList are not necessarily useful everywhere you might use HashMap or ArrayList, but are designed to optimize specific common situations. Many concurrent applications will benefit from their use.

So what is the difference between Hashtable and ConcurrentHashMap , both can be used in multi-threaded environment but once the size of Hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration.

Since ConcurrentHashMap introduced concept of segmentation, It doesn't mater whether how large it becomes because only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.

You can also check out Core Java Volume 1 - Fundamentals by Cay S. Horstmann to learn more about how concurrent collection works. I have found the explanation given about various things about Java API and programming language in this book very informative and easy to digest. That's the main reason I highly recommend this book.

Synchronized vs Concurrent Collection in Java



That's all about the difference between synchronized and concurrent collection classes in Java. In Summary concurrent collections use advanced technique to achieve thread-safety without compromising Scalability. For example, ConcurrentHashMap only locks certain portion of Map while Hashtable locks full map while doing iteration or performing any write operation.

As always comments and suggestions are welcome.

15 comments :

Leandro Herrera said...

Hi!
You said "ConcurrentHashMap and CopyOnWriteArrayList are not necessarily useful everywhere you might use HashMap or ArrayList". OK, fair enough, but why is that? These classes don't perform well with small size?

What makes that classes not fully interchangeable with their counterparts?

Thank you in advance

Javin @ FIX Protocol Tutorials said...

hi @Leandro, Since hashMap is non synchronized it is the fastest available solution when synchronization is not required. Same is true with Arraylist. ConcurrentHashMap and CopyOnWriteArrayList should only be used in case you need synchronization.

List to Set Java said...

Thank nshrestha, Glad to hear that you like this tutorial about synchronized collection and concurrent collection class in java. You may also like 10 Example of hashtable in java

Prashant said...

Very recently I have started studying java and found this article to be nice. There are some posts related to database system concepts at crazy4db.blogspot.in for those who may be interested in databases.

Anonymous said...

A very nice post
for more details we can go in depth of concurrent hashmaps and different types of locks used for more granular synchronization

Anonymous said...

One Question: If ConcurrentHashMap places lock only on some segment what if other elements outside this segments are modified?

Dwijen said...

Hi,
I would like to know the difference between hastable vs Collections.synchronizedMap . As, both are thread safe which one to use( not considering CHM in this discussion) Also, between these 2 who will perform faster .

Rabindra Panigrahy said...

Nice explanation dude..

Shubham Goswami said...

Could you please tell me how many bits assign to particular segment in concurrentHashMap.(asked in Wipro F2F round).

Sravanthi Appana said...

Hi,
Nice post! By CopyOnWriteHashSet in the post, did you mean CopyOnWriteArraySet?
Correct me if I am wrong.

Javin Paul said...

Yes, CopyOnWriteArraySet, you got it right there is nothing like CopyOnWriteHashSet.

Javin Paul said...

@Shubham, didn't get your question completely. Segments are specialized versions of hash tables and they themselves allows concurrent access. At the start, on CHM only one segment is created and then dynamically other segments are created using ensureSegments() method. ConcurrentHashMap internally maintains an array of Segments.

Gaurav Bhardwaj said...

Nice explanation.

Anonymous said...

can you please provide solution for this
how to write a program for counting the number of commas in aparagraph

SARAL SAXENA said...

@javin ..I think one explanation that you need to add is that use ConcurrentHashMap. It allows concurrent modification of the Map from several threads without the need to block them.
Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly).

Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently.

Post a Comment