[concurrency-interest] Assignment of references atomic?

Tim Peierls tim at peierls.net
Wed Oct 12 09:25:30 EDT 2005


Short answer: No, this is not safe, but not for the reason you think.

Longer answer: The JVM is under no obligation to make the new value of this.object (o) visible to 
other threads. While it is true that any value other threads see is guaranteed to be *some* value 
that was written by some thread at some point, it will not necessarily be the most *recent* value. 
The value seen by other threads might be a "stale" value; in fact, it might be the field's initial 
value.

The situation with doubles is even worse: not only will threads not necessarily see the most 
recent value, but the value seen might not be a value that was ever written by any thread, a 
so-called "out of thin air" value.

Unless you have confined all getObject/setObject calls to a single thread, or your program can 
tolerate arbitrarily stale values (which is a highly unusual property and one that should be 
documented carefully if you rely on it), you need to guard all accesses to the field with some 
kind of locking. The simplest way to do this is, as you implied, to add the synchronized keyword 
to methods that access this field.

--tim

Ryan LeCompte wrote:
> I know that assignment of doubles are potentially unsafe since they are 
> 64 bits, but I was wonder if assignment of object references are atomic 
> in J2SE 1.4.2 and J2SE 5.0? For example, is it safe to do the following 
> without synchronizing the methods:
> 
> Object getObject() {
>    return object;
> }
> 
> void setObject(Object o) {
>    callAnotherMethod();
>    if (someCondition == true) {
>       callAnotherMethod();
>       this.object = o;
>    }
> }



More information about the Concurrency-interest mailing list