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

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

> I believe
> Josh Bloch mentions in his book "Effective Java" that you may only see bad
> side effects if you're on a multi processor machine.

I don't believe he said that, but if he did, he was wrong.  You can see 
bad side effects as the result of compiler optimizations (instruction 
reordering, hoisting values into registers, etc) as well.

> It can get even more subtle than that.  So it really needs to be the
> same lock.

I can't stress enough the importance of this point.  Even if all 
accesses are "with synchronization", if you are using different locks, 
you might as well be using no synchronization at all.

The Simple Way: For each shared mutable variable in your program, make 
sure that _every_ access (read or write) to that variable is done with 
the _same_ lock held.

The Complicated Way: Learn the Java Memory Model.  Prove that there is a 
happens-before edge between every write of a shared variable and 
subsequent reads of that variable.

There really isn't much of a middle ground.

More information about the Concurrency-interest mailing list