Java locking structure best pattern

前端 未结 2 1270
小鲜肉
小鲜肉 2020-12-15 01:18

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.

          


        
2条回答
  •  心在旅途
    2020-12-15 01:38

    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.

提交回复
热议问题