Friday, January 25, 2013

HashTable V/s HashMap


HashTable -> synchronized – is a legacy class , Enumeration in the Hash table is not fail-fast
-            
HashMap -> not synchronized, Itrator in the hashmap is fail-fast
                        We can make the hashmap synchronized when ever required using Collections.SynchronizedMap(map)
                        Does not garentee the order of the keyvalue pair in the entered order, but the subclass of hashmap, which is LinkedHashMap we can achieve this.

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.

Fail-fast
A fail-fast system is designed to immediately report any failure or condition that is likely to lead to failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly-flawed process. When a problem occurs, a fail-fast system fails immediately and visibly. It will sounds like making your software more fragile, but it actually makes it more robust. Bugs are easier to find and fix, so fewer go into production

When to use what?
Whenever there is a possibility of multiple threads accessing the same instance, we should use Hashtable. While if not multiple threads are going to access the same instance then use HashMap. Non synchronized data structure will give better performance than the synchronized one.
Again , may be later point of time - there can be a scenario when you may require to retain the order of objects in the Collection with key-value pair then HashMap can be a good choice. As one of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.
Also if you have multiple thread accessing you HashMap then Collections.synchronizedMap() method can be leveraged.

Verdict:-Overall HashMap is better in all aspects.

HashMap Sample Program:-

class HashMap
{
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();

// Put elements to the map
hm.put("Sujith", new Double(71.5));
hm.put("Manjusha", new Double(53.6));
hm.put("Sukhesh", new Double(78.5));
hm.put("Ranjith", new Double(81.1));

// Get a set of the entries
Set set = hm.entrySet();

// Get an iterator
Iterator i = set.iterator();

// Display elements
while(i.hasNext())
{
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
}
}


No comments:

Post a Comment