[concurrency-interest] dealing with people that questionvisibility problems

David Holmes dcholmes at optusnet.com.au
Wed Feb 21 18:50:48 EST 2007


Peter,

> public class SomeRunnable implements Runnable{
>     private boolean stop = false;
> 
>     public void stop(){
> 	stop = true;
>     }
> 
>     public void run(){
>     	while(!stop){
> 		System.out.println("hello");
> 	}
>     }
> }
> There are a few reasons why this runnable could fail to stop:
> ... A possible
> scenario would be: thread1 (the thread that executed run) is running
> on cpu1 (with cache1). Thread2 (the thread that calls stop) is running
> on cpu2 (with cache2). When thread1 runs, it needs the value of stop,
> sees the initial false value and places it in his cache. When thread2
> executes stop, stop is set to true. But it might happen that this
> value remains in cache2 for an undetermined time and isn't flushed to
> main memory, so thread1 never sees the new value when it happens to
> read from main memory. Even if the value is flushed to main memory,
> thread1 could still be reading the stale value from cache1.
> 	</li>

As I've written before using caches as a motivation is a bad idea. While this is theoretically possible given an abstract caching mechanism, in practice cache coherency on modern SMPs won't allow the above to happen. It might have been possible on Alpha's. When people who understand hardware caching realize the example can not happen they extrapolate that to imply visibility is not an issue they have to worry about.

> 	<li>
> 		because the access to the stop variable isn't 
> safely published, and
> the value doesn't change in the loop, the 'compiler' (JIT, cpu etc)
> could decide to replace the variable read by the constant 'true' in
> that loop.
> 	</li>

Yes. This can and will happen. Hoptspot server compiler will effectively rewrite the loop as:
   if (!stop)
      while(true) ...


As for the general argument "if it ain't broke don't fit it" - well it *IS* broke. Just because the bug hasn't manifested itself yet doesn't mean it never will.

Howver, going to the extreme of making every field either final or volatile is pointless. If a field has visibility issues because it isn't volatile, there's a good chance that it also has atomicity issues that volatile can't fix.

Cheers,
David Holmes




More information about the Concurrency-interest mailing list