ConcurrentHashMap非阻塞读取和内存可见性问题

发布于 2024-12-11 23:48:14 字数 286 浏览 0 评论 0原文

Java 中的 ConcurrentHashMap 提供与更新同时进行的读取。这样做的权衡是,读取的结果仅限于反映读取开始时最后完成的更新,因此未指定它反映元素的最新状态。

然而,据我所知,Java 内存模型,如果读写线程之间没有某种形式的同步,即使在任意时间段之后,写入线程的更新也可能不会对读取线程可见。

鉴于读取线程不会被写入线程阻塞,那么什么构成了保证读取线程可用的最后完成的更新的可见性的基础?

我只能想到一些与比较和交换算法有关的东西,但我无法在该库的源代码中验证它。

ConcurrentHashMap in Java offers reads to proceed concurrently with updates. The trade-off in this is that the results of the read is limited to reflect only the last completed update when the reading began, so it is not specified to reflect the latest state of elements.

However AFAIK Java Memory Model , without some form of synchronization between the read and write threads, the updates of the write thread may not become visible to the read thread , even after arbitrary period of time.

Given the read threads do not block with write threads , what forms the basis of the guarantee of visibility of the last completed update to be available to the read thread ?

I could only think of something on the lines of Compare-and-swap algorithm at play but I could not verify it in the source code of that library.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鲜血染红嫁衣 2024-12-18 23:48:14

值的读取实际上是易失性负载。尽管它是非阻塞的,但您将确保发生之前的关系,因为存储也是不稳定的。

Java 5,6,7 版本的 CHM 不使用 CAS 来交换引用。但有一个较新的轻量级版本正在开发中,将在其某些写入中使用。

The read of the values are actually volatile loads. Though it is non-blocking you will ensure the happens-before relationship since the store too is volatile.

Java 5,6,7's version of the CHM does not use CAS to swap the references. But there is a newer lightweight version in the works that would use in some of its writes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文