Difference between synchronized HashMap and HashTable?




Asked on December 18, 2014
As we know that we can synchronize Hash Map as Collections.synchronizedMap(map).
 HashTable is already synchronized.
So what is difference between synchronized HashMap and HashTable?



Replied on April 20, 2017
Hashtable is synchronized, whereas HashMap is not synchronized. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform much better than synchronized ones. Synchronized means only a single thread can modify a hashtable at one point of time. Basically, that means any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.


Replied on July 03, 2017

Both HashTable and HashMap implements Map interface but there are some differences between these two. They are:

  1. Thread Safety (synchronized)
  2. Null Keys
  3. Inheritance
  4. Performance
  5. Traverse
  6. Fail-safe
  7. Time Complexity
  8. Legacy

Thread Safety (synchronized)

First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe (unsynchronized) while Hashtable is a thread-safe (synchronized) collection. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.

Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

You can make the HashMap as thread-safe (synchronized) by calling this code


 
Map mp = Collections.synchronizedMap(hashMap);




Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us