出于稀薄的空气安全 [英] Out of Thin Air Safety
问题描述
Java Concurrency in Practice 解释了这个概念:
当一个线程在没有同步的情况下读取变量时,它可能会看到一个
的陈旧值,但至少它会看到一个值实际上是通过一些线程而不是一些随机值放置
。这种安全的
保证被称为超薄空气安全。
When a thread reads a variable without synchronization, it may see a stale value, but at least it sees a value that was actually placed there by some thread rather than some random value. This safety guarantee is called out-of-thin-air safety.
这种类型的安全性是否很弱包含一个陈旧的值?
Is this type of safety weak since it may include a stale value?
也许这个片段,至少它会看到某个线程实际放置的值而不是某个随机值
,是因为本书的上一个主题是JVM重新命令变量语句的可能性,参考共享变量而没有同步
?
Perhaps this snippet, at least it sees a value that was actually placed there by some thread than some random value
, was mentioned since the book's previous topic was the possibility of the JVM to re-order variable statements in reference to sharing variables without synchronization
?
示例:取决于重新订购:42或0可以打印出来。
Example: Depending on re-ordering: 42 or 0 could print out.
public class NoVisibility {
private static boolean ready;
private static int number;
private static class ReaderThread extends Thread {
public void run() {
while(!ready)
Thread.yield();
System.out.println(number);
}
}
public static void main(String[] args) {
new ReaderThread().start();
number = 42;
ready = true;
}
}
已编辑 - 已删除请评论评论。
EDITED - removed "please comment" remark.
推荐答案
这种安全性是否很弱,因为它可能包含陈旧价值?
Is this type of safety weak since it may include a stale value?
是的。 Java Concurrency in Practice中的引用试图指出您的数字
可能是 0
或 42
取决于访问非同步字段所固有的竞争条件,但它不会(假设) 1
- 值将不是稀薄的空气。它可能是陈旧的,对于对象,甚至可能 long
64位值,具体取决于您的硬件架构,也可能部分更新,但它不会有任何随机值。
Yes. The quote from "Java Concurrency in Practice" is trying to point out that your number
may be 0
or 42
depending on the race conditions inherent with accessing unsynchronized fields but it won't be (let's say) 1
-- the value will not come "out-of-thin-air". It may be stale and, with objects and possibly even long
64-bit values depending on your hardware architecture, may also be partially updated, but it won't have some random value.
在您的示例中,数字
已初始化为 0
然后由主线程设置为 42
,这是 number $ c $的可能值c>
ReaderThread
。
In your example the number
was initialized to 0
and then set by the main thread to be 42
so that is the possible values for number
within ReaderThread
.
修改:
正如Voo和yshavit指出的那样, JLS第17.7节具体提到有一些架构将64位操作实现为可以中断的2个独立的32位操作。这意味着一个线程可能只看到另一半线程对字段的更新。虽然不是凭空,但由于按位数表示,结果值似乎是未被任何线程设置的值。
As Voo and yshavit point out, the JLS section 17.7 specifically mentions that there are architectures that implement 64-bit operations as 2 separate 32-bit operation that can be interrupted. This means that a thread might see only half of another threads' update to a field. Although not "out of thin air", the resulting value would seem to be one that was not set by any thread because of bitwise number representations.
这篇关于出于稀薄的空气安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!