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

Brian Goetz brian at quiotix.com
Tue Oct 25 16:12:55 EDT 2005

 > 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

You would be incorrect, then.

To put it in terms of the new JMM: the compiler can prove that the only 
writes to a non-volatile 'stopped' that can happen-before the next read 
to stopped occur in the body of the loop.  If it can prove that there 
are no such writes in the body of the loop, it becomes loop-invariant 
and can be hoisted.

The fact that another thread may want to write to stopped does not 
matter -- it is only writes that happen-before the next read in this 
thread that the compiler need pay attention to.

All access to shared mutable state must be done with appropriate 
synchronization, otherwise bad things happen.

>> 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.

More information about the Concurrency-interest mailing list