Better Java Blocking Structure Structure

What is the difference from the technical perspective between the two lists? First up is the one introduced in java doc lock . The 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(); } 
+5
source share
2 answers

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.

+8
source

The difference is 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 is masked by another NPE thrown from the finally block.

Also, if the lock failed, the finally block in the second example may try to unlock the lock that was not locked, where the first example will not.

+5
source

All Articles