ReentrantLock.FairSync的unlock方法源码笔记

ReentrantLock通过unlock方法调用公平锁的unlock方法

  public final boolean release(int arg) {
        //尝试释放锁,如果释放成功,则status置为了0,exclusiveOwnerThread置为了null
        if (tryRelease(arg)) {
            Node h = head;
            //持有锁的线程释放锁后,需要叫醒在队列中等待的线程,如果头节点不为空,且状态不为0,进行unpark
            //头结点为空的话,说明队列是空的,没有线程要叫醒,而之所以要waitStatus不为0才unpark,是因为waitStatus=0时,表明head就是队列里的最后一个节点,没有需要唤醒的线程了(如果它后面还有等待线程,则它的waitStatus=-1)。
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }
protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            //如果不是当前线程持有锁,没有资格释放锁,抛错
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            //如果status-1=0,可以释放锁
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            //更新status
            //释放锁,更新为0
            //重入锁释放一次锁,更新为status-1
            setState(c);
            return free;
        }
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;
        //将头节点的waitStatus更新为0
        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;
            //一般情况下,待唤醒线程是下一个节点,但如果下一个节点线程被中断取消或者是null,就不是要被唤醒线程
            //从后往前遍历的原因是:在加锁的入队操作里,先通过CAS设置了tail,如果在设置完tail后线程切换,则tail.pre是有节点的,但tail.pre.next=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);
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值