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

Jeremy Manson jmanson at cs.purdue.edu
Tue Oct 25 10:36:58 EDT 2005


Ryan LeCompte wrote:

> However, if the "synchronized" approach is taken, does it have to be
> at such a granular level? Or can it suffice that whenever the
> variable "stopped" is used, that it's at least protected by SOME
> lock? For example, if "stopped" is only directly referenced in three
> methods that perform various operations, can all three methods be
> declared as "synchronized" and the above two methods (stop() /
> isStopped()) simply removed? Or do we always need to have
> "synchronized accessors" for the variable in question?


You can do it this way.  Synchronized accessors are nice because that
way, anyone who uses the variable in future revisions of the code will
be forced to synchronize.  But if it saves a reasonable amount of
locking overhead, there is no reason not to do what you suggest.

Bear in mind the answer to the next question, though - it is crucial
when deciding whether you have done this correctly or not.

> Also, what happens if there are three methods that use the "stopped"
> variable, but they are using different locks? For example, let's say
> method1 uses "stopped" in a synchronized block on LOCK1, and method2
> uses "stopped" in a synchronized block on LOCK2, and method3 uses
> "stopped" in a synchronized block on LOCK3. Will we still have the
> same effect as simply declaring the variable as "volatile" here?

This is no good.  You won't get ordering or visibility guarantees.
Locks are only guaranteed to be ordered with respect to each other if
they are on the same monitor.  There are a whole host of potential
problems.

The first, and most obvious, one is that you won't get mutual exclusion.

The second is that the compiler can remove a lock if it doesn't think
that lock will ever be used to communicate between threads.  The way it
decides this is by determining if there is another thread that accesses
that lock.  So you are introducing the possibility that the lock will be
eliminated.

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

					Jeremy


More information about the Concurrency-interest mailing list