Reputation: 423
Is the whole method call atomic or is just the BiFunction execution atomic? Is it blocking for all keys or just for the calls on the same key?
Upvotes: 5
Views: 1966
Reputation: 423
I just tested this with Kotlin coroutines on Android using the following code
val incrementalNum = AtomicInteger(0)
val map = ConcurrentHashMap<Int, Unit>()
val lastThreadNum = AtomicInteger(-1)
val collisions = AtomicInteger(0)
for (a in 0..1000) GlobalScope.launch {
val threadNum = incrementalNum.incrementAndGet()
map.compute(threadNum) { k, v-> lastThreadNum.set(threadNum); Unit.apply {
Log.e("SLOW", "this operation will slow things")
if (lastThreadNum.get() != threadNum) Log.e("COLLISION", "Collision Number: ${collisions.incrementAndGet()}")
}}
}
With map.compute(threadNum) i get a fair number of collisions (about 10-30) every time I run it, while using map.compute(1) I never get any collisions.
This seems to indicate that - at least on Android- the ConcurrentHashMap.compute function is only blocking by key (which is a pretty good behaviour for my use case)
I'll try to test this with other Java implementations, if that's the standard/usual implementation, it should probably be documented better
Upvotes: 1
Reputation: 719229
The following details are for OpenJDK Java 11.
These three methods hold a lock on a Node
in the map while the method is called and the key / value is updated. This node will typically be the first node in a the chain or tree of nodes for a hash bucket. Concurrent attempts to insert, update or delete key/value pairs in the same bucket will be blocked until the lock is released.
(The behavior for other versions of Java could be different.)
Is the whole method call atomic or is just the BiFunction execution atomic?
The whole method call.
Is it blocking for all keys or just for the calls on the same key?
Somewhere in between; see above. But if you follow this advice in the javadocs, it should not matter.
" 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 ..."
Upvotes: 4