AbstractQueuedSynchronizer 源码解析

203 阅读3分钟

核心属性

    //状态
    private volatile int state;
    
    //队列头结点
    private transient volatile Node head;

    //队列尾节点
    private transient volatile Node tail;

acquire方法

1.先尝试获取锁,如果成功就直接执行
2.获取锁失败,将当前线程加入到AQS队列中
3.自旋 判断是否是第一个节点,如果是再尝试获取锁,否则会阻塞

    public final void acquireInterruptibly(int arg)
            throws InterruptedException {
        //查看中断标志位,如果中断直接抛出异常
        if (Thread.interrupted())
            throw new InterruptedException();
        //先尝试获取锁,如果没有成功则调用doAcquireInterruptibly
        //尝试获取锁的方法没有默认实现
        if (!tryAcquire(arg))
            doAcquireInterruptibly(arg);
    }
    
 private void doAcquireInterruptibly(int arg)
        throws InterruptedException {
        //Node.EXCLUSIVE表示排他节点,把当前线程加入队列当中
        final Node node = addWaiter(Node.EXCLUSIVE);
        boolean failed = true;
        try {
            for (;;) {
                //获取前驱节点
                final Node p = node.predecessor();
                //前驱节点为头结点表示自己是队列中的第一个节点,如果前驱为头结点并且可尝试拿锁成功
                if (p == head && tryAcquire(arg)) {
                    //把头结点改为自己,表示自己已经出了队列
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return;
                }
                
                //调用LockSupport.park阻塞当前线程
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
    
    //节点加入队尾
    private Node addWaiter(Node mode) {
        //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
                //新建一个头结点作为head
                if (compareAndSetHead(new Node()))
                //头尾指向同一个节点
                    tail = head;
            } else {
                //插入队尾
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }

release方法

1.先尝试调用tryRelease方法,如果失败直接返回false
2.成功后获取头结点,唤醒第一个节点对应的线程

public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }
    
    private void unparkSuccessor(Node node) {
        int ws = node.waitStatus;
        //waitStatus<0说明状态不是是CANCELED
        if (ws < 0)
        //cas把头节点的ws更新为0
            compareAndSetWaitStatus(node, ws, 0);
        //获取第一个节点
        Node s = node.next;
        //如果后面没有及诶点或者状态为已取消
        if (s == null || s.waitStatus > 0) {
            s = null;
            //从尾节点开始,找到状态不为null的节点
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        //调用LockSupport.unpark来唤醒头结点的线程
        if (s != null)
            LockSupport.unpark(s.thread);
    }

acquireShared方法

1、尝试执行tryAcquireShared如果成功就直接返回 2、

    public final void acquireShared(int arg) {
        if (tryAcquireShared(arg) < 0)
            doAcquireShared(arg);
    }
    
    private void doAcquireShared(int arg) {
        //新建共享节点加入队列
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                //判断是否为头结点
                final Node p = node.predecessor();
                if (p == head) {
                    //如果是第一个节点先尝试获取tryAcquireShared
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        //头节点获取锁成功后调用setHeadAndPropagate方法
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        if (interrupted)
                            selfInterrupt();
                        failed = false;
                        return;
                    }
                }
                //不是头结点的话阻塞,线程进入waiting状态
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
    
    private void setHeadAndPropagate(Node node, int propagate) {
        Node h = head; // Record old head for check below
        //把当前节点设置为头结点
        setHead(node);

        //这里判断头结点的ws是否小于0,或者tryAcquireShared的结果大于0
        if (propagate > 0 || h == null || h.waitStatus < 0 ||
            (h = head) == null || h.waitStatus < 0) {
            Node s = node.next;
            //下一个节点也是共享节点执行doReleaseShared方法
            if (s == null || s.isShared())
                doReleaseShared();
        }
    }
    
    //唤醒后续节点
    
    //这个方法就一个目的,就是把当前结点设置为SIGNAL或者PROPAGATE,如果当前结点不是头结点也不是尾结点,先判断当前结点的状态位是否为SIGNAL,如果是就设置为0,因为共享模式下更多使用PROPAGATE来传播,SIGNAL会被经过两步改为PROPAGATE
        private void doReleaseShared() {
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    //
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }

releaseShared方法

    public final boolean releaseShared(int arg) {
        //尝试执行tryReleaseShared,成功后执行doReleaseShared
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }