Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java locking structure best pattern

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();
     }
like image 495
RMachnik Avatar asked Jun 25 '15 19:06

RMachnik


Video Answer


2 Answers

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.

like image 72
fge Avatar answered Oct 03 '22 03:10

fge


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.

like image 39
Nathan Hughes Avatar answered Oct 03 '22 03:10

Nathan Hughes