HashMap vs Hashtable vs SynchronizedHashMap vs ConcurrentHashMap

In this Article, we will explore HashMap vs Hashtable vs SynchronizedHashMap vs ConcurrentHashMap.

HashMap vs Hashtable vs SynchronizedHashMap vs ConcurrentHashMap: Differences

 HashMapHashtableSynchronizedHashMapConcurrentHashMap
CreationMap hm = new HashMap();Map ht = new Hashtable() Map map = new HashMap();

 

Map syncMap = Collections.synchronizedMap(map);

Map chm = new ConcurrentHashMap();
Is Null Key Allowed?Allows one Null KeyNOAllows one Null KeyNO
Is Null Value Allowed?YESNOYESNO
Is Thread Safe?NOYESYES. It locks the entire Map. Every read/write operation needs to acquire lock.YES.Thread safety is ensured by having separate locks for separate buckets, resulting in better performance.Performance is further improved by providing read access concurrently without any blocking.
PerformanceFastestSlow due to synchronisation overheadSlow due to synchronisation overheadFaster then Hashtable and SynchronizedHashMap but slower than HashMap.ConcurrentHashMap is a better choice when there are more reads than writes.
IteratorFail-fast iterator: the Iterator of the HashMap is a fail-fast and it throws ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except iterator’s own remove() method. In Simple words fail-fast means: When calling iterator.next(), if any modification has been made between the moment the iterator was created and the moment next() is called, a ConcurrentModificationException is immediately thrown.Hashtable uses enumerator to iterate the values of Hashtable object.Enumerations returned by the Hashtable keys and elements methods are not fail fast.Fail-fast iterator: fails-fast on concurrent modification.Fail-safe Iterator: Iterator provided by the ConcurrentHashMap is fail-safe, which means it will not throw ConcurrentModificationException.

Leave a Reply

Your email address will not be published. Required fields are marked *