简体   繁体   English

线程在同步块内崩溃时锁定会发生什么?

[英]What happens to the lock when thread crashes inside a Synchronized block?

lets say Thread-1 synchronizes on object 让我们说Thread-1在对象上同步

synchronize(object){
  //statement1
  //statement2
  //statement3
}

what happens to the lock on object if Thread-1 crashes on statement2, will JVM release the lock on Thread-1 automatically when this happens ? 如果Thread-1在statement2上崩溃,对象上的锁会发生什么?当发生这种情况时,JVM会自动释放Thread-1上的锁吗? because otherwise if Thread-2 is wating for the lock on object to be released and Thread-1 crashes, the Thread-2 will wait forever. 因为否则如果Thread-2正在为要释放的对象锁定并且Thread-1崩溃,则Thread-2将永远等待。

It is defined in the JLS #14.19 : 它在JLS#14.19中定义:

synchronized ( Expression ) Block

If execution of the Block completes abruptly for any reason, then the monitor is unlocked and the synchronized statement completes abruptly for the same reason. 如果块的执行因任何原因突然完成,则监视器将被解锁并且同步语句由于同样的原因而突然完成。

You should think of the synchronized block: 你应该想到synchronized块:

synchronized(lock) {
   // code
}

as being the equivalent of (pseudocode): 作为(伪代码)的等价物:

lock.acquire();
try {
   // code
} finally {
   lock.release();
}

Thus, the lock will be released, no matter what happens in the code section. 因此,无论代码部分发生什么,锁都将被释放。

Yes, the monitor (not lock) will be released. 是的,显示器(不是锁定)将被释放。

The Java VM spec will be specific about this if you wish to read it. 如果您希望阅读它,Java VM规范将具体说明。

The exact reference in the JVM spec can be found in section 2.11.10 JVM规范中的确切参考可以在2.11.10节中找到

When invoking a method for which ACC_SYNCHRONIZED is set, the executing thread enters a monitor, invokes the method itself, and exits the monitor whether the method invocation completes normally or abruptly. 当调用设置了ACC_SYNCHRONIZED的方法时,执行线程进入监视器,调用方法本身,并退出监视器,无论方法调用是正常还是突然完成。 During the time the executing thread owns the monitor, no other thread may enter it. 在执行线程拥有监视器期间,没有其他线程可以输入它。 If an exception is thrown during invocation of the synchronized method and the synchronized method does not handle the exception, the monitor for the method is automatically exited before the exception is (re)thrown out of the synchronized method. 如果在调用synchronized方法期间抛出异常并且synchronized方法不处理异常, 则在异步(重新)抛出异步方法之前,将自动退出该方法的监视器。

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

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