The reason is to be found in the javadoc of the .unlock()
documentation of Lock
:
Implementation Considerations
A Lock implementation will usually impose restrictions on which thread can release a lock (typically only the holder of the lock can release it) and may throw an (unchecked) exception if the restriction is violated. Any restrictions and the exception type must be documented by that Lock implementation.
Similarly, a .lock()
may fail with an unchecked exception.
Which means that in:
l.lock();
try {
...
} finally {
l.unlock();
}
if the locking fails, you never get to unlock()
. Whereas in:
try {
l.lock();
...
} finally {
lock.unlock();
}
you needlessly throw two exceptions if the locking fails; and one of them will be lost.
Not to mention that depending on the implementation of the lock, with the second version you may end up unlocking "someone else"'s lock... Not a good thing.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…