Java locking structure best pattern

前端 未结 2 1271
小鲜肉
小鲜肉 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:43

    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.

提交回复
热议问题