Happens-Before relation in volatile fields

The Java Concurrency In Practice says that

Written to an unstable field - the same field before each subsequent reading

Does this mean that if two threads try to read and write to a volatile field at the same time , the JVM will ensure that the write operation precedes the read operation, or there will be a race condition anyway?

+3


source to share


3 answers


A happens-before relationship has an extremely specific meaning in the Java specification. Oracle provides an overview of what concurrency means in their tutorial .

It is important to understand that relationships are determined over time spent on the processor. In other words, it has nothing to do with the initial order in which events occur: the write or read can be the first in your application.



Rather, it says that if a write is in progress, then the consequences of that write will be visible to all threads before they perform subsequent reads. It just enforces memory consistency.

+3


source


There will be a race condition. The result will depend on who gets there first:



  • If the write is the first, then it happens - before it is seen that the read sees the new value.
  • If the read is the first, the previous one with the most recent earliest record ensures that the read sees the value of that record.
+4


source


If a volatile field is written before that field is read, then volatile guarantees that the read will be the last .

Note. volatile does not guarantee atomicity, it does guarantee visibility.

+2


source







All Articles