private volatile Object obj = new MyObject();
void foo()
{
synchronized(obj)
{
obj.doWork();
}
}
void bar()
{
synchronized(obj)
{
obj.doWork();
obj = new MyObject(); // <<<< notice this line (call it line-x)
}
}
Suppose at a certain point in time, a thread t_bar
is executing bar()
, and another one t_foo
is executing foo
, and that t_bar
has just acquired obj
, so t_foo
is, in effect, waiting.
After the sync-block in bar
is executed, foo
will get to execute its sync-block, right? What value of obj
would it see? The old one? Or the new one set in bar
?
(I would hope that the new value is seen, that's the whole point of coding it that way, but I want to know if this is a 'safe' bet)