[concurrency-interest] Synchronization question

Ryan LeCompte Ryan.LeCompte at pangonetworks.com
Tue Jun 27 17:43:07 EDT 2006


Thanks! I'll make the field volatile then. There is absolutely no harm in making a field volatile and using it inside of another synchronized method/block, correct? No potential deadlocks simply due to the variable being made volatile?
 
Thanks,
Ryan

________________________________

From: tpeierls at gmail.com on behalf of Tim Peierls
Sent: Tue 6/27/2006 5:24 PM
To: Ryan LeCompte
Cc: Jeremy Manson; concurrency-interest at cs.oswego.edu
Subject: Re: [concurrency-interest] Synchronization question


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/43bf9fb5/attachment.html 


More information about the Concurrency-interest mailing list