[concurrency-interest] Volatile array and Wait

Jeremy Manson jmanson at cs.purdue.edu
Wed Oct 19 14:07:58 EDT 2005


Jeremy Manson wrote:
> Chris Purcell wrote:
> 
>> Okay, I've thought this out a bit. My analysis follows.
> 
> 
> Hmm...  What we have here is a situation where I pointed out the problem 
> you bring up, and then you suggested a fix, and I completely missed that 
> you were pointing out a fix.
> 
> My mistake.  Sorry.
> 

There is a little confusion about this.  I didn't realize that the 
problem that Chris was fixing was this one I brought up:

 > In general, you have to be very careful about using this.  I would
 > suspect that in nine cases out of ten, it will not do what you want
 > it to do.  For example, if you were trying to use this for a
 > singleton, it would NOT be correct:
 >
 > Bad Writer Thread:
 > b[22] = new SingletonObject();
 > b = b;
 >
 > Bad Reader Thread:
 > SingletonObject so = b[22];
 > so.doThings();
 >
 > You could easily imagine the reader thread being scheduled between
 > the two statements of the writer thread.  Guess what?  In that case,
 > you don't see the effects of the volatile write.

Chris's point was that by putting the b = b statement *before* the write 
to b[22], thus:

1: SingletonObject so = new SingletonObject();
2: b = b;
3: b[22] = so;

then if the reader thread sees the SingletonObject reference, it is 
guaranteed to see the fully constructed SingletonObject.

Of course, if we were to use this code, it would mean that no one is 
actually guaranteed to see the write of the SingletonObject reference to 
b[22].  This was my point.  If you want to guarantee *that*, you have to 
do it this way:

1: SingletonObject so = new SingletonObject();
2: b = b;
3: b[22] = so;
4: b = b;

The volatile write on line 2 guarantees that *if* anyone sees the 
SingletonObject reference, they will also see the correctly constructed 
SingletonObject.  The volatile write on line 4 changes that *if* to a 
*when*: it guarantees that other threads will actually see the reference.

Sorry about the crossed signals.  I hope that clears matters up, and is 
a clear illustration to people why this stuff is hard.

					Jeremy


More information about the Concurrency-interest mailing list