Happens-before mechanism in Java

I have a question about what happens - before the mechanism in Java. Here is an example:

public class MyThread extends Thread {

        int a = 0;
        volatile int b = 0;

        public void run() {


            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            read();
        }

        public void write(int a, int b) {
            this.a = a;  
            this.b = b;
        }

        public void read() {
            System.out.println(a + " " + b);
        }


    }

This is a clear example of what happens before, and it is safe enough, as I know. awill get the new value correctly, because it faces binitialization. But does reordering mean that security is not guaranteed? I say this:

public void write(int a, int b) {
    this.b = b;
    this.a = a;//might not work? isn't it?
}

UPD Main stream:

public class Main {

    public static void main(String[] args) throws InterruptedException {

        MyThread t = new MyThread();
        t.start();
        t.write(1, 2);


    }
}
+4
source share
1 answer

Creating b volatileand having a writeset value bafter it sets a value aensures:

  • b a,
  • a , , , b .

, b b , , a, b b ( a , ).

, . read :

a + " " + b

Java . , a b. , , a a, b b. b a, "t20" "read-before" a a. .

write -., b a, read b a

, b volatile:

<- >

write a                         read a
write b --> happens before -->  read b

write a -

                                read a
write b --> happens before -->  read b
write a

read , a b -

write b --> happens before -->  read b
write a                         read a

, , write read -

write a
write b --> happens before -->  read b
                                read a
+4

All Articles