2015年3月31日星期二

The difference between Hashtable and HashMap in Java

1. Hashtable is synchronized, while HashMap is not. Hashtable can be used for multiple threads. Since lock takes time, it degrade the performance with Hashtable. HashMap is only used for non-threaded application. But, actually, this buys you very little because we need synchronization in many applications. So we use equivalently synchronized HashMap which can be obtained by:

But also, you need to correctly implement this logic with additional synchronization form:

So, if the map was modified, it is still not thread safe unless you guard them. But you can solve the problem by thread safe check-then-act semantics like:
2. Hashtable does not allow null keys or values, but HashMap allows one null key and any number of null values.
3. HashMap can have predictable iteration order by swapping out LinkedHashMap. But it is not easy with Hashtable.
4. Hashtable is almost used for legacy API. 

没有评论:

发表评论