Reputation: 2928
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?
Upvotes: 4
Views: 110
Reputation: 86
It's important to understand the difference between synchronized methods and synchronized statements.
Take a look at this page which explains it pretty well: http://download.oracle.com/javase/tutorial/essential/concurrency/locksync.html
Upvotes: 0
Reputation: 28761
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.
Upvotes: 3
Reputation: 1501656
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.
Upvotes: 5
Reputation: 32969
I believe the previous instance of someObject is locked and your new instance is not locked.
Upvotes: 1