Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 873
Robin Bajaj Avatar asked Sep 20 '12 22:09

Robin Bajaj


3 Answers

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.

like image 173
assylias Avatar answered Nov 15 '22 05:11

assylias


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.

like image 30
Tudor Avatar answered Nov 15 '22 06:11

Tudor


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.

like image 22
dty Avatar answered Nov 15 '22 06:11

dty