What are the differences between a HashMap and a Hashtable in Java?
Which is more efficient for non-threaded applications?
Old and classic topic, just want to add this helpful blog that explains this:
http://blog.manishchhabra.com/2012/08/the-5-main-differences-betwen-hashmap-and-hashtable/
Blog by Manish Chhabra
The 5 main differences betwen HashMap and Hashtable
HashMap and Hashtable both implement java.util.Map interface but there are some differences that Java developers must understand to write more efficient code. As of the Java 2 platform v1.2, Hashtable class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework.
One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap cannot be shared between multiple threads without proper synchronization. Java 5 introduced ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.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.
The HashMap class is roughly equivalent to Hashtable, except that it permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. This is also an important difference between Enumeration and Iterator in Java.
One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower than HashMap if used in Single threaded environment. So if you don’t need synchronization and HashMap is only used by one thread, it out perform Hashtable in Java.
HashMap does not guarantee that the order of the map will remain constant over time.
Note that HashMap can be synchronized by
Map m = Collections.synchronizedMap(hashMap);
In Summary there are significant differences between Hashtable and HashMap in Java e.g. thread-safety and speed and based upon that only use Hashtable if you absolutely need thread-safety, if you are running Java 5 consider using ConcurrentHashMap in Java.