I know there have been many questions around computeIfAbsent
.
Specifically what I am looking for is to understand the statement around atomicity for a concurrent hash map.
from the JavaDoc
The entire method invocation is performed atomically, so the function is applied at most once per key.
If two threads attempt to execute computeIfAbsent
with different key's and find that in both cases the map does not contain them, might the resulting executions of the compute if absent function be concurrent? I understand they would not be concurrent in the event that both threads were trying to add the SAME key.
The word Atomic is used and it is mentioned that this means applied at most once per key. But there isn't a specific mention of synchronized behaviour on the method.
As a side note, this is relevant to me in that the method called by computeIfAbsent modifies then uses a field of the class in its body.*
I want to understand if there is a threading concern resulting from two different thread executions of the computeIfAbsent method for the two different keys.
Essentially do I have to look at something along the lines of synchronizing access to the field variable and its subsequent use within the computeIfAbsent method I call.
*( The computeIfAbsent method invoked is the only method which modifies the field. There is no other invoker of the method outside of the call from the hash map computeIfAbsent method. There is only one instance of the concurrent hash map that calls the computeWithAbsent method that invokes the "atomic" method in question)
My field is volatile to avoid potential concerns with atomic visibility.