[concurrency-interest] Synchronization question
joe.bowbeer at gmail.com
Tue Jun 27 18:54:49 EDT 2006
On 6/27/06, Ryan LeCompte <Ryan.LeCompte at pangonetworks.com> wrote:
> I have a question regarding thread synchronization and referencing
> variables. Here's the rough description:
> I have a class that has a non-volatile, private member variable. The class
> has a default no-arg constructor which doesn't do anything of importance.
> There is a synchronized method which gets invoked by the main thread, which
> assigns a value to the private member variable (non-primitive), among other
> Then, I have another non-synchronized method which simply returns a
> reference to the private member variable (that's all it does). Multiple
> threads will ultimately invoke this non-synchronized method to get access to
> the variable. My question is this: is it possible that these other threads
> will not see the assignment made to the private member variable by the
> synchronized method? The system is written such that these other threads
> will NOT invoke the non-synchronized accessor method until the synchronized
> method is invoked. Do I want to make this private member variable volatile?
> Hopefully not.
Here's how I view your choices:
If it is true that only one thread will initialize the variable, and
that is guaranteed to happen before any other threads access the
variable (because of synchronization external to this class, e.g.,
Swing event dispatch thread), then neither initializer nor accessor
need to be synchronized and the variable doesn't need to be volatile.
BUT in that case you should definitely document that this class
depends on these conditions.
Otherwise, you should synchronize both initializer and accessor
methods, and you don't need to make the variable volatile. This is my
You could also just make the variable volatile and not synchronize the
methods -- IF the initializer is only doing simple assignment (that
is, nothing that requires an atomic block). But this is kind of
fragile. Leave volatile to the experts is my advice.
The worst thing to do is to synchronize one method and not the other.
This is a sure sign to others that something is messed up :-)
Half-synchronization doesn't do any good at all.
Joe Bowbeer ~ joebowbeer.thruhere.net
More information about the Concurrency-interest