简体   繁体   中英

ConcurrentHashMap in Java locking mechanism for computeIfPresent

I'm using Java 8 and would like to know if the computeIfPresent operation of the ConcurrentHashMap does lock the whole table/map or just the bin containing the key.

From the documentation of the computeIfPresent method:

Some attempted update operations on this map by other threads may be blocked while computation is in progress, so the computation should be short and simple, and must not attempt to update any other mappings of this map

This looks like the whole map is locked when invoking this method for a key. Why does the whole map have to be locked if a value of a certain key is updated? Wouldn't it be better to just lock the bin containing the key/value pair?

Judging by implementation (Oracle JDK 1.8.0_101), just the corresponding bin is locked. This does not contradict the documentation snippet you've cited, since it mentions that some update operations may be blocked, not necessarily all. Of course, it'd be clearer if the docs stated explicitly what gets locked, but that'd be leaking implementation details to what is de facto a part of the interface.

If you look at the source code of ConcurrentHashMap#computeIfPresent , you'll notice that the synchronisation is made directly on the node itself.

So an operation will only block if you attempt to update any node that is being computed. You should not have any problems with other nodes.

From my understanding, the synchronization directly on nodes is actually the major add-on of ConcurrentHashMap vs old Hashtable .

If you look at the source code of hashtables, you'll notice that the synchronization is much wider. A contrario , any synchronization in ConcurrentHashMap happens directly on nodes.

The end of Hashtable documentation also suggest that :

[...] 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.

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