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

拥有回忆 提交于 2019-12-07 06:13:35

问题


lets say Thread-1 synchronizes on object

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 ? 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.


回答1:


It is defined in the 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.




回答2:


You should think of the synchronized block:

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.




回答3:


Yes, the monitor (not lock) will be released.

The Java VM spec will be specific about this if you wish to read it.

The exact reference in the JVM spec can be found in section 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. 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.



来源:https://stackoverflow.com/questions/12521776/what-happens-to-the-lock-when-thread-crashes-inside-a-synchronized-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!