Is ConcurrentHashMap compute() method thread safe?

Viewed 577
concurrentHashMapInstance.compute("Name", (key, val) -> {
     modifyValWithComplexLogic(val); 
     return val;
});

is modifyValWithComplexLogic(val) (and the whole compute method) thread safe regarding val?

1 Answers

In a word, yes, but you still need to be careful.

ConcurrentHashMap#compute runs the remapping function in a block that's synchronized on the node it's about to update, so if the remapping function itself may be racy on another resource and you're calling it on multiple keys, you should probably synchronize it yourself and not assume the ConcurrentHashMap will do it for you.

Related