Over a million developers have joined DZone.

Beware of Slightly Different Behavior Between ConcurrentMap and ConcurrentHashMap for computeIfAbsent

The key difference is in how many times the implementation can be called.

· Java Zone

Learn more about the advantages of moving from a monolithic to microservices architecture.  Brought to you in partnership with IBM.

So I was refactoring some code to use non-locking collection classes and I noticed this significant difference between ConcurrentMap.computeIfAbsent and ConcurrentHashMap.computeIfAbsent. The key difference is that for the former, default implementing the mapping function can be called many times for a particular key, whereas for the concrete implementation it will be called only once.

Right, okay, so armed with that you know that any collection that implements just ConcurrentMap will inherit this behavior; further to that I found in particular that Guava would return a different implementation depending on the passed on parameters:

ConcurrentMap map1 = new MapMaker().makeMap();

ConcurrentMap map2 = new MapMaker().weakKeys().makeMap();


class java.util.concurrent.ConcurrentHashMap
class com.google.common.collect.MapMakerInternalMap

MapMakerInternalMap doesn't override computerIfAbsent, therefore the behaviour of this function will be significantly different depending on the parameters to pass into the maker, something that might not be apparent from the get go.

From Idea to Application gives you the architecture to quickly build, manage and run a range of applications (web, mobile, big data, new smart devices, etc.) on an open-standard, cloud-based platform. See why developers are using IBM Bluemix. Brought to you in partnership with IBM.


Published at DZone with permission of Gerard Davison, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}