gpt4 book ai didi

java - 是否可以使用可见性保证而不是成熟的锁定来以线程安全的方式访问共享状态?

转载 作者:行者123 更新时间:2023-11-30 01:49:58 24 4
gpt4 key购买 nike

实践中的 Java 并发声明如下:

When thread A executes a synchronized block, and subsequently thread B enters a synchronized block guarded by the same lock, the values of variables that were visible to A prior to releasing the lock are guaranteed to be visible to B upon acquiring the lock. In other words, everything A did in or prior to a synchronized block is visible to B when it executes a synchronized block guarded by the same lock. Without synchronization, there is no such guarantee.

Here's a diagram from the book

相同的逻辑适用于 volatile 变量:

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.

从描述中可以清楚地看出,当您需要访问某些共享状态时,您可以使用这种可见性效果来实际替换(或限制使用)传统锁。在图中的示例中,您可以看到线程 B 可以安全地读取变量 y,即使它在同步块(synchronized block)之外的线程 A 中发生了更改。

那么,当您在获取线程锁之前更改某些共享状态,然后获取锁,执行某些操作(或者什么都不做,我猜),释放时,使用此可见性保证是否安全锁,然后在另一个线程中获取相同的锁,释放它,然后安全地从第一个线程中更新的共享变量中读取最新值?

最佳答案

引用的句子中有一个关键部分:

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.

虽然这显然是正确的,但你这里有一个条件,即 A 必须先阅读 B 的内容。 但是,如果没有锁定,则无法保证读/写顺序 - 这就是重点。

因此,您不能用 volatile 替换每个同步,因为它不会产生相同的结果。

关于java - 是否可以使用可见性保证而不是成熟的锁定来以线程安全的方式访问共享状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56422209/

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