[concurrency-interest] Volatile array and Wait

Tim Peierls tim at peierls.net
Fri Oct 21 10:43:10 EDT 2005


>>>On the consideration of a no op ...
>>>
>>>  volatile Object[] b = new Object[50]; ...
>>>  b = b;      // volatile write
>>>
>>>Isn't the compiler/jit liable to remove the b=b statement, 

The fact that this thread has gone on for so long about the ins and outs of volatiles might 
encourage folks to think that proper concurrent program design often depends on this kind of 
finicky reasoning. That would be a shame.

Don't use volatile reads and writes to manage visibility of anything but the volatile value 
itself. Yes, the rules permit more than this, but they are there to protect you, not for you to 
write the concurrency equivalent of spaghetti code. (And yes, Doug Lea does it, in AQS/AQLS, but I 
hope fewer than two people reading this believe they are Doug Lea.)

*Do* use Atomic{Integer,Long,Reference}Array if you really need each element of an array to have 
volatile semantics. As a bonus, you'll get per-element atomic updates, something you'll probably 
want eventually even if you think you don't need it right now.

Of course, if there is any interdependence at all between elements of an array, you need explicit 
synchronization, in which case there is no point in using AtomicXxxArray and the entire discussion 
is moot.

--tim



More information about the Concurrency-interest mailing list