Bartvbl
Bartvbl

Reputation: 2928

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?

Upvotes: 4

Views: 110

Answers (4)

oanoss
oanoss

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

Miserable Variable
Miserable Variable

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

Jon Skeet
Jon Skeet

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

John B
John B

Reputation: 32969

I believe the previous instance of someObject is locked and your new instance is not locked.

Upvotes: 1

Related Questions