General order between! mutable variables?

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 common order for unstable accesses, then at least one println would always be achieved.

Is it really guaranteed by the Java standard? Or is this execution as 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 access to the same mutable variable in the standard (but I could miss something).

"Writing to a mutable variable (ยง8.3.1.4) v is synchronized with all subsequent readings v by any thread (where the next is determined in accordance with the synchronization order).

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

Thank!

+3
source share
6

, , .

v2 B # 2 "" A .

:

" (ยง8.3.1.4) v v ..."

+1

4 , / v1/v2, . , . .

. , " ". " " . "-" . .

+1

- , v2 - volatile.

v2 volatile, A v2, false.

v2 , , , .

, , - , , .

0

: , .

, , Doug Lea , , . (http://gee.cs.oswego.edu/dl/jmm/cookbook.html)


,

!

A: v1 = true;
B: v2 = true; 
A: read v2 = false; // initialization happens before thread start
B: read v1 = false; // initialization happens before thread start

, , , v2 v1 volatile v1 v2 v2 v1

!

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

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

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

... volatile, v2 true B, A .

volatile , , ( ++ - !)

-1

( ), , , :

A: read v2 = false;
A: v1 = true;

"" (if) ( , ).

, , :

A: read v2 = false;
A: v1 = true;
B: read v1 = false;
B: v2 = true;

, , , , , .

I asked a question similar, but definitely not identical (writing a and b from the same stream, reading from different threads) here:

Volatile Warranties and Out of Order Performance

-1
source

Source: https://habr.com/ru/post/1739346/


All Articles