Total Order between !different! volatile variables?

Posted by andreas on Stack Overflow See other posts from Stack Overflow or by andreas
Published on 2010-03-31T18:28:37Z Indexed on 2010/03/31 18:33 UTC
Read the original article Hit count: 309

Filed under:
|
|

Hi all,

Consider the following Java code:

volatile boolean v1 = false;
volatile boolean v2 = false;

//Thread A
v1 = true;
if (v2)
    System.out.println("v2 was true");

//Thread B
v2 = true;
if (v1)
    System.out.println("v1 was true");

If there was a globally visible total order for volatile accesses then at least one println would always be reached.

Is that actually guaranteed by the Java Standard? Or is an execution like this possible:

A: v1 = true;
B: v2 = true;
A: read v2 = false;
B: read v1 = false;
A: v2 = true becomes visible (after the if)
B: v1 = true becomes visible (after the if)

I could only find statements about accesses to the same volatile variable in the Standard (but I might be missing something).

"A write to a volatile variable (§8.3.1.4) v synchronizes-with all subsequent reads of v by any thread (where subsequent is defined according to the synchronization order)."

http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.4.4

Thanks!

© Stack Overflow or respective owner

Related posts about java

Related posts about volatile