Search code examples
javaconcurrencyjava.util.concurrent

Determine if 'put' operation actually executed in putIfAbsent method of ConcurrentHashMap?


I want to know whether 'put' operation actually executed in putIfAbsent method of ConcurrentHashMap.

This is what I want:

if(map.putIfAbsent(Key,Value)){//Clearly this is wrong
  return true;
}

//other operation

return false;

Solution

  • Map#putIfAbsent will return null if no associated key exists or the value for the key is null. Otherwise it will return the existing value.

    V resultOfPut = map.putIfAbsent(key, value);
    
    if (resultOfPut == null) {
        // was able to put
    } else {
        // was not able to put, value already exists
    }