Reputation: 1299
In Java Concurrency In Practice, it says that
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 ?
Upvotes: 4
Views: 140
Reputation: 41975
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.
Note volatile does not guarantee atomicity, it guarantees visibility.
Upvotes: 2
Reputation: 803
A happens-before relationship has an extremely specific meaning in the Java specification. Oracle provides an overview of what it means in their concurrency tutorial.
It's important to understand that the relationship is defined over time spent on the 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.
Upvotes: 3
Reputation: 500773
There would be a race condition. The outcome would depend on who gets there first:
Upvotes: 4