简体   繁体   English

当一个对象被锁定,并且该对象被替换时,是否保持了锁?

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

Let's say I have this java code: 假设我有这个java代码:

synchronized(someObject)
{
    someObject = new SomeObject();
    someObject.doSomething();
}

Is the instance of SomeObject still locked by the time doSomething() is called on it? 在调用doSomething()时,SomeObject的实例是否仍然被锁定?

The thread will still own the monitor for the original value of someObject until the end of the synchronized block. 在同步块结束之前,线程仍然拥有someObject 原始值的监视器。 If you imagine that there were two methods, Monitor.enter(Object) and Monitor.exit(Object) then the synchronized block would act something like: 如果你想象有两个方法, Monitor.enter(Object)Monitor.exit(Object)那么synchronized块的行为类似于:

SomeObject tmp = someObject;
Monitor.enter(tmp);
try
{
    someObject = new SomeObject();
    someObject.doSomething();
}
finally
{
    Monitor.exit(tmp);
}

From section 14.19 of the JLS : JLS第14.19节

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. 否则,如果Expression的值为null,则抛出NullPointerException。

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. 否则,让表达式的非空值为V.执行线程锁定与V关联的锁。然后执行块。 If execution of the Block completes normally, then the lock is unlocked and the synchronized statement completes normally. 如果块的执行正常完成,则解锁并且synchronized语句正常完成。 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(); someObject = new SomeObject(); the variable someObject references a new object, the lock is still on the old one. 变量someObject引用一个新对象,该锁仍然在旧对象上。

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 看一下这个解释得很好的页面: http//download.oracle.com/javase/tutorial/essential/concurrency/locksync.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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