ConcurrentHashMap computeIfAbsent method in Java 8

The very nifty method computeIfAbsent has been added in the ConcurrentMap interface in Java 8 as part of the atomic operations of the ConcurrentMap interface. It’s more precisely a default method that provides an alternative to what we use to code ourselves:

if (map.get(key) == null) {
   V newValue = mappingFunction.apply(key);
   if (newValue != null)
      return map.putIfAbsent(key, newValue);

but this time providing a function as a second argument.

Most often this method will be used in the context of ConcurrentHashMap in which case the method is implemented in a thread-safe synchronised way.

In terms of usage the method is handy for situations where we want to maintain a thread-safe cache of expensive one-off computed resources.

Here’s another example of holding a key-value pair where value is a thread-safe counter represented by an AtomicInteger:

private final Map counters = new ConcurrentHashMap();

private void accumulate(String name) {
    counters.computeIfAbsent(name, k -> new AtomicInteger()).incrementAndGet();

2 comments on “ConcurrentHashMap computeIfAbsent method in Java 8

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s