[concurrency-interest] Assignment of references atomic?

Gregg Wonderly gregg at cytetech.com
Wed Oct 12 11:35:41 EDT 2005

Ryan LeCompte wrote:
> Hello all,
> 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;
>    }
> }

The other replies so far are good information.  The only interesting point, I 
think is that if this.object is not volatile, then there is no guarentee of 
when, exactly, the effects of "this.object = o" will be visible to other 
threads.  You will never see an inconsistant value, but you may not ever/always 
see the "correct" value in other threads.  Either setObject should be 
synchronized, or this.object should be volatile to make sure that the assignment 
is "consistant" with any other sideeffects of calling setObject().

Gregg Wonderly

More information about the Concurrency-interest mailing list