独占锁ReentrantLock中的公平锁源码解析

最近几天学习Lock的实现,顺手记下笔记。废话不多说从lock()方法开始。

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

sync是ReentrantLock下的一个属性字段,属于抽象类,有两个实现:FairSync(公平锁)、 NonfairSync(非公平锁)。那这篇解析的会是稍微复杂的公平锁。

final void lock() {
     acquire(1);
}
最后会调用到AbstractQueuedSynchronizer类下的acquire方法:
public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

其中tryAcquire方法又会传递到FairSync类下的tryAcquire方法中,该方法主要是通过CAS方式获取锁(即state+1),成功返回true,否则false。

/**
 * Fair version of tryAcquire.  Don't grant access unless
 * recursive call or no waiters or is first.
 */
protected final boolean tryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    //获取同步状态
    int c = getState();
    //如果没有其他线程占有同步状态
    if (c == 0) {
    	//1、判断当前线程是否为同步队列中的第一个节点
    	//2、CAS设置同步状态
        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;
}

而当tryAcquire方法未获取到锁时返回false,会执行接下来的addWaiter(Node.EXCLUSIVE)方法,该方法主要是把当前线程信息构造成node节点,并放入同步队列的尾部。

private Node addWaiter(Node mode) {
    //构造当前线程信息的node节点
    Node node = new Node(Thread.currentThread(), mode);
    // Try the fast path of enq; backup to full enq on failure
    Node pred = tail;
    //如果tail节点(尾节点)不为空
    if (pred != null) {
        //设置当前节点的pre指向尾节点
        node.prev = pred;
        //并设置当前节点为tail节点(尾节点)
        if (compareAndSetTail(pred, node)) {
            //设置之前尾节点的next指向当前节点
            pred.next = node;
            return node;
        }
    }
    //tail节点为null或放入同步队列的尾部失败的情况下
    enq(node);
    return node;
}
其中enq方法是通过自旋的方式不断的尝试插入队列尾部,直到成功。
private Node enq(final Node node) {
    for (;;) {
        Node t = tail;
        //如果tail节点为null,则构造一个新的node节点充当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;
            }
        }
    }
}

接下来会执行到acquireQueued方法,该方法就是线程被唤醒或获取锁失败阻塞的地方。

final boolean acquireQueued(final Node node, int arg) {
    boolean failed = true;
    try {
        boolean interrupted = false;
        for (;;) {
            final Node p = node.predecessor();
            //1、判断当前节点的前一个节点是否就是头节点
            //2、再前一个节点就是头节点的情况下尝试CAS获取锁
            if (p == head && tryAcquire(arg)) {
                //设置当前节点为head节点
                setHead(node);
                p.next = null; // help GC
                failed = false;
                return interrupted;
            }
            //1、判断当前线程是否需要被阻塞
            //2、阻塞当前线程,并设置中断标识
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        //出现异常的情况下,取消获取同步状态
        if (failed)
            cancelAcquire(node);
    }
}

下面来看看关键的阻塞方法shouldParkAfterFailedAcquire和parkAndCheckInterrupt

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;
}
/**
 * Convenience method to park and then check if interrupted
 *
 * @return {@code true} if interrupted
 */
private final boolean parkAndCheckInterrupt() {
    //阻塞当前线程
    LockSupport.park(this);
    //返回当前线程的中断标识
    return Thread.interrupted();
}

至此lock的解析大部分完成,接下来看下释放锁unlock。

public void unlock() {
    sync.release(1);
}
/**
 * Releases in exclusive mode.  Implemented by unblocking one or
 * more threads if {@link #tryRelease} returns true.
 * This method can be used to implement method {@link Lock#unlock}.
 *
 * @param arg the release argument.  This value is conveyed to
 *        {@link #tryRelease} but is otherwise uninterpreted and
 *        can represent anything you like.
 * @return the value returned from {@link #tryRelease}
 */
public final boolean release(int arg) {
    //释放同步状态
    if (tryRelease(arg)) {
        Node h = head;
        //如果头节点不为空且状态为正常
        if (h != null && h.waitStatus != 0)
            //唤醒下一个节点
            unparkSuccessor(h);
        return true;
    }
    return false;
}

先来看看tryRelease方法。tryRelease方法是由子类Sync实现。

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;
        //设置获取锁的线程为null
        setExclusiveOwnerThread(null);
    }
    setState(c);
    return free;
}
最后看下唤醒下一个节点的方法。
/**
 * Wakes up node's successor, if one exists.
 *
 * @param node the 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;
    //如果下一个节点为null或者状态为超时或中断
    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;
    }
    //如果下一个节点不为null,就唤醒下一个节点的线程
    if (s != null)
        LockSupport.unpark(s.thread);
}











评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值