java - ConcurrentHashMap检索操作不带锁?

标签 java multithreading concurrenthashmap

根据 Java 文档

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries

问题:假设线程 t1 正在更新一个键值对(称为 x),然后其他线程 t2 到来并想要读取 x,是否会在 t2 开始时创建 x 的副本 c1,并且 t2 会从该副本 c1 中读取

最佳答案

Retrievals reflect the results of the most recently completed update operations holding upon their onset

完整的单词在这里很重要。现在你的场景是

 Suppose a thread t1 is updating a key-value pair(called x), and then other thread t2 comes and want to read x.

T2 将读取已完成但不在进程中的操作更新的值。在您的场景中,如果线程 t1 的更新操作未完成,则 t2 将看不到更新的值。不创建任何副本。这是简单的时间基础。如果到 t2 线程读取 x 值并且 t2 更新操作完成时,它将看到更新的值,否则不会。

关于java - ConcurrentHashMap检索操作不带锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16503733/

相关文章:

java - Java 中 BoundedBuffer 的正确实现?

java - 修改 ConcurrentHashMap 中的值

java - ConcurrentHashMap 如何处理重新散列?

java - 单击按钮时显示/隐藏 ImageView

java - 为什么 OpenJDK 11 Java 垃圾收集器*减少*此示例程序中的可用内存?

java - 如何在java中将图像转换为棕褐色?

java - 在 AWT 组件上添加透明 JPanel 进行绘制

Java Publisher Server 聊天程序

java - 如何防止我的消费者线程两次删除最后一个元素?

java - 具有空键功能的线程安全映射