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

Ryan LeCompte ryan.lecompte at pangonetworks.com
Tue Oct 25 09:16:46 EDT 2005


Hello all,

 

I know that one has two options for "protecting" data that can be
potentially read/written by multiple threads. In order for the main thread
to always see the most recently written value, one must declare the variable
as "volatile" or synchronize all access to it, such as:

 

synchronized void stop() {

   stopped = true;

}

 

synchronized boolean isStopped() {

   return stopped;

}

 

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? 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?

 

Thanks,

Ryan

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20051025/2378a6f7/attachment.htm


More information about the Concurrency-interest mailing list