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

萝らか妹 提交于 2019-12-05 08:52:01

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.

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.

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.

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