简体   繁体   中英

ConcurrenthashMap and thread safety

javadocs of ConcurrenthashMap says:

A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.

What is the meaning of following statement from above paragraph?

This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details

Hashtable methods are synchronized , and you can write blocks of code being sure the state of the Hashtable won't change in the middle:

syncronized (hashtable) {
    if (!hashtable.contains(key))
        hashtable.put(key, value);
}

ConcurrentHashMap 's methods are not synchronized (though still thread-safe, as specified in the javadoc), you can't perform compound operations synchroniously with it's state.

Notice: the above example compound operation has a perfect equivalent in ConcurrentHashMap api: putIfAbsent(K, V) , but some other useful actions doesn't.

Found this in the javadocs for Hashtable:

As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.

I think they are saying that Hashtable has synchronized methods but the new ConcurrentHashMap doesn't use synchronization to ensure thread safety. As for "interoperable", I think that means the interface is basically the same - so you can use either one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM