Let's say I have this java code:
synchronized(someObject)
{
someObject = new SomeObject();
someObject.doSomething();
}
Is the instance of SomeObject still locked by the time doSomething() is called on it?
The thread will still own the monitor for the original value of someObject
until the end of the synchronized block. If you imagine that there were two methods, Monitor.enter(Object)
and Monitor.exit(Object)
then the synchronized block would act something like:
SomeObject tmp = someObject;
Monitor.enter(tmp);
try
{
someObject = new SomeObject();
someObject.doSomething();
}
finally
{
Monitor.exit(tmp);
}
From section 14.19 of the JLS:
A synchronized statement is executed by first evaluating the Expression.
If evaluation of the Expression completes abruptly for some reason, then the synchronized statement completes abruptly for the same reason.
Otherwise, if the value of the Expression is null, a NullPointerException is thrown.
Otherwise, let the non-null value of the Expression be V. The executing thread locks the lock associated with V. Then the Block is executed. If execution of the Block completes normally, then the lock is unlocked and the synchronized statement completes normally. If execution of the Block completes abruptly for any reason, then the lock is unlocked and the synchronized statement then completes abruptly for the same reason.
Note how the evaluation only occurs once.
The lock applies to an object, not a variable. After someObject = new SomeObject();
the variable someObject
references a new object, the lock is still on the old one.
Bye and bye very dangerous.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With