Tell me about ConcurrentHashMap and how it differs from Hashtable.
sobes.tech AI
Answer from AI
ConcurrentHashMap and Hashtable are thread-safe implementations of the Map interface in Java, but there are important differences:
-
Synchronization:
- Hashtable synchronizes all methods, which leads to locking the entire object during each operation, reducing performance under high contention.
- ConcurrentHashMap uses segmented (or in newer versions — finer-grained) locking, allowing multiple threads to read and write to different parts of the map simultaneously without locking the entire structure.
-
Performance: ConcurrentHashMap is significantly faster in a multithreaded environment due to finer-grained locking.
-
Null values: Hashtable does not allow null keys or values, and ConcurrentHashMap also does not allow null keys or values (unlike HashMap).
-
Iterators: Iterators of ConcurrentHashMap are "weakly consistent" — they reflect the state of the map at the time of their creation and may see some changes made after creation without throwing ConcurrentModificationException. Hashtable uses outdated iterators that may throw exceptions when the map is modified.
Example of using ConcurrentHashMap:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key1", 1);
map.computeIfAbsent("key2", k -> 2);
In summary: ConcurrentHashMap is preferable for modern multithreaded applications due to better scalability and performance.