Differences and Similarities between HashMap and ConcurrentHashMap in java


In this Collection framework tutorial we will learn what are differences and similarities between java.util.HashMap and java.util.concurrent.ConcurrentHashMap in java.


Contents of page :
  • Differences between java.util.HashMap and java.util.concurrent.ConcurrentHashMap in java >
  • Performance comparison of ConcurrentHashMap and HashMap in java >
    • java.util.concurrent.ConcurrentHashMap
      • Segments in ConcurrentHashMap with diagram >
      • Now let’s form few questions to clear your doubts (based on above diagram) >
      • Let’s summarize above section >
    • java.util.HashMap
      • Now let’s form few questions to clear your doubts (based on above diagram) >
      • Let’s summarize above section >
  • What is concurrency level? What is default concurrency level of ConcurrentHashMap ?
  • Similarity between java.util.HashMap and java.util.concurrent.ConcurrentHashMap>


Differences between java.util.HashMap and java.util.concurrent.ConcurrentHashMap in java >
Property
java.util.HashMap
java.util.concurrent. ConcurrentHashMap
synchronization
HashMap is not synchronized.
ConcurrentHashMap is synchronized.
2 threads on same Map object can access it at concurrently?
Yes, because HashMap is not synchronized.
Yes.

But how despite of being synchronized, 2 threads on same ConcurrentHashMap object can access it at same time?

ConcurrentHashMap is divided into different segments based on concurrency level. So different threads can access different segments concurrently.
Performance
We will synchronize HashMap and then compare its performance with ConcurrentHashMap.

We can synchronize hashMap by using Collections’s class synchronizedMap method.
Map synchronizedMap = Collections.synchronizedMap(hashMap);
Now, no 2 threads can access same instance of map concurrently.
Hence synchronized HashMap’s performance is slower as compared to ConcurrentHashMap.


SCROLL BELOW FOR PERFORMANCE COMPARISON WITH DIAGRAMS.

But why we didn’t compared HashMap (unSynchronized) with ConcurrentHashMap?
Because performance of unSynchronized collection is always better than some synchronized collection. As, default (unSynchronized) hashMap didn’t cause any locking.
ConcurrentHashMap’s performance is faster as compared to HashMap (because it is divided into segments, as discussed in above point).


SCROLL BELOW FOR PERFORMANCE COMPARISON WITH DIAGRAMS.
Null keys and values
HashMap allows to store one null key and many null values i.e. any key can have null value.
ConcurrentHashMap does not allow to store null key or null value.
Any attempt to store null key or value throws runtimeException (NullPointerException).
iterators
The iterators returned by the iterator() method of HashMap are fail-fast >
hashMap.keySet().iterator()
hashMap.values().iterator()
hashMap.entrySet().iterator()

all three iterators are fail-fast
iterators are fail-safe.

concurrentHashMap.keySet().iterator()
concurrentHashMap.values().iterator()
concurrentHashMap.entrySet().iterator()

all three iterators are fail-safe.
putIfAbsent
HashMap does not contain putIfAbsent method.
putIfAbsent method is equivalent to writing following code >
synchronized (map){
   if (!map.containsKey(key))
   return map.put(key, value);
   else
      return map.get(key);
}

If map does not contain specified key, put specified key-value pair in map and return null.
If map already contains specified key, return value corresponding to specified key.





Introduced  in which java version
HashMap was introduced in java 2 i.e. JDK 1.2,
ConcurrentHashMap was introduced in java 5 i.e. JDK 1.5, since its introduction Hashtable has become obsolete, because of concurrency level its performance is better than Hashtable.
Implements which interface
HashMap implements java.util.Map
ConcurrentHashMap implements
java.util.Map and
java.util.concurrent.ConcurrentMap
Package
HashMap is in java.util package
ConcurrentHashMap is in java.util.concurrent package.



Performance comparison of java.util.concurrent.ConcurrentHashMap and java.util.HashMap in java >

ConcurrentHashMap is divided into different segments based on concurrency level. So different threads can access different segments concurrently in java.

Can threads read the segment locked by some other thread?
Yes. When thread locks one segment for updation it does not block it for retrieval (done by get method) hence some other thread can read the segment (by get method), but it will be able to read the data before locking in java.

For operations such as putAll concurrent retrievals may reflect removal of only some entries in java.
For operations such as clear concurrent retrievals may reflect removal of only some entries in java.

Segments in ConcurrentHashMap with diagram >
we have ConcurrentHashMap with 4 segments -
(Diagram shows how segments are formed in ConcurrentHashMap)

Now let’s form few questions to clear your doubts (based on above diagram) >

Question 1 : What will happen map.put(25,12) is called and some other thread concurrently calls map.get(25)?
Answer : When map.put(25,12) is called segment 2 will be locked,
key=25 also lies in segment 2, When thread locks one segment for updation it does not block it for retrieval hence some other thread can read the same segment, but it will be able to read the data before locking (hence map.get(25) will return 121)


