美文网首页
并发包ReentrantLock源码分析

并发包ReentrantLock源码分析

作者: zcb炒冰 | 来源:发表于2019-10-30 09:35 被阅读0次

首先先分析下reentrantLock的类的基本结构关系,下面是关系图


ReentrantLock.png

从图中可以看出,reentrantlock类实现了Lock接口,并且包含了Sync抽象内部类;而Sync类又继承了AbstractQueuedSynchronizer抽象类,并且Sync的两个具体实现类NonfairSync和FairSync均是reentrantLock的内部类;下面我们就从reentrantlock的lock和unlock方法切入,分析reentrantlock加锁的具体实现流程。

public ReentrantLock() {
        sync = new NonfairSync();
}

当我们new一个reentrantLock对象时,实际上是new一个Sync的NonfairSync对象,当调用了reentrantLock.lock方法时,也是调用Sync抽象类的lock方法。

public void lock() {
        sync.lock();
}

由于new对象是NonfairSync对象,我们直接看NonfairSync类的lock方法

final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
}

进入NonfairSync的lock方法时,首先会先调用compareAndSetState方法,此方法主要是用于比较并置换state变量值,当传入的期望值0等于state变量值时,则会将state变量值变为置换值1,并且返回true,具体的内部实现方法是native方法,这里就不再深究;回到代码上问题,假设有两个线程A和线程B,线程A先进入lock方法,并且进入if判断逻辑,此时state值默认为0,与期望值0一致,所以会将state值变为1,并进入setExclusiveOwnerThread方法,此方法作用是将exclusiveOwnerThread设置为当前线程,可理解为当前线程可以优先执行;而线程B进入lock方法时,此时state值已经变为1,与期望值0不一致,则会走acquire方法

public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
}

进入acquire方法时,会先调用tryAcquire,最终调用的是Sync.nonfairTryAcquire方法,我们直接看nonfairTryAcquire方法逻辑

        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

nonfairTryAcquire方法会先尝试获取当前state变量的值,如果state=0,则会重新调用compareAndSetState方法判断并置换,获得锁优先执行权;或者当前线程为优先执行权线程时,也可以获得锁优先执行权;如果两者都不满足条件,则会返回true,执行addWaiter方法。

    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;
    }

addWaiter方法会生成一个包含当前线程对象的Node节点对象,并把新生成的node节点对象设置在链表的尾部,把原尾部node节点的next node设置为当前节点;当不存在tail node尾部节点时,把当前节点node设置为尾部tail节点和head节点(enq方法);大概逻辑理解可以用以下图解释。


未命名文件.png

当执行完addWaiter方法后,会返回新生成的node对象进入acquireQueued方法

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);
    }
}

此时又会尝试调用tryAcquire方法,因为被线程A占用着,所以tryAcquire返回false,进入shouldParkAfterFailedAcquire方法

private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
    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.
         */
        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.
         */
        compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
    }
    return false;
}

因为pred.waitStatus=0,所以会进入compareAndSetWaitStatus方法设置waitStatus=-1,并返回false执行parkAndCheckInterrupt方法

private final boolean parkAndCheckInterrupt() {
    LockSupport.park(this);
    return Thread.interrupted();
}

此时当前线程B就被中断挂起了,需要等到线程A执行完成后调用unlock方法释放锁后再唤醒线程B才能执行;
线程A执行完后,释放锁需要调用unlock方法,调用reentrantlock.unlock方法最终调用的是Sync.release方法,下面来看下release方法具体实现:

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

线程A进入release方法会先调用tryRelease方法,将state值设置为state-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;
}

设置完state后,进入if逻辑获取head node节点对象,进入unparkSuccessor方法设置下一个执行线程节点node

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)
        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);
}

获取头部head node节点的next node节点,从next node节点获取到下一个执行的线程对象s.thread(B线程)并调用LockSupport.unpark(s.thread)将其唤醒,此时B线程将获得执行权限,执行之前被挂起的死循环逻辑(上面讲到的acquireQueued方法)获得锁,至此逻辑结束。

相关文章

网友评论

      本文标题:并发包ReentrantLock源码分析

      本文链接:https://www.haomeiwen.com/subject/jpebvctx.html