简体   繁体   中英

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?

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.

我相信someObject前一个实例已被锁定,并且您的实例未被锁定。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM