![]() |
VOOZH | about |
In Java, thread safety is an important concern when multiple threads access shared data structures. Two commonly used thread-safe map implementations are Hashtable and Synchronized Map. Although both provide synchronization, they differ in design, performance, and usage.
Hashtable is a legacy class that implements the Map interface. It stores data in the form of key–value pairs and is synchronized by default, meaning all its public methods are thread-safe.
3 Joe Biden 2 Donald Trump 1 James Bond
Explanation:
A Synchronized Map is created by wrapping a non-synchronized map (like HashMap) using Collections.synchronizedMap(). This provides thread safety by synchronizing access to the map.
1 Brad 2 Anil 3 Sachin
Explanation:
| Hashtable | Synchronized HashMap |
|---|---|
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-fast in nature and throw ConcurrentModificationException on concurrent modification. | 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. |