AQS源码分析

AbstractQueueSynchronizer简称AQS(抽象的队列同步器),是重量级基础框架以及JUC体系的基石,主要用于解决锁分配给谁的问题。

AQS入门级理论知识

整体就是一个抽象的FIFO队列来完成线程获取资源排队的工作,并通过一个int类变量(state)表示持有锁的状态。

ReentrantLock、CountDownLatch、ReentrantReadWriteLock、Semaphore底层都是调用的AQS。

Node

AQS中含有静态内部类Node用来存储阻塞线程信息,头尾指针,以及state持有锁状态。使用双向链表实现FIFO队列。

    static final class Node {
        // 共享锁
        static final Node SHARED = new Node();

        // 独占锁
        static final Node EXCLUSIVE = null;

        // 线程获取锁的请求被取消了
        static final int CANCELLED =  1;

        // 线程已经准备好了就等着资源释放
        static final int SIGNAL    = -1;

        // condition等待唤醒
        static final int CONDITION = -2;

        // 共享式同步状态获取将会无条件传播下去
        static final int PROPAGATE = -3;

        // 初始为0,当前节点在队列中的状态
        volatile int waitStatus;

        volatile Node prev;

        volatile Node next;

        volatile Thread thread;

        // 指向下一个处于condition状态的节点
        Node nextWaiter;

        final boolean isShared() {
            return nextWaiter == SHARED;
        }

        final Node predecessor() throws NullPointerException {
            Node p = prev;
            if (p == null)
                throw new NullPointerException();
            else
                return p;
        }

        Node() {
        }

        Node(Thread thread, Node mode) {
            this.nextWaiter = mode;
            this.thread = thread;
        }

        Node(Thread thread, int waitStatus) {
            this.waitStatus = waitStatus;
            this.thread = thread;
        }
    }

ReentrantLock与AQS

ReentrantLock实现了Lock、Serializable接口,ReentrantLock含有静态内部类Sync、FairSync、NofairSync,其中公平锁(FairSync)与非公平锁(NofairSync)都继承了Sync,而Sync继承了AbstractQueueSynchronizer(AQS)类。

