java – 在ConcurrentHashMap.computeIfAbsent和ConcurrentHashMap.computeIfPresent中执行`mappingFunction`

前端之家收集整理的这篇文章主要介绍了java – 在ConcurrentHashMap.computeIfAbsent和ConcurrentHashMap.computeIfPresent中执行`mappingFunction`前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我试图看到实际的Java文档,描述了传递给ConcurrentHashMap.computeIfAbsent和ConcurrentHashMap.computeIfPresent方法时可以调用mappingFunction的次数的行为.

ConcurrentHashMap.computeIfAbsent的Javadoc似乎很清楚,表示mappingFunction最多只执行一次:

ConcurrentHashMap.computeIfAbsent的Javadoc

If the specified key is not already associated with a value,attempts
to compute its value using the given mapping function and enters it
into this map unless null. The entire method invocation is performed
atomically,so the function is applied at most once per key. Some
attempted update operations on this map by other threads may be
blocked while computation is in progress,so the computation should be
short and simple,and must not attempt to update any other mappings of
this map.

但是ConcurrentHashMap.computeIfPresent的Javadoc并没有说明可以执行mappingFunction的次数

ConcurrentHashMap.computeIfPresent的Javadoc

If the value for the specified key is present,attempts to compute a
new mapping given the key and its current mapped value. The entire
method invocation is performed atomically. Some attempted update
operations on this map by other threads may be blocked while
computation is in progress,so the computation should be short and
simple,and must not attempt to update any other mappings of this map.

通过查看源代码,他们看起来就像mappingFunction最多只执行一次.但我真的希望看到保证这种行为的实际文档.

有这样的文件吗?

最佳答案
ConcurrentMap#computeIfPresent的文档中,我们看到以下内容

The default implementation is equivalent to performing the following 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;

尽管文档没有明确说明重映射功能只会执行一次,但文档提供的等效代码却清楚了.

注意:请记住:

When multiple threads attempt updates,map operations and the remapping function may be called multiple times.

(强调我的)

猜你在找的Java相关文章