Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 250
Prasad Weera Avatar asked Oct 29 '25 08:10

Prasad Weera


2 Answers

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.
like image 120
NPE Avatar answered Oct 31 '25 03:10

NPE


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.

like image 41
impl Avatar answered Oct 31 '25 03:10

impl