Java NIO-Lock.unlock

来源:互联网 发布:ubuntu认证失败 编辑:程序博客网 时间:2024/05/23 02:00

unlock用来释放锁,使用lock保护临界区,但是临界区通常会出现异常,所以unlock我们会放在finall语句中执行。

  1. lock.lock();
  2. try{
  3.   //do something
  4. } finally {
  5.    lock.unlock();
  6. }


Lock的实现类ReentrantLock中unlock的实现来自其成员变量sync实现.

  1. public void unlock() {
  2.        sync.release(1);
  3.    }

具体调用AbstractQueuedSynchronized对象的release方法。

  1.    public final boolean release(int arg) {
  2.        if (tryRelease(arg)) {
  3.            Node h = head;
  4.            if (h != null && h.waitStatus != 0)
  5.                unparkSuccessor(h);
  6.            return true;
  7.        }
  8.        return false;
  9.    }


  1. /**
  2.     * Wakes up node's successor, if one exists.
  3.     *
  4.     * @param node the node
  5.     */
  6.    private void unparkSuccessor(Node node) {
  7.        /*
  8.         * If status is negative (i.e., possibly needing signal) try
  9.         * to clear in anticipation of signalling.  It is OK if this
  10.         * fails or if status is changed by waiting thread.
  11.         */
  12.        int ws = node.waitStatus;
  13.        if (ws < 0)
  14.            compareAndSetWaitStatus(node, ws, 0);
  15.        /*
  16.         * Thread to unpark is held in successor, which is normally
  17.         * just the next node.  But if cancelled or apparently null,
  18.         * traverse backwards from tail to find the actual
  19.         * non-cancelled successor.
  20.         */
  21.        Node s = node.next;
  22.        if (s == null || s.waitStatus > 0) {
  23.            s = null;
  24.            for (Node t = tail; t != null && t != node; t = t.prev)
  25.                if (t.waitStatus <= 0)
  26.                    s = t;
  27.        }
  28.        if (s != null)
  29.            LockSupport.unpark(s.thread);
  30.    }


0 0