[concurrency-interest] Assignment of references atomic?

Brian Goetz brian at quiotix.com
Wed Oct 12 10:27:50 EDT 2005


There are two things going on here.

The assignment of the _reference_ is atomic -- other threads will either 
see the old value, or the new value, but not gibberish.  But in the 
general case, this program is still broken.  Just atomically assigning 
the reference is not enough to ensure thread-safety -- you still have to 
ensure that the state of the referred-to object is also properly 
published.

It is possible for a thread calling getObject in this case to see a 
partially constructed object; in other words, see an up-to-date value of 
'object' but a stale/inconsistent/invalid version of the object's state, 
because object was not properly published.

In short, no, you cannot do what you want to do.  You have to synchronize.

> Object getObject() {
> 
>    return object;
> 
> }
> 
> void setObject(Object o) {
>    callAnotherMethod();
>    if (someCondition == true) {
>       callAnotherMethod();
>       this.object = o;
>    }
> }



More information about the Concurrency-interest mailing list