Difference Between Hashtable and Synchronized Map in Java
The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a Hashtable, the objects used as keys must implement the hashCode method and also the equals method.
Features of Hashtable:
- It is kind of like HashMap but is synchronized.
- Hashtable stores key/value pair in the hash table.
- In Hashtable we specify an object that is used as a key, and the value we want to associate with that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.
- The initial default capacity of Hashtable class is 11 whereas load Factor is 0.75.
- HashMap doesn’t provide any Enumeration, while Hashtable provides not fail-fast Enumeration.
4 Mona Lisa 3 Joe Biden 2 Donald Trumph 1 James Bond
- Synchronization at the Object level.
- Every read/write operation needs to acquire lock.
- Locking the whole collection is a performance overhead.
- This essentially gives access to just one thread to the entire map & blocks all the other threads.
- It may cause contention.
- SynchronizedHashMap returns Iterator, which fails-fast on concurrent modification.
1: Brad 2: Anil 4: Sachin 88: XYZ 44: Ajit
Hashtable vs SynchronizedHashMap
Hashtable doesn’t allow even a single null key and null values.
Synchronized HashMap allows one null key and any number of null values.
Iterators returned by Hashtable are fail-safe in nature. i.e they don’t throw ConcurrentModificationException if the map is modified after the creation of the iterator.
Iterators returned by synchronized HashMap are fail-fast in nature. i.e they throw ConcurrentModificationException if the map is modified after the creation of iterator.
HashTable was there since JDK 1.1. From JDK 1.2, it has been made a part of Java Collection Framework.
HashMap is introduced in JDK 1.2.
HashTable is the legacy class. It is sometimes considered as due for deprecation. So, it is recommended that not to use HashTable in your applications.
If you want a high level of data consistency, then only consider using synchronized HashMap.