Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When an object is locked, and this object is replaced, is the lock maintained?

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?

like image 684
Bartvbl Avatar asked Jan 18 '23 14:01

Bartvbl


2 Answers

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.

like image 162
Jon Skeet Avatar answered Jan 25 '23 23:01

Jon Skeet


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.

like image 23
Miserable Variable Avatar answered Jan 25 '23 23:01

Miserable Variable