简体   繁体   中英

Why non-volatile approach works?

Look at this code.

Thread:

public class MyThread extends Thread {

    int a = 0;
    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);
    }


}

And the main class:

public class Main {

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

        MyThread t = new MyThread();
        t.start();
        t.write(1, 2);
        System.out.println(t.getA() + " " + t.getB());

    }
}

Output is:

1 2
1 2

But as you can see a and b are not volatile. So why output is not:

1 2
0 0

And how main thread cache knows about another thread cache without volatile statement? Could you show me the example, where that case gives us different values?

Writing a variable in one thread, and reading it in another thread (without it being volatile, or synchronized etc) is not thread-safe.

You can get either "0 0", "1 0", "0 2", or "1 2" as possible outputs. Neither one of them is guaranteed. A thread may cache the values of a and b which would cause "0 0" to be output, but this is just one possible outcome. It doesn't need to happen.

Volatile would provide the guarantee that "1 2" would be output.

If you only have one Thread, there won't be a problem anyway. Just have n Threads and log, whatever you can (or better write some Tests). There may be situtations, when it fails.

Ah! Your Integers should be in another class then. Lets say, about 10 Threads modify/read the very same instance. Were are nearly there :D

You will make em volatile then, that's a promise!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM