gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 20:17:11 31 4
gpt4 key购买 nike

我正在尝试查看实际的 Java 文档,描述传递给 ConcurrentHashMap.computeIfAbsentConcurrentHashMap.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 - 在 ConcurrentHashMap.computeIfAbsent 和 ConcurrentHashMap.computeIfPresent 中执行 `mappingFunction`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48587505/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com