创建对象时参数决定是否使用公平锁:


    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

        final void lock() {
            acquire(1);
        }

        /**
         * 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) {
                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区别:公平锁的tryAcquire有 hasQueuedPredecessors 方法,

 -  返回true则有一个线程在当之前线程之前排队,返回后不枪锁

 -  返回false则当前线程为第一个或者队列为空,返回后枪锁

    public final boolean hasQueuedPredecessors() {
        // The correctness of this depends on head being initialized
        // before tail and on head.next being accurate if the current
        // thread is first in queue.
        Node t = tail; // Read fields in reverse initialization order
        Node h = head;
        Node s;
        return h != t &&
            ((s = h.next) == null || s.thread != Thread.currentThread());
    }

AQS源码入队、出队解读

1、lock

从lock方法进入,走公平锁 NoFairSync

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

NoFairSync中的lock方法会先尝试抢占锁(compareAndSetState(0, 1)比较并交换锁的状态,setExclusiveOwnerThread(Thread.currentThread())设置锁的占有者为当前线程),若抢占失败才回去执行acquire(AQS中)方法

    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;


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

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

2、AQS中的acquire

tryAcquire:尝试抢占锁,抢占成功返回true,取反为false,则不会执行接下来的代码

addWaiter(Node.EXCLUSIVE):加入到等待队列(独占锁)

acquireQueued:

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

tryAcquire

AQS中的tryAcquire调用的是 非公平锁中的tryAcquire

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }

 c 为当前锁的占有状态,0为空闲,大于0则被占有。

 - 如果锁未被持有:尝试获取锁(比较并交换,设置当前线程为锁的占有者),成功返回true

 - 如果锁已经被使用:else if 语句是重入锁的代码,判断持有锁的线程是否为当前线程,若不是直接返回false;若是,则会更新所得状态(state + 1)

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

addWaiter

参数是 null(Node.EXCLUSIVE 独占锁),传入当前线程new了一个新节点Node,若是第一次尝试获取锁(即队列未初始化,为空),则prev、tail节点都是null,则会进入enq方法,执行强制初始化。

注意初始化时new了一个虚拟节点(头尾指针指向虚拟节点),然后再将上一步创建的线程节点与虚拟节点之间建立连接。这里compareAndSetHead、compareAndSetTail都是调用的unSafe类中定义的native方法。

之后进队只是Node建立连接、重设尾节点

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

acquireQueued

参数:new的当前线程节点,想要设置当前锁的状态 1。

设置中断标识位(interrupted)为false,node.predecessor()获取当前节点的上一个节点p,

第一个if:判断p是不是头节点(第一次进入head、p都为虚拟节点),若是头节点则再次执行tryAcquire尝试抢占锁。

第二个if:尝试枪锁失败后执行等待。

第一次进入 shouldParkAfterFailedAcquire (即p为虚拟节点,waitStatus为0),将waitStatus 设置为SIGNAL(-1)并会返回false,再次进入循环。

第二次进入 shouldParkAfterFailedAcquire 则返回true,执行等待并检查中断状态parkAndCheckInterrupt ,这个方法使用的 LockSupport.park(this)执行等待,被唤醒后返回线程的中断状态。

值得注意的是:所有的节点在shouldParkAfterFailedAcquire 中都会把前置节点waitStatus设置为-1  compareAndSetWaitStatus(pred, ws, Node.SIGNAL)。占有锁的线程不释放锁,所有的节点都会在LockSupport.park(this)执行等待,除了异常情况(被中断等)

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

    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;
        if (ws == Node.SIGNAL)
            return true;
        if (ws > 0) {
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }

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

unlock(释放锁以即之后的流程)

lock.unlock()调用release(AQS),尝试释放锁 tryRelease ,c 为锁的状态state - 1,会判断解锁的线程与枷锁的线程是否一致。

如果 c == 0,则会释放锁(将绑定锁的线程设置为null,设置state为0),返回true;

如果c != 0,释放锁失败,返回false

头节点head不为null,且后面右节点在执行等待的话,那么head的waitStatus为 -1,进入unparkSuccessor ,通过CAS自旋设置头节点的 waitStatus 为0

第一个if:进入(头节点的next节点存在且next的waitStatus > 0),waitStatus > 0是指获取锁的请求被取消了,则会从尾节点向前找,找到第一个节点的waitStatus <= 0的,然后由下一个if唤醒。

第二个if:唤醒next节点,尝试枪锁

    public void unlock() {
        sync.release(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;
    }

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


    private void unparkSuccessor(Node node) {

        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);

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

唤醒后枪锁

正常情况下被唤醒,返回线程是否被中断false,退回到acquireQueued方法进行下一次循环,执行tryAcquire抢占锁,因为锁的状态state为0,所以会进入CAS自选枪锁。

枪锁成功返回true,之后会将头节点指向当前节点,当前节点中线程为null,断开与之前的头节点p之间的引用指向(便于gc),然后返回false。若异常中断则会在返回之前执行finally中的cancelAcquire。

为什么这里只有一个出队也要使用tryAcquire尝试枪锁呢?可能会有没进入队列的线程抢占锁,所以要争抢。

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

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

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

    final boolean nonfairTryAcquire(int acquires) {
        final Thread current = Thread.currentThread();
        int c = getState();
        if (c == 0) {
            if (compareAndSetState(0, acquires)) {
                setExclusiveOwnerThread(current);
                return true;
            }
        }
            ...

cancelAcquire(从队列中移出)

当异常中断执行此方法,分取消排队的node节点位置

 - node节点在队尾,如果前面的Node也要移出(通过waitStatus > 0),循环找出最左边要移出的节点的左节点pred(此节点不移出),preNext即为第一个要移除的节点,给参数Node的waitStatus重新赋值1,因为此节点是尾节点,所以进入第一个if,重设尾节点为pred,然后把尾节点next引用指向null。

 - node节点在队中间,一样通过循环出最左边要移出的节点的左节点pred(此节点不移出),只不过进入else,移出中间的部分节点操作后,将两端的节点重新指向(建立联系),移出的节点移出指针指向,便于GC。

    private void cancelAcquire(Node node) {
        if (node == null)
            return;

        node.thread = null;
        
        Node pred = node.prev;
        while (pred.waitStatus > 0)
            node.prev = pred = pred.prev;
        
        Node predNext = pred.next;
        
        node.waitStatus = Node.CANCELLED;

        if (node == tail && compareAndSetTail(node, pred)) {
            compareAndSetNext(pred, predNext, null);
        } else {
            int ws;
            if (pred != head &&
                    ((ws = pred.waitStatus) == Node.SIGNAL ||
                     (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
                    pred.thread != null) {
                Node next = node.next;
                if (next != null && next.waitStatus <= 0)
                    compareAndSetNext(pred, predNext, next);
            } else {
                unparkSuccessor(node);
            }

            node.next = node; // help GC
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值