[concurrency-interest] RE: Synchronization of data read by multiple threads

Jeremy Manson jmanson at cs.purdue.edu
Sun Oct 30 16:46:01 EST 2005


Ryan LeCompte wrote:
> Okay, this sounds reasonable. So, if I make the variables "final" and
> they are assigned their values in the constructor, then there is no
> need to make them volatile if they are accessed by multiple threads,
> correct? 

True, but be careful when doing this:

class Foo {
   static Foo global;
   final boolean f;
   Foo() {
     global = this;  // dangerous!
     f = true;
   }
}

In that case, you are "publishing" a reference to the constructed object 
inside the constructor.  Another thread can access the constructed 
object by reading global before the assignment to f happens.  Also, in 
this case:

   Foo() {
     f = true;
     global = this;  // also dangerous!
   }

The compiler can reorder the writes, and you end up with the same problem.

The way to avoid this is not to publish the constructed object inside 
the constructor.  There are guarantees in that case.

 > Also, what happens in the case of a boolean variable that is
> declared as a blank final? If it gets a value assigned to it in the
> constructor, then it keeps that value. Otherwise it just defaults to
> "false" as the final value, correct?

javac won't compile it if you don't definitely assign to it.

					Jeremy


More information about the Concurrency-interest mailing list