How do you perform a safe get if present operation on a Concurrent Hash Map? (same thing like putIfAbsent)
Bad example, not very thread safe (check then act situation):
ConcurrentMap<String, SomeObject> concMap = new ...
//... many putIfAbsent and remove operations
public boolean setOption(String id, Object option){
SomeObject obj = concMap.get(id);
if (obj != null){
//what if this key has been removed from the map?
obj.setOption(option);
return true;
}
// in the meantime a putIfAbsent may have been called on the map and then this
//setOption call is no longer correct
return false;
}
Another bad example would be:
public boolean setOption(String id, Object option){
if (concMap.contains(id)){
concMap.get(id).setOption(option);
return true;
}
return false;
}
The desirable thing here is to not bottleneck the add, remove and get operations by synchronizing them.
Thanks
The get()
method on a ConcurrentHashMap
is atomic. Since that map does not allow null values, get()
implements "get if present": If the result is null
, the key was not present.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With