Doing `mappingFunction` in ConcurrentHashMap.computeIfAbsent and ConcurrentHashMap.computeIfPresent

I am trying to see the actual Java documentation describing the behavior of how many times a mappingFunction can be called when passing methods to ConcurrentHashMap.computeIfAbsent and ConcurrentHashMap.computeIfPresent .

The Javadoc ConcurrentHashMap.computeIfAbsent seems pretty clear saying that the mappingFunction will execute no more than once:

Javadoc for ConcurrentHashMap.computeIfAbsent

If the specified key is not yet associated with the value, try to calculate its value using this display function and enter it on this card if null is not specified. The entire method call is made atomically, so the function is applied at most once per key . Some attempts to perform updates on this map by other threads may be blocked while the calculation is in progress, so the calculation should be short and simple, and should not try to update any other mappings of this map.

But the Javadoc for ConcurrentHashMap.computeIfPresent doesn't say anything about how many times a mappingFunction can be executed:

Javadoc for ConcurrentHashMap.computeIfPresent

If a value for the specified key is present, try to calculate a new mapping based on the key and the current displayed value. The whole method call is atomic. Some attempts to update the operation of this map by other threads may be blocked. The calculation is performed, therefore, the calculation should be short and simple and should not try to update any other mappings of this map.

After looking at the source code, they look like this: mappingFunction will be executed no more than once. But I really would like to see the actual documentation guaranteeing such behavior.

Is there any such documentation?

+5
source share
1 answer

In the documentation for ConcurrentMap#computeIfPresent we see the following:

The default implementation is equivalent to following these steps for this map:

 for (V oldValue; (oldValue = map.get(key)) != null; ) { V newValue = remappingFunction.apply(key, oldValue); if ((newValue == null) ? map.remove(key, oldValue) : map.replace(key, oldValue, newValue)) return newValue; } return null; 

Although the documentation does not explicitly state that the reassignment function will be executed only once, the equivalent code provided by the documentation makes this clear.

Note Keep in mind that:

When several threads try to update, card operations and the reassignment function can be called several times .

(my emphasis)

+3
source

Source: https://habr.com/ru/post/1275136/


All Articles