MapComparison

Hashtable vs HashMap

    1. Synchronized: Hashtable is synchronized which means all the methods are marked with synchronized keyword. Look at the code.

    2. Supports null: HashMap supports null key (only one) and null values. Hashtable does not support any null.

    3. Iteration: Iterators of HashMap are fail-fast but enumeration in Hashtable in not fail fast (it does not mean it is fail safe).

    4. Order of Iteration: One variant of HashMap is LinkedHashMap which extends HashMap and provides the ordering of keys.

    5. Historical: Hashtable is legacy code. All features of Hashtable can found in other implementations. E.g. HashMap, Collections.synchronizedMap(). Thus, got new code one may never want to use Hashtable.

What is LinkedHashMap? How it is different from HashMap?

LikedHashMap is simple extension of HashMap providing predictable iteration order. Predictability is done by maintaining a separate (doubly) Linked List for the keys. Thus, in case user is interested only in the default order of inserting and not the actual ordering, he may want to use LinkedHashMap instead of TreeMap.

Example of usage: A module takes a map as input, copies it and then return the results whose order is determined by that of the copy.

So, it has an extra overhead of maintaining the separate linked list (which is not too much).

Please go through Javadoc once.

Hashtable vs Collections.synchronizedMap()

Collections.synchronizedMap() provides a wrapper on Map to return Synchronized Map. That means, it will return a proxy object in which all the methods are synchronized. (Look at the code: each method in SynchronizedMap extends each method of Map with synchronized keyword).

Again a word of caution - Only the map methods are synchronized and made atomic. Compound operations needs to be made synchronized outside.

Why HashMap is not thread safe?

Example: One thread tries to add a value, this causes re-hash. At the same time

1. Another thread may erroneously fail to find a key.

2. Iteration over the bucket (collision list maintained) could fail to find a key that exists in the Map.