gpt4 book ai didi

java - Java 中的 ConcurrentHashMap 锁定机制用于 computeIfPresent

转载 作者:搜寻专家 更新时间:2023-11-01 03:17:53 26 4
gpt4 key购买 nike

我正在使用 Java 8,想知道 ConcurrentHashMapcomputeIfPresent 操作是否锁定了整个表/映射或仅锁定包含 key 的 bin。

来自documentation computeIfPresent 方法:

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

当为一个键调用这个方法时,看起来整个 map 都被锁定了。如果更新某个键的值,为什么必须锁定整个 map ?只锁定包含键/值对的容器不是更好吗?

最佳答案

从实现来看(Oracle JDK 1.8.0_101),只是相应的bin被锁定了。这与您引用的文档片段并不矛盾,因为它提到某些 更新操作可能会被阻止,不一定是全部。当然,如果文档明确说明锁定的内容会更清楚,但那会将实现细节泄露给接口(interface)的事实上部分。

关于java - Java 中的 ConcurrentHashMap 锁定机制用于 computeIfPresent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41916368/

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