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?
source to share
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.
source to share
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.
source to share