facelessss
facelessss

Reputation: 37

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;

Upvotes: 1

Views: 258

Answers (1)

Jason
Jason

Reputation: 5246

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
}

Upvotes: 5

Related Questions