We can syncronize HashMap as follows:
1: Collections.syncronizedMap(hashMap);
2: We can also use ConcurrentHashMap if we need syncronized HashMap.
What are differences in these two syncronized HashMap.?
In 1: gives a thread-safe HashMap backed by original HashMap and for each operation entire HashMap will be locked so that only one thread can access the map.
In 2: all operations are thread-safe and retrieval operation does not require locking of map. While updating, only that portion of map is locked which is being updated.
So performance wise 2: option is better than 1:
1: Collections.syncronizedMap(hashMap);
2: We can also use ConcurrentHashMap if we need syncronized HashMap.
What are differences in these two syncronized HashMap.?
In 1: gives a thread-safe HashMap backed by original HashMap and for each operation entire HashMap will be locked so that only one thread can access the map.
In 2: all operations are thread-safe and retrieval operation does not require locking of map. While updating, only that portion of map is locked which is being updated.
So performance wise 2: option is better than 1:
ConcurrentHashMap does not allow
null key or value like Hashtable. The reason is if multiple threads will access
the Map then it’s difficult to predict why key or value is null because it may
be modified by other threads.
ConcurrentHashMap differs from Hashtable:
1: Hashtable is based on synchronization while
ConcurrentHashMap works on concurrency.
2: Retrieval operation generally does not need any locking
3: Multiple threads can modify ConcurrentHashMap. By default
it has concurrency level 16. It means 16 threads can update the table
concurrently given that no two threads are working on same bucket. If it is the
case then those threads will access that bucket in sequence.
4: It locks the bucket and not the whole map. ConcurrentHashMap
uses Reentrant lock internally.
5: ConcurrentHashMap’s iterator is fail- safe. It means Map can be modified externally while
iterating but not in case of Hashtable.
6: ConcurrentHashMap uses balanced
tree to store the next key value in case of hash collision while Hashtable
uses LinkedList (Separate
Chaining)
7: There are many useful methods that are present in ConcurrentHashMap
(searchKeys, searchValues, newKeySet ) but not in Hashtable.