gpt4 book ai didi

java - 更喜欢 synchronized 而不是 volatile

转载 作者:搜寻专家 更新时间:2023-10-30 21:28:12 27 4
gpt4 key购买 nike

我读过这个answer最后写了以下内容:

Anything that you can with volatile can be done with synchronized, but not vice versa.

不清楚。 JLS 8.3.1.4定义可变字段如下:

A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable (§17.4).

因此,volatile 字段与内存可见性有关。另外,就我引用的答案而言,读取和写入 volatile 字段是同步的。

同步反过来保证只有一个线程可以访问同步块(synchronized block)。据我了解,它与内存可见性无关。我错过了什么?

最佳答案

事实上,同步也与内存可见性有关,因为 JVM 在同步块(synchronized block)的导出处添加了一个内存屏障。这确保了同步块(synchronized block)中线程的写入结果保证对另一个线程的读取可见一旦第一个线程退出了同步块(synchronized block)。

注意:按照@PaŭloEbermann 的评论,如果另一个线程通过读取内存屏障(例如通过进入同步块(synchronized block)),它们的本地缓存不会失效,因此它们可能会读取旧值。

同步块(synchronized block)的退出是本文档中的happens-before:http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html#MemoryVisibility

寻找这些摘录:

The results of a write by one thread are guaranteed to be visible to a read by another thread only if the write operation happens-before the read operation.

An unlock (synchronized block or method exit) of a monitor happens-before every subsequent lock (synchronized block or method entry) of that same monitor. And because the happens-before relation is transitive, all actions of a thread prior to unlocking happen-before all actions subsequent to any thread locking that monitor.

关于java - 更喜欢 synchronized 而不是 volatile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32818323/

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