Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a write to a volatile a memory-barrier in Java

Tags:

I recently heard in a talk that a write to a volatile triggers a memory-barrier for each variable that the thread has written to. Is that really correct? From the JLS, it seems that only the variable concerned gets flushed out, but not others. Does anybody know what is actually correct? Can one point me a concrete location in the JLS?

like image 519
MKK Avatar asked Dec 03 '12 17:12

MKK


People also ask

Is volatile a memory barrier?

volatile in most programming languages does not imply a real CPU read memory barrier but an order to the compiler not to optimize the reads via caching in a register. This means that the reading process/thread will get the value "eventually".

What is memory barrier in Java?

Memory barriers, or fences, are a set of processor instructions used to apply ordering limitations on memory operations.

What does volatile mean in Java?

For Java, “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself.

Is volatile variable in Java thread safe?

Unlike synchronized methods or blocks, it does not make other threads wait while one thread is working on a critical section. Therefore, the volatile keyword does not provide thread safety when non-atomic operations or composite operations are performed on shared variables.


1 Answers

Yes, it will initiate a barrier. You can read more here. There are 4 types, LoadLoad LoadStore StoreStore StoreLoad.

As far as your question

From the JLS, it seems that only the variable concerned gets flushed out, but not others. Does anybody know what is actually correct?

All writes that occur before a volatile store are visible by any other threads with the predicate that the other threads load this new store. However, writes that occur before a volatile load may or may not be seen by other threads if they do not load the new value.

For a practical example

volatile int a =0; int b = 0;  Thread-1 b = 10; a = 3;  Thread-2 if(a == 0){   // b can b 10 or 0 }  if(a == 3){    // b is guaranteed to be 10 (according to the JMM) } 
like image 130
John Vint Avatar answered Nov 22 '22 05:11

John Vint