Originally posted by Himanshu Jhamb:
It is a general impression that when thread-safe behaviour is not required, it is better to use a HashMap than a Hashtable.
I would contend that you are much
more likely to write threadsafe code using a HashMap than using a Hashtable. Why? Because the "thread-safety" of Hashtable guarantees that multithreaded access will not mess up your Hashtable. It does by no means guarantee that it won't mess up your application. For example, if you use the Hashtable to realise some form of cache you will typically have logic like "check if the map
contains the object; if not, instantiate it and
put it in the map". This entire operation needs to be atomic; the fact that in a Hashtable
contains and
put themselves are atomic buys you absolutely nothing. It only lures you into a false sense of security.
The only significant differences between Hashtable and HashMap are (1) Hashtable is synchronized (I don't like the
word "threadsafe" for obvious reasons), with negative implications for performance and the thread safety of your code, and (2) Hashtable carries around both its old API and the Map API, making it rather confusing and ambiguous to work with. Avoid Hashtable and Vector whenever you can, IMHO.
- Peter