user1870400
user1870400

Reputation: 6364

what if we want to allow overwriting the values with putIFAbsent in concuurentHashMap?

what if we want to allow overwriting the values by two different threads with putIFAbsent in concuurentHashMap?

Saying I have String key, String value1 and String value2 in my concurrent hash map and say I want to allow overwriting the values for the same key by two different threads. Do I need to have a loop ?

public insertCarefullyIntoMap(String key, value) {
    while(value != putIfAbsent(key,value)){}
}

Upvotes: 0

Views: 309

Answers (1)

Andrew Williamson
Andrew Williamson

Reputation: 8671

The put function still works like normal - in fact, the Java documentation uses it to describe the behaviour of putIfAbsent:

If the specified key is not already associated with a value, associate it with the given value. This is equivalent to

if (!map.containsKey(key))
    return map.put(key, value);
else
    return map.get(key);

except that the action is performed atomically.

So if you don't care whether the key already exists in the hashmap, then you can just put your value in unconditionally:

public insertCarefullyIntoMap(String key, String value) {
    map.put(key, value);
}

The only constraints with the put function are that both the key and the value must not be null.

Upvotes: 1

Related Questions