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

标签 java multithreading java-8

我正在尝试查看实际的 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/

相关文章:

java - 如何停止 Beanshell 断言中程序的进一步执行

c - 竞争条件和互斥体

java - Java 方法引用稳定吗?

java - 将数组变量的值赋给自身?

JAVA 8 将返回值传回同一个方法 x 次

java - 使用 Jar 从文件创建类

c# - 使用 async/await 对大型 C# 应用程序进行多线程处理

c++ - 访问其他线程堆栈变量如何在 C++ 中工作?

https - 如何添加 *.P12 keystore (只有一个条目)?

java - 无法在 JavaFX 中加载 Controller