What is the difference from technical perspective between those two listings? First is one that is provided in java doc of lock. Second is mine.
1.
Lock l = ...;
l.lock();
try {
// access the resource protected by this lock
} finally {
l.unlock();
}
2.
Lock l = ...;
try {
l.lock();
// access the resource protected by this lock
} finally {
l.unlock();
}
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.
The difference is in what happens if l
is null:
The first example will fail with an exception that points to the first line, above the try block.
The second example will fail with an NPE that gets masked by another NPE thrown from the finally block.
Also if locking fails, the finally block in the second example could attempt to unlock a lock that was not locked, where the first example will not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With