Reason in javadoc documentation .unlock() Lock :
Implementation Recommendations
The implementation of a lock usually imposes restrictions on which thread can release the lock (usually only the owner of the lock can release it) and can throw an exception (unchecked) if the restriction is violated . Any restrictions and type of exclusion should be documented by the Lock implementation.
Similarly, a .lock() can fail with an uncontrolled exception.
This means that in:
l.lock(); try { ... } finally { l.unlock(); }
If the lock fails, you will never reach unlock() . If in:
try { l.lock(); ... } finally { lock.unlock(); }
You do not need to throw two exceptions if the lock fails; and one of them will be lost.
Not to mention that, depending on the implementation of the lock, with the second version, you can end up unlocking someone elseโs lock ... Not good.
source share