[concurrency-interest] computeIfAbsent optimized for missing entries
dl at cs.oswego.edu
Wed Feb 8 11:55:02 EST 2017
On 02/08/2017 01:52 AM, Amir Hadadi wrote:
> I read the source code for ConcurrentHashMap's computeIfAbsent, and I
> noticed it enters a synchronized block whether or not the key is present.
computeIfAbsent must be more conservative than putIfAbsent because
we guarantee exclusion during the "compute" part.
Even if an element is apparently present, we need to guarantee
that it is not in the process of being removed (while holding lock).
There was a fair amount of pre-jdk8 discussion about whether to
guarantee locking/exclusion in CHM (it is not guaranteed for
ConcurrentMaps in general). The consensus was that it was
worth doing despite the extra overhead. Especially since it
is avoidable in cases where you know that a key will never be
removed once added, first calling get(), and then only
call computeIfAbsent if it returns null.
More information about the Concurrency-interest