Tim B
Tim B

Reputation: 41208

What is the correct way to tell whether putIfAbsent modified a ConcurrentHashMap?

I'm using putIfAbsent to add values to a ConcurrentHashMap if they do not already exist as an atomic operations.

That all seems fine, but I could really do with being able to tell whether a new object was actually added.

The best idea I have is to check if the return value from putIfAbsent is null, that looks like it should work so long as we never put null values into the map (which ConcurrentHashMap doesn't allow anyway) but I was wondering if there was something I missed. Or is that the correct way to do it?

Upvotes: 1

Views: 743

Answers (1)

John Vint
John Vint

Reputation: 40256

The best way to use the CHM in this case is as such:

Object o = concurrentMap.get(key);

if(o == null){
   Object ret = concurrentMap.putIfAbsent(key, value);
   if(ret == null){
      o = ret;
   }
}
return o;

The get calls are non-blocking, so you want to leverage the non-blocking calls as much as you can. Continuously calling putIfAbsent can slow down performance if many are being invoked.

Upvotes: 3

Related Questions