相对于其他领域的易变语义
假设我有以下代码
private volatile Service service;
public void setService(Service service) {
this.service = service;
}
public void doWork() {
service.doWork();
}
Modified 字段标记为易失性,并且其值不依赖于先前的状态。所以,这是正确的多线程代码(暂时不用担心 Service
实现)。
据我所知,从内存可见性的角度来看,读取 volatile 变量就像进入一把锁。这是因为普通变量的读取不能与易失性变量的读取重新排序。
这是否意味着以下代码是正确的?
private volatile boolean serviceReady = false;
private Service service;
public void setService(Service service) {
this.service = service;
this.serviceReady = true;
}
public void doWork() {
if ( serviceReady ) {
service.doWork();
}
}
Suppose I have following code
private volatile Service service;
public void setService(Service service) {
this.service = service;
}
public void doWork() {
service.doWork();
}
Modified field marked as volatile and its value do not depend on previous state. So, this is correct multithreaded code (don't bother about Service
implementations for a minute).
As far as I know, reading volatile variable is like entering a lock, from perspective of memory visibility. It's because reading of normal variables can not be reordered with reading volatile variables.
Does this mean that following code is correct?
private volatile boolean serviceReady = false;
private Service service;
public void setService(Service service) {
this.service = service;
this.serviceReady = true;
}
public void doWork() {
if ( serviceReady ) {
service.doWork();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,从 Java 1.5 开始,这段代码是“正确的”。
无论有或没有易失性(写入对象引用都是原子的),原子性都不是问题,因此您可以以任何方式将其从关注列表中划掉——唯一悬而未决的问题是更改的可见性和顺序的“正确性”。
对易失性变量的任何写入都会设置“发生之前”关系(新 Java 内存模型的关键概念,如 JSR-133) 以及同一变量的任何后续读取。这意味着读取线程必须能够看到写入线程可见的所有内容:也就是说,它必须看到写入时至少具有“当前”值的所有变量。
我们可以通过查看 第 17.4 节来详细解释这一点Java 语言规范 .5,具体如下要点:
因此,在您的示例中:
这意味着在本例中,一旦 serviceReady 为 true,就可以保证“服务”设置正确。
您可以看到一些使用几乎完全相同相同示例的优秀文章,其中一个位于 IBM DeveloperWorks -- 请参阅“Volatile 的新保证”:
,并且位于 JSR-133 FAQ,由该 JSR 的作者编写:
Yes, this code is 'correct' as it stands, from Java 1.5 onwards.
Atomicity is not a concern, with or without the volatile (writes to object references are atomic), so you can cross that off the concerns list either way -- the only open question is visibility of changes and the 'correctness' of the ordering.
Any write to a volatile variable sets up a 'happens-before' relationship (the key concept of the new Java Memory Model, as specified in JSR-133) with any subsequent reads of the same variable. This means that the reading thread must have visibility into everything visible to the writing thread: that is, it must see all variables with at least their 'current' values at the time of the write.
We can explain this in detail by looking at section 17.4.5 of the Java Language Specification, specifically the following key points:
So in your example:
meaning that you are guaranteed that 'service' is set correctly, in this instance, once serviceReady is true.
You can see some good write-ups using almost exactly the same example, one at IBM DeveloperWorks -- see "New Guarantees for Volatile":
and one at the JSR-133 FAQ, written by the authors of that JSR:
AFAIK 这是正确的代码。
@CPerkins:仅使
setService
方法同步将不起作用,因为您还必须在读取时同步。然而,在这种情况下,一个变量就足够了。为什么需要额外的布尔字段。
例如
,假设没有人将 setService 调用为
null
。所以你可能应该进行空检查:AFAIK this is correct code.
@CPerkins: making the only the
setService
method synchronized won't work as you also have to synchronize on reads.However, one variable would be enough in this case. Why do you need the extra boolean field.
E.g.
given that no one ever calls setService to
null
. So you should probably a null-check:您对
易失性
的影响是正确的,所以这应该是正确的,但我对您的设计感到困惑。我不明白为什么你不只是同步setService
- 它可能不会经常被调用。如果它被多次调用,“if (serviceReady)
”部分就没有意义了,因为它仍然是真的,但没关系,因为如果我理解正确的话,替换是原子的。我猜
service.doWork()
是线程安全的,是吗?You're right about the effects of
volatile
, so this should be correct, but I'm confused about your design. I don't understand why you don't just synchronizesetService
- it probably wouldn't be called often. If it is called more than once, the "if (serviceReady)
" part is moot, since it'll still be true, but that's fine, since the replacement is atomic, if I understand correctly.I gather that
service.doWork()
is thread-safe, yes?从理论上讲,它永远不会起作用。您希望确保两个变量的内存一致性,并且希望依赖第一个变量的
易失性读取
。易失性只读保证读取线程看到变量的最新值。所以它绝对不如进入锁定(同步)部分那么强。实际上,它可能会起作用,具体取决于您所使用的 JVM 的 volatile 实现。如果通过刷新所有 CPU 缓存来实现易失性读取,那么它应该可以工作。但我准备打赌这不会发生。 我可以在多核 x86 CPU 上强制实现缓存一致性吗?< /a> 是关于这个主题的好读物。
我想说,只需为两个变量设置一个公共锁( java.util.concurrent.Lock 或 synchronized )即可完成。
Java 语言规范,第三版,有这个说说易失性:
和
它没有提及其他变量的可见性影响。
In theory, it should never work. You want to insure memory consistency for two variables, and you want to rely on a
volatile read
on the first one. The volatile read only guarantees that a reading thread sees the most recent value of the variable. So it's definitely not as strong as entering a locked ( synchronized ) section.In practice, it might work, depending on the implementation of volatile by the JVM you're using. If volatile reads are implemented by flushing all CPU caches, it should work. But I'm ready to bet that it will not happen. Can I force cache coherency on a multicore x86 CPU? is a good read regarding this topic.
I would say simply have a common lock ( java.util.concurrent.Lock or synchronized ) for the two variables and be done with it.
The Java Language Specification, Third Edition, has this to say about volatile:
and
It says nothing about the visibility effect of other variables.