简体   繁体   中英

Why is the write to non-volatile visible to the main-thread?

Imagine the following program.

class Main {


    static class Whatever {
        int x = 0;
    }


    public static void main(String[] args) {
        Whatever whatever = new Whatever();

        Thread t = new Thread(() -> {
            whatever.x = 1;
        });
        t.start();
        try {
            t.join();
        }
        catch (InterruptedException e) {
        }

        System.out.println(whatever.x);
    }
}

The main-thread has cached whatever and x is set to 0 . The other thread starts, caches whatever and sets the cached x to 1 .

The output is

1

so the main-thread has seen the write. Why is that?

Why was the write done to the shared cache and why has the main-thread invalidated its cache to read from the shared cache? Why don't I need volatile here?

Because of the main thread joining on it. See 17.4.5 in the JLS:

All actions in a thread happen-before any other thread successfully returns from a join() on that thread.

Btw it is true that not having a happens-before doesn't necessarily mean something won't be visible.

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