What happens to the lock when thread crashes insid

2019-04-29 07:50发布

问题:

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.