In this Article, we will explore HashMap vs Hashtable vs SynchronizedHashMap vs ConcurrentHashMap.
HashMap vs Hashtable vs SynchronizedHashMap vs ConcurrentHashMap: Differences
HashMap | Hashtable | SynchronizedHashMap | ConcurrentHashMap | |
Creation | Map 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 Key | NO | Allows one Null Key | NO |
Is Null Value Allowed? | YES | NO | YES | NO |
Is Thread Safe? | NO | YES | YES. 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. |
Performance | Fastest | Slow due to synchronisation overhead | Slow due to synchronisation overhead | Faster then Hashtable and SynchronizedHashMap but slower than HashMap.ConcurrentHashMap is a better choice when there are more reads than writes. |
Iterator | Fail-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. |