Tuesday, March 13, 2012

Difference between HashMap and HashTable?


The HashMap class is roughly equivalent to Hashtable.


  1. hasMap is not synchronized(not thread-safe) whereas hashTable is synchronized(thread-safe)

  2. hashMap permits null values in key and value whereas hashTable does not allow nulls.

  3. hashMap does not guarantee that the order of the map will remain constant over time whereas with hashTable, order is constant over time.

  4. Iterator in hashMap is fail-safe while the enumerator for hashTable is not so.

  5. hashMap throws ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort.





HashMap can be synchronized


Map m = Collections.synchronizeMap(hashMap);



Note on Some Important Terms




  1. Synchronized means that only one thread can modify the hashTable at any 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.



  2. Fail-safe is relevant from the context of iterators.

    If an iterator has been created on a collection object and some other thread tries to modify the collection object structurally, a concurrent modification exception will be thrown.

    It is possible for other threads though, to invoke set() method since it doesn't modify the collection structurally.

    However, if prior to calling set(), the collection has been modified structurally, "IllegalArgumentException" will be thrown.



  3. Structurally modification means deleting or inserting element which could effectively change the structure of map.


No comments:

Post a Comment