ReentrantLock底层源码分析

  1. ReentrantLock lock = new ReentrantLock();

一、加锁

  1. // 非公平锁,公平锁和非公平锁的区别就是新进入的线程是否可以插队获取锁资源
  2. final void lock() {
  3. if (compareAndSetState(0, 1)) {
  4. setExclusiveOwnerThread(Thread.currentThread());
  5. } else {
  6. acquire(1);
  7. }
  8. }
  9. // 尝试获取锁,如果获取锁失败则加入到等待队列中
  10. public final void acquire(int arg) {
  11. if (!tryAcquire(arg) &&
  12. acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
  13. selfInterrupt();
  14. }

1.加锁成功

// 尝试获取锁
protected final boolean tryAcquire(int acquires) {
            // 当前尝试加锁线程
            final Thread current = Thread.currentThread();
            // 锁的状态标识
            int c = getState();
            if (c == 0) {
                if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {
                    // 将独占线程设置为当前线程
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            // 可重入锁
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

2.加锁失败,初始化队列

private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail;
        if (pred != null) {
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        enq(node);
        return node;
    }

// 创建头节点,将当前线程的节点设置为尾节点,且相互指向
private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }

Node节点中包含4个重要的属性:

  • pred:指向前一个节点
  • next:指向后一个节点
  • thread:线程
  • waitStatus:标记当前节点的信号量状态(1,0,-1,-2,-3)

    • 1:表示当前线程已经中断,在队列中没有意义,可以被剔除
    • 0:初始化状态
    • -1:后继节点的线程处于等待状态,而当前节点如果释放了锁将会通知后继节点重新获取锁资源
    • -2: 节点在等待队列中,节点的线程等待在Condition上,当其他线程对Condition调用了signal()方法后, 该节点会从等待队列中转移到同步队列中,加入到同步状态的获取中
    • -3: 表示下一次共享方式同步状态获取将会被无条件的传播下去

当线程A已经加锁成功且还没有释放锁,此时线程B尝试加锁,则会加锁失败,会初始化一个双向列表的节点队列,创建一个头节点和尾节点,并将当前线程的节点通过CAS设置成尾节点,且头尾节点相互指向,头节点的next为尾节点,尾节点的pred为头节点。

// final Node node 传入的当前线程的节点
final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                // 当前节点的前一个节点
                // 第一次p为头节点
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                // 尝试获取锁资源失败后阻塞等待
                if (shouldParkAfterFailedAcquire(p, node) &&
                    // 让当前线程阻塞
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
// Node pred 当前节点的前一个节点,Node node 当前线程节点
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        // ws 第一次为0
        int ws = pred.waitStatus;
        if (ws == Node.SIGNAL)
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;
        if (ws > 0) {
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
            // ws >1 表示当前线程可能中断,可以被剔除
            do {
                // 当前节点的前一个节点指向 前一个节点的前一个节点
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            /*
             * waitStatus must be 0 or PROPAGATE.  Indicate that we
             * need a signal, but don't park yet.  Caller will need to
             * retry to make sure it cannot acquire before parking.
             */
            // 将前一个节点的ws设置为-1
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }

将当前线程节点的前一个节点的ws设置为-1,已方便获取锁的线程释放锁后唤醒队列中除头节点的第一个节点

二、释放锁

public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

1.尝试释放锁

protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }

将锁的状态标识设置为0,且将独占线程设置为空

2.唤醒队列中的节点

// Node node,传入的参数node为头节点
// 此时node中属性,ws=-1
private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
        if (ws < 0)
            // 将头节点ws设置为0
            compareAndSetWaitStatus(node, ws, 0);

        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
        Node s = node.next;// 头节点的后一个阻塞的节点
        if (s == null || s.waitStatus > 0) {
            s = null;
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        if (s != null)
            // 唤醒头节点的后一个节点
            LockSupport.unpark(s.thread);
    }

3.唤醒后的节点尝试重新获取锁资源

final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    // 唤醒后从这里重新执行代码
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

当重新获取到锁资源时,将锁状态标志位设置为1,将当前节点设置为头节点,将当前节点的前一个节点制空,当前节点线程属性制空,(就是将原来的head头节点清除)

private void setHead(Node node) {
        head = node;
        node.thread = null;
        node.prev = null;
    }