Re: Thread safety and atomic assignment (again)
Philipp wrote:
brian@briangoetz.com wrote:
Perhaps I can clarify. Szabolics' analysis is correct, but I would
put it slightly differently. Its not so much a question of "what do
you mean by safe." Its a question of what you expect from this
class.
By making the internal field volatile, you have made your class data-
race free. This means that callers of get() will see the most recent
value passed by any thread to set(). However, you cannot use this
class to safely build a counter, for example; uses like
foo.set(foo.get() + 1)
are in danger of "lost updates" because there's no way to make the
set(get()+1) operation atomic with respect to other ops on Test2
object. That might be OK.
If I understand this correctly, then synchronizing set and get would
guarantee the correct counter behavior by making set and get *mutually*
exclusive, which is not guaranteed by volatile.
But is there a difference between the above and this?
Actually, that isn't any different than volatile really.
You have to synchronize the entire operation.
Imagine two threads A and B, and foo's value is 10
A: foo.get() is called, returns 10
B: foo.get() is called, returns 10
A: adds one to result (11) and stores it in newValue.
B: adds one to result (11) and stores it in newValue.
A: foo.set(11) gets called
B: foo.set(11) gets called.
Whoops, we just lost a count! What you need to do to ensure your
counter works as expected is to synchronize the "increment" operation.
int newValue = foo.get() + 1;
foo.set(newValue);
Does the call in one single line guarantee that the lock is passed
directly from the get to the set? Else, another thread with another get
might interfer.
Exactly! The lock isn't passed on.
Can a counter only be implemented with a specific synchronized
"increment()" method?
Man, I should have read you're entire post before replying, you've got
the right idea.
In summary, how can you guys sleep at night without making *everything*
synchronized? (and at the same time, having nightmares about deadlocks I
guess)... ? :-)
I sleep fine by knowing what must be an atomic operation, and what must
be thread-safe, and what doesn't need to be one or the other. I tend to
prefer Thread Confinement, such as having a separate Context per thread,
so mutable objects aren't passed to other threads. That approach is
useful in servlets. Thread Confinement is also used in AWT/Swing on the
Event Dispatch Thread.
Phil
PS: Thanks for the references to Matt Humphrey and Szabolcs
I suggest reading the book Java Concurrency in Practice by Doug Lea. It
is an excellent reference on what, why, and how in handle multi-threaded
programming. Its not too thick, and one of the few reference books
worth ready cover to cover.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>