Sunday, May 5, 2019

HashMap Vs ConcurrentHashMap

Q- HashMap Vs ConcurrentHashMap : Java Collections Interview Question

HashMap concurrentHashMap
Since Java 1.2 Since Java 1.5
Synchronized and Thread Safe:
HashMap is not synchronized. Hence HashMap is not thread safe.
ConcurrentHashMap is synchronized. Hence ConcurrentHashMap is thread safe.
HashMap allows one null key and multiple null values in hashmap.
Because there is a check for null keys, if the key is null then that element will be stored in a zero index location in Entry array. We cannot have more than one Null key in HashMap because Keys are unique therefor only one Null key and many Null values are allowed
ConcurrentHashMap does not allow null key or value. It will throw NullPointerException.
ConcurrentHashMaps is not allowed null, to avoid ambiguities. If map.get(key) returns null, it cannot detect whether the key explicitly maps to null or the key itself is not mapped.
Performance: HashMap is faster. ConcurrentHashMap is slower than HashMap. because ConcurrentHashMap is synchronized.
HashMap iterator is fail-fast and throws ConcurrentModificationException. ConcurrentHashMap is fail-safe and never throw ConcurrentModificationException.
HashMap can be synchronized by using Collections.synchronizedMap(map) method. By using this method we will get object which is equivalent to the HashTable object. So it will locked on Map object (whole Map Object.). while using in multithreading. ConcurrentHashMap synchronizes or locks on the certain portion of the Map called Segment (internal data structure) . To optimize the performance of ConcurrentHashMap , Map is divided into different partitions depending upon the Concurrency level . So that we do not need to synchronize the whole Map Object. its only getting locked while adding or updating the map. So ConcurrentHashMap allows concurrent threads to read the value without locking at all. This data structure was introduced to improve performance.
In multiple threaded environment only single thread can access the certain portion of the Map At a time. In multiple threaded environment, multiple threads can access the certain portion of the Map. depending  upon the Concurrency level. 
Synchronization at Object level.
Every read/write operation needs to acquire lock.
Locking the entire map object is a performance overhead.
This essentially gives access to only one thread to the entire map & blocks all the other threads.
Reads can happen very fast while write is done with a lock.
There is no locking at the object level. its on segment.

No comments:

Post a Comment