ConcurrentHashMap非阻塞读取和内存可见性问题
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
值的读取实际上是易失性负载。尽管它是非阻塞的,但您将确保发生之前的关系,因为存储也是不稳定的。
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.