Question 2 : What will happen map.put(25,12) is called and some other thread concurrently calls map.get(33)?
Answer : When map.put(25,12) is called segment 2 will be locked,
key=33 also lies in segment 2, When thread locks one segment for updation it does not block it for retrieval hence some other thread can read the same segment, but it will be able to read the data before locking (hence map.get(33) will return 15)


Question 3 : What will happen map.put(25,12) is called and some other thread concurrently calls map.put(33,24)?
Answer : When map.put(25,12) is called segment 2 will be locked,
key=33 also lies in segment 2, When thread locks one segment for updation it does not allow any other thread to perform updations in same segment until lock is not released on segment.
hence map.put(33,24) will have to wait for map.put(25,12) operation to release lock on segment.



Question 4 : What will happen map.put(25,12) is called and some other thread concurrently calls map.put(30,29)?
Answer : When map.put(25,12) is called segment 2 will be locked,
but key=30 lies in segment 3.
Both the kays lies in different segments, hence both operations can be performed concurrently.


Question 5 : What will happen updations (put/remove) are in process in certain segments and new key-pair have to be put/remove in same segment ?
Answer : When updations are in process thread locks the segment and it does not allow any other thread to perform updations (put/remove) in same segment until lock is not released on segment.


Let’s summarize above section >
What operations lock ConcurrentHashMap segment & what operations are allowed when ConcurrentHashMap segment is locked >
  • thread locks one segment for updation (put/remove) & it does not block it for retrieval (get) hence some other thread can read the same segment, but it will be able to read the data before locking
  • It’s important to know get operations does not lock any segment.



HashMap -  can be synchronized by using Collections’s class synchronizedMap method in java.
Map synchronizedMap = Collections.synchronizedMap(hashMap);
Now, no 2 threads can access same instance of map concurrently.
Hence synchronized HashMap’s performance is slower as compared to ConcurrentHashMap in java.


Now let’s form few questions to clear your doubts (based on above diagram) >

Question 1 : What will happen map.put(25,12) is called and some other thread concurrently calls map.get(25)?
Answer : When map.put(25,12) is called whole map is locked,  When one thread performs any updations (put/remove)  on HashMap it locks whole HashMap and does not allow any other thread to perform updation (put/remove) or retrieval (get) operations  until lock is not released on HashMap.
Hence map.get(25) operation will have to wait for map.put(25,12) operation to release lock on HashMap.



Let’s summarize above section >
What operations lock synchronized HashMap & what operations are allowed when synchronized HashMap is locked >
  • When one thread performs any updations (put/remove) on HashMap it locks whole HashMap and does not allow any other thread to perform updation (put/remove) or retrieval (get) operations  until lock is not released on HashMap.
  • It’s important to know get operations does not lock HashMap.


What is concurrency level? What is default concurrency level of java.util.concurrent.ConcurrentHashMap in java?
Concurrency level tells how many threads can access ConcurrentHashMap concurrently, default concurrency level of ConcurrentHashMap is 16 in java.
new ConcurrentHashMap();
Creates a new ConcurrentHashMap with concurrency level of 16.


So far we have learned what are differences between java.util.HashMap and java.util.ConcurrentHashMap in java. Now we will learn similarities between java.util.HashMap and java.util.ConcurrentHashMap in Collection framework in java.


Similarity between java.util.HashMap and java.util.concurrent.ConcurrentHashMap in java>
Property
java.util.HashMap and
java.util.concurrent.ConcurrentHashMap
Insertion order
HashMap and ConcurrentHashMap both does not maintain insertion order.
Implements java.util.Map
HashMap and ConcurrentHashMap both are implementation of the java.util.Map interface.


So in this Collection framework tutorial we learned what are differences and similarities between java.util.HashMap and java.util.concurrent.ConcurrentHashMap in java.


/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */




Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>

Comparable vs Comparator


HashMap in java


ConcurrentHashMap in java - with Segments formation in detail with diagram




Important Similarity and Differences >

ArrayList vs LinkedList - Similarity and Differences

HashMap vs Hashtable vs LinkedHashMap vs TreeMap - Differences


HashMap vs IdentityHashMap - Similarity and Differences with program


TreeMap vs ConcurrentSkipListMap - Similarity and Differences with program

Map hierarchy tutorial in java - Detailed - java.util.HashMap, java.util.Hashtable, java.util.concurrent.ConcurrentHashMap, java.util.LinkedHashMap, java.util.TreeMap, java.util.concurrent.ConcurrentSkipListMap, java.util.IdentityHashMap, java.util.WeakHashMap, java.util.EnumMap classes


No comments:

Post a Comment