Thursday, March 6, 2014

HashMap Vs. HashTable ( Java)


1:   One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap cannot be shared between multiple threads without proper synchronization.  Java 5 introduced ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.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.

2:    The HashMap class is roughly equivalent to Hashtable, except that it permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).

3:    The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw 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. This is also an important difference between Enumeration and Iterator in Java.

4:    One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower than HashMap if used in Single threaded environment. So if you don’t need synchronization and HashMap is only used by one thread, it out perform Hashtable in Java.

5:    HashMap does not guarantee that the order of the map will remain constant over time.

 补充:
HashMap is implemented as a hash table, and there is no ordering on keys or values.
TreeMap is implemented based on red-black tree (和AVL一样所有操作log(n), 通过rotate实现self-balance, AVL is defined that each of parents children has height difference less or equal than 1)structure, and it is ordered by the key.
LinkedHashMap preserves the insertion order
Hashtable is synchronized and does not allow null value


Learned:
fail-fast iterator   见链接
An iterator is considered fail-fast if it throws a ConcurrentModificationException under either of the following two conditions:
  1. In multithreaded processing: if one thread is trying to modify a Collection while another thread is iterating over it.
  2. In single-threaded or in multithreaded processing: if after the creation of the Iterator, the container is modified at any time by any method other than the Iterator's own remove or add methods.

No comments:

Post a Comment