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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With