Replace normal field around volatile field

Based on

What does volatile do? http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#incorrectlySync

and

New warranties for volatile http://www.ibm.com/developerworks/library/j-jtp03304/

class VolatileExample {
  int x = 0;
  volatile boolean v = false;
  public void writer() {
    x = 42;
    v = true;
  }

  public void reader() {
    if (v == true) {
      //uses x - guaranteed to see 42.
    }
  }
}

It seems that.

1a) write to non-volatile variable x 
1b) write to volatile variable v

1a can never move passage 1b

I was wondering if I change the source code to the next

class VolatileExample {
  int x = 42;
  volatile boolean v = true;
  public void writer() {
    v = false;
    x = 0;
  }

  public void reader() {
    if (v == true) {
      //uses x - guaranteed to see 42?????
    }
  }
}

Is it possible to rearrange the following sequence?

2a) write to volatile variable v
2b) write to non-volatile variable x

I was wondering if 2b can ever move to 2a? . This is because if 2b is capable of moving to 2a, the reader can no longer guarantee that there will be 42 inside the block.

I feel that 2b can move to 2a based on the following information.


http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#reordering

, , .


, , , , .


Roach Motels Java

volatile_v = true;      <-- monitor release
non_volatile_x = 42;
(volatile_v will act as a roach motels, and it is fine for non_volatile_x to move into roach motels)


non_volatile_x = 42;
volatile_v = true;      <-- monitor release
(volatile_v will act as a roach motels, and it is not OK for non_volatile_x to move out from roach motels)
+3
5

, , ( Java5), . x = 0; v = false; , .

, v, , v , v, , v - , , v .

+1

, "" .

, - , 42, 0. , .

, , , 42, , .

+1

, , , , , . , 2b 2a, " ", .

0

, , x . x volatile .

0

2b ( x) 2a ( v), , , v==true x==0).

, !

, VolatileExample . T1 reader. v == true . writer v=false x=0. T1 x, 0 ( 0). 0, , T1 v==true x==0. T1 , . , , .

0

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


All Articles