Thursday, March 31, 2011

Diff. between HashMap and HashTable

1) is synchronized, thread-safe.
2) each time a thread is required to acquire a lock before using it.
3) does not allow null value as key.

1) is not synchronized or thread-safe.
2) lock is not required by threads.
3) allows one null value as key
4) it can be made thread-safe by using --> Collections.synchronizedMap() method.
5) better performance in single-threaded applications. -- no lock is required to acquire.
6) better performance in multi-threaded applications. -- you can implement a synchronize block at more broad level, so at each entry point lock is not required.
Also, if there is a possibility in future that - 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. Overall HashMap gives you more flexibility in terms of possible future changes.

No comments:

Post a Comment