Java:Difference between HashMap & Hashtable

Posted on Updated on

  • HashMap and Hashtable both classes implements java.util.Map interface, however there are differences in the way they work and their usage
  • HashMap is non-synchronized. This means if it’s used in multithread environment then more than one thread can access and process the HashMap simultaneously. Where as Hashtable is synchronized. It ensures that no more than one thread can access the Hashtable at a given moment of time. The thread which works on Hashtable acquires a lock on it to make the other threads wait till its work gets completed.
  • HashMap allows one null key and any number of null values,Where as Hashtable doesn’t allow null keys and null values.
  •  HashMap implementation LinkedHashMap maintains the insertion order and TreeMap sorts the mappings based on the ascending order of keys ,Where as Hashtable doesn’t  maintain the mappings in any particular order.
  • Another major difference between these 2 classes is iterator of HashMap is a fail fast where as Hashtable’s iterator is not.

Let us understand what is fail fast

In Simple words fail-fast means: When calling iterator.next(), if any modification has been made between the moment the iterator was created and the moment next() is called, a ConcurrentModificationException is immediately thrown.

  • Finally the usage of these collections can be decided based on the need of user i.e if we need a thread safe operation Hashtable can be used and for non thread environment HashMap
  • However we can achieve synchronization using concurrent HashMap as well

Let us see an example on How to synchronize HashMap explicitly

We use Collections.synchronizedMap(hmap) it returns a thread-safe map backed up by the specified HashMap.

package tejaswi.com;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
public class HashMapSyncExample {
public static void main(String args[]) {
HashMap<Integer, String> hmap= new HashMap<Integer, String>();
hmap.put(2, “Anil”);
hmap.put(44, “Ajit”);
hmap.put(1, “Brad”);
hmap.put(4, “Sachin”);
hmap.put(88, “XYZ”);
Map map= Collections.synchronizedMap(hmap);
Set set = map.entrySet();
synchronized(map){
Iterator i = set.iterator();
// Display elements
//Iterator must be in the synchronized block
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + “: “);
System.out.println(me.getValue());
}
}
}
}

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s