[concurrency-interest] Synchronization question

Tim Peierls tim at peierls.net
Tue Jun 27 17:24:23 EDT 2006


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

--tim

On 6/27/06, Jeremy Manson <jmanson at cs.purdue.edu> wrote:
>
> Hi Ryan,
>
> There has to be a happens-before relationship between the assignment to
> the variable and any read of it.  This means that, when you say:
>
> > The system is written such that these other threads will NOT invoke the
> > non-synchronized accessor method until the synchronized method is
> > invoked.
>
> Then if there is a happens-before relationship making this guarantee,
> then you are fine.
>
> The happens-before guarantee can be made by, for example, a write to a
> volatile in the writer thread after the write, and a read of the same
> variable in the reader thread before the read. Alternatively, you can
> have an unlock in the writer thread after the write, followed by a lock
> on the same monitor in a reader thread before the read.  Alternatively,
> you can have the writer thread start the reader threads after it
> performs the write.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20060627/64c3da6c/attachment.html 


More information about the Concurrency-interest mailing list