[concurrency-interest] Mixing volatile and synchronizedtogether...
dawidk at mathcs.emory.edu
Sat Oct 15 01:50:19 EDT 2005
Ryan LeCompte wrote:
>Great. I just wanted to be clear on the behavior. So it's okay then to use a
>volatile variable in a synchronized method/block as well as an
>unsynchronized method/block in the same class?
>From: Tim Peierls [mailto:tim at peierls.net]
>Sent: Friday, October 14, 2005 11:38 AM
>To: Ryan LeCompte
>Cc: concurrency-interest at altair.cs.oswego.edu
>Subject: Re: [concurrency-interest] Mixing volatile and synchronized
>Ryan LeCompte wrote:
>>I know that there really isn't a need to do this, but I was wondering if
>>In other words, there is no harm in using a volatile variable in a
>>synchronized method or block, right?
Yes, but keep in mind that a volatile (unsynchronized) reader will be
able to see any value set in the middle of a synchronized block by any
writer, so it is only OK if the volatile does not participate in a
multi-field state invariant, and if there are no intermittent illegal
values set temporarily to the variable inside synchronized blocks. In
other words, it must be OK for the reader to see any value that can be
possibly assigned anytime, including in the middle of the synchronized
block, by any writer.
Good example: emulating atomic variables in Java 1.4: all writer methods
are synchronized, but get() is a volatile-read.
More information about the Concurrency-interest