[concurrency-interest] Assignment of references atomic?

Tim Peierls tim at peierls.net
Wed Oct 12 12:38:45 EDT 2005

I can't tell from your code sample whether it is safe. The relevant code looked something like this:

   void setObject(Object o) {
       if (someCondition) {
           this.object = o;

If your intent is that "object" only be given a new value when "someCondition" is true -- that's 
what I meant by "class invariant" -- then it is *not* enough to make someCondition and object 
volatiles, because the read of someCondition and the subsequent write to object do not happen 
atomically. Volatiles provide visibility but not atomicity. In that case, you must use 
synchronization when accessing the fields, and there is no point in making the fields volatile.


Ryan LeCompte wrote:
> I'm not sure I completely understood your last reason for *not* using
> volatile. Forgetting about the code sample from earlier, I basically have
> two variables.. one is a primitive (boolean) and the other is a regular
> Object reference. Is it safe to declare both of these as volatile? I want to
> ensure that other threads see the most recent values of these two variables.
> Ryan
> -----Original Message-----
> From: Tim Peierls [mailto:tim at peierls.net] 
> The only reason you might *not* want to use a volatile is if there is a
> class invariant involving more than one field, including the object field. 
> I saw the use of a variable named someCondition and assumed this was the case.

More information about the Concurrency-interest mailing list