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

Gregg Wonderly gregg at cytetech.com
Tue Oct 25 14:31:47 EDT 2005



Jeremy Manson wrote:
> It would be perfectly legal for a compiler to examine the code in Thread 
> 1 and determine that it does not change the value of stopped.  It could 
> then decide that what you have in Thread 1 is an infinite loop, and 
> remove the loop guard:
> 
> Replacement Thread 1:
> if (!stopped) {
>   while (true) {
>     // do stuff
>   }
> }
> 
> And Thread 1 will never end, regardless of what Thread 2 does.

I don't believe this is a valid optimization.  If the visibility of stopped is 
such that it can be referenced outside of the context the compiler is 
optimizing, then it can't possibly make this change to the code.  In that code, 
it would be perfectly valid for someone to code

synchronized( something ) {
	stopped = true;
}

and that would make the "stopped" change visible to the Thread 1 context.  This 
is java and late bindings can wreak havoc on such optimizations that are 
possible in other languages.

If Jeremy is suggesting that the compiler has done complete visibility analysis 
and can absolutely determine that the value is not altered, perhaps it might 
make that change.

I'm not convinced that such an optimization strategy would be a safe thing to 
do.  It will create such amazingly ugly bugs.  In code that has failed to 
utilize volatile (it didn't really work before) correctly, there are problems 
that will be very difficult to find with such changes to the code.  Now that 
volatile does actually work, it will be very unhelpful for the language to have 
compilers and JITs being this agressive, out of the box.

It would be very nice to have some tools that would look for variables that are 
read and written in different methods, in unsynchronized (from the method level 
down) blocks.  If they could do more global analysis too, that would be great. 
Then, you could scan your code and look for disparate paths of reading and 
alteration and then go study them to decide whether there were problems there or 
not.

Gregg Wonderly



More information about the Concurrency-interest mailing list