[concurrency-interest] Assignment of references atomic?

Ryan LeCompte ryan.lecompte at pangonetworks.com
Wed Oct 12 09:40:56 EDT 2005


Thank you for the lengthy response. This particular part of the code can
tolerate stale values that are returned from the getObject() method.
However, I want to be able to rely on the fact that the getObject() method
will EVENTUALLY return a recent update to the this.object (o) field. Am I
safe to make that assumption? Or is it possible for the JVM to always return
a stale value even if the value gets updated one more time? What about
declaring the variable volatile? 


-----Original Message-----
From: Tim Peierls [mailto:tim at peierls.net] 
Sent: Wednesday, October 12, 2005 9:26 AM
To: Ryan LeCompte
Cc: concurrency-interest at altair.cs.oswego.edu
Subject: Re: [concurrency-interest] Assignment of references atomic?

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 

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.


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