Prasad Weera
Prasad Weera

Reputation: 1299

Happens-Before relation in volatile fields

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

Answers (3)

Narendra Pathai
Narendra Pathai

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

impl
impl

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

NPE
NPE

Reputation: 500773

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.

Upvotes: 4

Related Questions