1

In this code, shutdown is a non volatile variable in Holder class. In Test object, an holder object is declared as volatile. If I update the shutdown variable, would it have the same effect as a volatile variable in Test class? that is to say, Will other threads immediately see the change after it is updated in one thread.

class Test {
    volatile Holder holder = new Holder();

    public void func() {

        List<Thread> list = new ArrayList<Thread>();
        for (int i = 0; i < 10; i++) {
            list.add(new Thread() {

                public void run() {
                    while (holder.shutdown) {
                        if (...) {
                            holder.shutdown = true; 
                        }
                    }
                }
            });
        }
        for (Thread thread : list) {
            thread.start();
        }


    }


    class Holder {
        boolean shutdown = false;
    }

}
zonyang
  • 828
  • 3
  • 10
  • 24
  • 1
    No. If you assign a new `Holder` to the volatile variable in the writer thread, and read it explicitly in the loop, the reader will read the fresh shutdown flag, since volatile can build a happens-before relationship between the writer and the reader after the the write operation. `while (true) { Holder tmp = holder; if (!tmp.shutdown) { tmp = new Holder(); tmp.shutdown = true; holder = tmp; } }` – xingbin Nov 30 '19 at 07:57
  • 1
    There is no such thing as a `volatile` object. The `volatile` keyword in your example applies to the _variable_ named `holder`. It has no effect on the `Holder` instance to which that variable refers. Also note that the only _guaranteed_ effects of `volatile` all depend on one thread assigning the variable and another thread examining it. Since there are no assignments to `holder` in this example, the `volatile` keyword will not necessarily have any effect at all. – Solomon Slow Nov 30 '19 at 16:26

0 Answers0