简体   繁体   English

发生在易失性领域之前的关系

[英]Happens-Before relation in volatile fields

In Java Concurrency In Practice, it says that 在Java Concurrency In Practice中,它说明了这一点

A write to a volatile field happens-before every subsequent read of that same field 在每次后续读取同一字段之前,会发生对易失性字段的写入

Does that mean if two threads try to simultaneously read and write to a volatile field , the JVM will ensure that the write operation precedes the read operation or would there be a race condition anyway ? 这是否意味着如果两个线程尝试同时读取和写入易失性字段JVM将确保写入操作先于读取操作或者是否存在竞争条件?

There would be a race condition. 会有竞争条件。 The outcome would depend on who gets there first: 结果将取决于谁先到达那里:

  • If the write is first, the happens-before guarantees that the read will see the new value. 如果写入是第一个,则发生之前保证读取将看到新值。
  • If the read is first, the happens-before with the most recent earlier write guarantees that the read will see the value of that write. 如果读取是第一个,则在最近的早期写入之前发生的事件保证读取将看到该写入的值。

A happens-before relationship has an extremely specific meaning in the Java specification. 先前发生的关系在Java规范中具有非常特定的含义。 Oracle provides an overview of what it means in their concurrency tutorial . Oracle概述了它们在并发教程中的含义。

It's important to understand that the relationship is defined over time spent on the CPU. 重要的是要理解这种关系是在CPU上花费的时间上定义的。 In other words, it has nothing to do with the initial order in which events occur: a write or a read could come first in your application. 换句话说,它与事件发生的初始顺序无关:写入或读取可能首先出现在应用程序中。

It rather says that if the write is executed first, then the effects of that write will be visible to all threads before they execute subsequent read operations. 相反, 如果首先执行写操作, 那么在执行后续读操作之前,所有线程都可以看到该写操作的效果。 It just provides memory consistency. 它只是提供内存一致性。

If the write to the volatile field happens before the read of that field, then volatile will guarantee that the read will be the latest value. 如果在读取该字段之前发生对volatile字段的写入,则volatile将保证读取将是最新值。

Note volatile does not guarantee atomicity, it guarantees visibility. 注意volatile不保证原子性,它保证可见性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM