[concurrency-interest] computeIfAbsent optimized for missing entries

Amir Hadadi amirhadadi at hotmail.com
Wed Feb 8 01:52:38 EST 2017

I read the source code for ConcurrentHashMap's computeIfAbsent, and I noticed it enters a synchronized block whether or not the key is present.

I would expect this method to first check if the key is present, and only then resort to locking. This would make computeIfAbsent slower when the key is missing, but will speed it up and reduce contention when the key is present.

In the common use case of using ConcurrentHashMap + computeIfAbsent to implement a registry that lazily initializes objects, and the same resource is accessed through the map frequently, contention will ensue.

Why this method was optimized for the missing entry case?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20170208/f60ce84e/attachment.html>

More information about the Concurrency-interest mailing list