Wednesday, January 10, 2018

What is the difference between synchronize and concurrent collection in Java?

1 ) Internal implementation and performance
Collections.SynchronizedMap
SynchronizedMap is a static inner class of utility class java.util.Collections. It is quite similar to Hashtable and it acquires lock on entire Map instance.

But it internally wraps all the methods of Map interface with synchronized keyword. For example, here is the internal put() and get() method implementation of SynchronizedMap :

  1. public V get(Object key) {

  2. synchronized(mutex) {return m.get(key);}

  3. }

  4. public V put(K key, V value) {

  5. synchronized(mutex) {return m.put(key, value);}

  6. }


SynchronizedMap acquires lock on entire Map object which provides thread-safety, but not good performance as at a time only one thread can access that Map instance.
ConcurrentHashMap
To overcome slow performance issue, ConcurrentHashMap was introduced in Java 5 along with other concurrent classes like CountDownLatchCyclicBarrierCopyOnWriteArrayListBlockingQueue within java.util.Concurrent package.
More than one threads can read and write concurrently in ConcurrentHashMap and still it provides thread-safety.

ConcurrentHashMap divides the Map instance into different segments. And each thread acquires lock on each segment. By default it allows 16 threads to access it simultaneously without any external synchronization i.e. by default concurrency level is 16. We can also increase or decrease the default concurrency level while creating ConcurrentHashMap by using below constructor :

  1. ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel)


2) Null Key and Null Values
ConcurrentHashMap doesn't allow null keys and null values, whereas SynchronizedMap may allow null keys and null values based on the original collection class being passed inside it

No comments:

Post a Comment

உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...