What are the differences between a HashMap and a Hashtable in Java?

后端 未结 30 3152
青春惊慌失措
青春惊慌失措 2020-11-21 13:30

What are the differences between a HashMap and a Hashtable in Java?

Which is more efficient for non-threaded applications?

30条回答
  •  深忆病人
    2020-11-21 13:57

    Note, that a lot of the answers state that Hashtable is synchronised. In practice this buys you very little. The synchronization is on the accessor / mutator methods will stop two threads adding or removing from the map concurrently, but in the real world you will often need additional synchronisation.

    A very common idiom is to "check then put" — i.e. look for an entry in the Map, and add it if it does not already exist. This is not in any way an atomic operation whether you use Hashtable or HashMap.

    An equivalently synchronised HashMap can be obtained by:

    Collections.synchronizedMap(myMap);
    

    But to correctly implement this logic you need additional synchronisation of the form:

    synchronized(myMap) {
        if (!myMap.containsKey("tomato"))
            myMap.put("tomato", "red");
    }
    

    Even iterating over a Hashtable's entries (or a HashMap obtained by Collections.synchronizedMap) is not thread safe unless you also guard the Map from being modified through additional synchronization.

    Implementations of the ConcurrentMap interface (for example ConcurrentHashMap) solve some of this by including thread safe check-then-act semantics such as:

    ConcurrentMap.putIfAbsent(key, value);
    

提交回复
热议问题