The Hashtable is among the original collection classes in Java.Hashtable extends the Dictionary class, which as the Javadocs state, is obsolete and has been replaced by the Map interface. HashMap is part of the new Collections Framework, added with Java 2.
The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap is not synchronized.This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones
HashMap has a more complex hashing algorithm then Hashtable. It takes the hash value from the key and then hashes it again (double hashing). This can improve the distribution of the keys and hence the performance of the Map.
Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If we change the map while iterating, it will throw exception.
Third difference is that HashMap permits null values in it, while Hashtable doesn't.Also note that only one NULL value is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.
Using ConcurrentHashmap: for having a thread safe map we can use ConcurrenthashMap(from java5 onwards) as well instead of Hashtable which has become obsolete.
private Map
Now The question arises why ConcurrentHashMap and not HashTable or just have a synchronised access to HasMap.
So the major advantage of using ConcurrentHashMap is "performance" as the lock is not applied on wholeMap as is the case with a Synchronised access to hashmap or Hashtable.
As we know that hash maps store their data in a series of separate buckets, it is possible to lock only the portion of the map that is being accessed.ConcurrentHashMap uses this to provide us a highly optimized synchronised way of accessing HashMap.ConcurrentHash hash map follows following to provide a concurrent access:
1. Writing to a ConcurrentHashMap locks only a portion of the map
2. Reads can occur without locking.
Some disadvantges of ConcurrentHashMap:
ConcurrentHashMap will generally take up more memory.
it cannot take null as a key.
Good Article
ReplyDeleteOne more difference between Hashtable vs HashMap in Java is that former is a legacy class and initially not part of Collection API
DeleteHi Apurv,
ReplyDeleteNice article, just to add ConcurrentHashMap is more useful in case you are writing some cache on a moderately busy server and there are more reader and write is infrequent.
Thanks
Javin
FIX Protocol Interview Questions
deadlock in java
tibco tutorial
Hashtable vs HashMap
Hi,Apurv This is Mahendra.
ReplyDeletei got more information about Hashmap and HashTable than i know.
Thanks
Excellent! Very well explained!
ReplyDeleteHere are few more differences between HashMap and ConcurrentHashMap in Java
ReplyDelete