[concurrency-interest] Synchronization question

Brian Goetz brian at quiotix.com
Tue Jun 27 18:18:44 EDT 2006


And, just for completeness: synchronized write + nonsynchronized read 
doesn't create the required happens-before, so it doesn't work.  The 
getter in such a case isn't required to ever return anything other than 
the default (zero) value.

Tim Peierls wrote:
> Jeremy answered the question, but there's another important point: Code 
> that relies on complicated happens-before reasoning is bound to be 
> harder to understand and maintain than code with a straightforward 
> synchronization policy.
> 
> Volatile access is not expensive. Unless there is a demonstrable 
> performance disadvantage in this particular case, you should either make 
> the field volatile or synchronize the accessor method. Don't make future 
> maintainers of your code read through a justification of why 
> non-volatile, non-synchronized access is OK, even if it is. (And 
> definitely don't leave out such a justification if you are relying on it!)
> 
> Chapters 2-4 of Java Concurrency in Practice make this point much more 
> compellingly than I can here. :-)


More information about the Concurrency-interest mailing list