有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程Java锁定结构最佳模式

从技术角度来看,这两个列表有什么不同?第一个是在lock的java文档中提供的。第二个是我的

一,

 Lock l = ...;
         l.lock();
         try {
             // access the resource protected by this lock
         } finally {
             l.unlock();
         }

二,

Lock l = ...;

     try {
         l.lock();
         // access the resource protected by this lock
     } finally {
         l.unlock();
     }

共 (2) 个答案

  1. # 1 楼答案

    区别在于l为空时会发生什么:

    • 第一个示例将失败,异常指向try块上方的第一行

    • 第二个例子将失败,一个NPE被finally块抛出的另一个NPE屏蔽

    此外,如果锁定失败,第二个示例中的finally块可以尝试解锁未锁定的锁,而第一个示例不会

  2. # 2 楼答案

    原因可以在the javadoc of the ^{} documentation of ^{}中找到:

    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.

    类似地,.lock()可能会失败,并出现未经检查的异常

    这意味着:

    l.lock();
    try {
        ...
    } finally {
        l.unlock();
    }
    

    如果锁定失败,您将永远无法访问^{。鉴于:

    try {
        l.lock();
        ...
    } finally {
        lock.unlock();
    }
    

    如果锁定失败,则不必要地抛出两个异常;其中一个将会丢失

    更不用说,根据锁的实现,第二个版本可能会解锁“其他人”的锁。。。这不是一件好事