gpt4 book ai didi

java - 在读写原子性、可见性和防止重新排序方面,锁定、同步、原子变量与 Java 中的 volatile

转载 作者:行者123 更新时间:2023-12-04 10:19:26 25 4
gpt4 key购买 nike

我阅读了以下关于 volatile来自《Java 并发实践》一书:

When a field is declared volatile, the compiler and runtime are put on notice that this variable is shared and that operations on it should not be reordered with other memory operations. Volatile variables are not cached in registers or in caches where they are hidden from other processors, so a read of a volatile variable always returns the most recent write by any thread.

The visibility effects of volatile variables extend beyond the value of the volatile variable itself. When thread A writes to a volatile variable and subsequently thread B reads that same variable, the values of all variables that were visible to A prior to writing to the volatile variable become visible to B after reading the volatile variable. So from a memory visibility perspective, writing a volatile variable is like exiting a synchronized block and reading a volatile variable is like entering a synchronized block.



我对上面的最后一句话感到困惑。说变量 x已定义 volatile和修改前 x , u , vw对线程可见 A ,然后当线程 B阅读 x之后,它还可以读取 u的最新值。 , vw .我们可以为 synchronized 指定相同的内容吗? ?.

一季度。 也就是说,下面正确吗?

Variables u,v and w were visible to thread A while exiting synchronized block, then the latest values of u,v and w will be visible to thread B entering synchronized block afterwards.



我觉得以上事实不正确,因为 u , vw可能存储在高速缓存和寄存器中,因为它们未定义 volatile .我对此是否正确?因此, synchronized 无法确保可见性(还有 locksatomic 变量,因为它们类似于 synchronized )

书中进一步说:

Locking can guarantee both visibility and atomicity; volatile variables can only guarantee visibility.



但我感觉如下:
  • 锁,synchronized和原子变量只保证读写原子性(不可见性和防止重新排序)。
  • volatile保证可见性并防止编译器和运行时重新排序(不是读写原子性)。

  • Q2。 以上两点我是否正确?

    最佳答案

    1)锁、同步和原子变量保证读写原子性
    可见性和防止重新排序

    2) volatile 保证可见性并防止编译器和运行时重新排序

    volatile 字段的读写原子性有点棘手:读取和写入 volatile 字段是原子的,例如,如果您在 32 位 jvm 上写入 volatile long(64 位),则读取和写入仍然是原子的。您总是阅读完整的 64 位。但是像++ 对 volatile int 或 long 的操作不是原子的

    关于java - 在读写原子性、可见性和防止重新排序方面,锁定、同步、原子变量与 Java 中的 volatile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60931421/

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