Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does reading a volatile reference to an object guarantee atomic reads of the latest values of its properties?

Assuming that all properties are not long or double, does reading a volatile reference to an object guarantee atomic reads of the latest values of its properties?

Here's a concrete example.

public class Foo {
    private int bar;

    public int getBar() {
        return this.bar;
    }

    public void setBar(int bar) {
        this.bar = bar;
    }
}

public class Baz {
    private volatile Foo foo;
}

Thread A may write to Foo's Bar property any time. Thread B can only read Foo's Bar property. If thread B accesses the Bar property through Baz, will it read the latest value of Bar?

like image 363
Tom Tucker Avatar asked Jun 03 '13 18:06

Tom Tucker


1 Answers

In short no. The volatile keyword only applies to the foo reference, not to the fields of the underlying object.

So you would need to mark bar as volatile too to achieve the result your describe.

like image 155
assylias Avatar answered Sep 26 '22 02:09

assylias