Over a million developers have joined DZone.

Beware of Slightly Different Behavior Between ConcurrentMap and ConcurrentHashMap for computeIfAbsent

DZone's Guide to

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
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

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.

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

java ,concurrency

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 }}