一篇文章搞懂AQS!!!(持续更新)

AQS的核心思想

如果当前共享资源是空闲的,那么便会将请求资源的这个线程设为工作线程,并把资源的状态设置为锁定状态;如果资源正在被占用,那么就将请求的线程加入到工作队列(CLH队列中),等待唤醒。

CLH队列结构

CLH队列通常用于spinLock,也就是自旋锁。 

CLH队列中每一个节点都是一个AQS.Node。

AQS.Node类

    static final class Node {
        // 用于指示当前节点在共享模式下阻塞,等待执行 (Marker to indicate a node is waiting in shared mode)
        static final Node SHARED = new Node();
        // 用于指示当前节点在独占模式下阻塞,等待执行
        static final Node EXCLUSIVE = null;

        // 表示Node包含的线程已经被取消了调度,状态永远不会再被改变
        static final int CANCELLED =  1;

        // Node的【后继节点】处于或即将处于阻塞状态,当前Node在执行后,需要对后继节点执行unpark操作来唤醒后继节点。也就是说,后继节点是在等待当前的节点来唤醒它的(节点入队时,会将前继节点的waitStatus设定为SIGNAL)
        static final int SIGNAL    = -1;

        // 表明该Node节点在条件队列当中,当其它线程调用了Condition的signal方法之后,当前节点会从等待队列转移到同步队列,等待着获取同步锁。
        static final int CONDITION = -2;

        // 表明releaseShared应该传播到其它节点。 在doReleaseShared中对此进行了设置(仅适用于头节点),以确保传播继续进行,即使此后进行了其他操作(官方文档直接翻译来的)。
        // 也就是说,共享模式下,当前节点被唤醒时,会唤醒后面的所有的共享节点。
        static final int PROPAGATE = -3;
        
        // 取值为 CANCELLED、SIGNAL、CONDITION或PROPAGATE
        // 如果不是以上几种,则设定为0
        volatile int waitStatus;
        
        // 指向在CLH队列中的前、后节点
        volatile Node prev;
        volatile Node next;

        // Node代表的线程
        volatile Thread thread;

        // 链接到下一个条件节点,或者具有特殊值SHARED的节点
        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() {    // Used to establish initial head or SHARED marker
        }

        Node(Thread thread, Node mode) {     // Used by addWaiter
            this.nextWaiter = mode;
            this.thread = thread;
        }

        Node(Thread thread, int waitStatus) { // Used by Condition
            this.waitStatus = waitStatus;
            this.thread = thread;
        }
    }

AQS类的一些重要的字段

private volatile int state:同步状态(The synchronization state)(Exclusive和Share两种状态,分别来表明是独占的,还是共享的)

private transient volatile Node head:指向CLH队列的头节点

private transient volatile Node tail:指向CLH队列的尾节点


部分方法预览

private Node enq(final Node node):将Node插入CLH队列

private Node addWaiter(Node mode):为当前线程创建指定mode(Node.EXCLUSIVE 或 Node.SHARED)的Node,并加入CLH队列(Creates and enqueues node for current thread and given mode)

private void unparkSuccessor(Node node):唤醒node的后继节点

private void doReleaseShared():shared mode下的释放操作

private void cancelAcquire(Node node):取消正在执行acquire的操作

private static boolean shouldParkAfterFailedAcquire(Node pred, Node node):检查并且更新 执行acquire操作 失败的node的status

protected boolean tryAcquire(int arg) :排它模式exclusive下使用,尝试在排它模式下获取共享资源

protected boolean tryRelease(int arg):在exclusive模式下,尝试执行release共享资源操作

protected int tryAcquireShared(int arg):在shared模式下,尝试执行acquire共享资源操作

protected boolean tryReleaseShared(int arg):在shared模式下,尝试执行release共享资源操作

protected boolean isHeldExclusively():判断一个线程是否正在独占资源,括号后面的异常表明只能用于用到condition的情况(UnsupportedOperationException if conditions are not supported)

public final void acquire(int arg) :exclusive模式下获取共享资源,ignoring interrupts

public final void acquireInterruptibly(int arg):exclusive模式下获取共享资源,但是会aborting if interrupted

public final boolean release(int arg):exclusive模式下的释放操作

public final void acquireShared(int arg):shared模式下的获取操作,ignoring interrupts

public final void acquireSharedInterruptibly(int arg):shared模式下的获取操作,但是会aborting if interrupted

public final boolean releaseShared(int arg) :shared模式下的释放操作

public final boolean isQueued(Thread thread):判断一个线程是否已经在CLH队列中

public final Collection<Thread> getQueuedThreads():获取队列中的所有的等待线程

public final Collection<Thread> getExclusiveQueuedThreads() :获取队列中所有的exclusive模式下的等待线程

public final Collection<Thread> getSharedQueuedThreads():获取队列中所有的shared模式下的等待线程

final boolean transferForSignal(Node node):将一个Node从condition队列转到同步队列中


一些源码

Node入CLH队列:该方法采用了自旋操作

将Node加入CLH队列的时候,如果未进行初始化,则需要进行初始化。如果已初始化,则将Node接到CLH队列的尾部,并将tail指针指向当前加入的Node。返回的是插入的节点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;
                }
            }
        }
}

enq方法中涉及到两个采用CAS机制的方法,compareAndSetHead和compareAndSetTail

    /**
     * CAS head field. Used only by enq.
     */
    private final boolean compareAndSetHead(Node update) {
        return unsafe.compareAndSwapObject(this, headOffset, null, update);
    }

    /**
     * CAS tail field. Used only by enq.
     */
    private final boolean compareAndSetTail(Node expect, Node update) {
        return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
    }

AQS.addWaiter:以SHARED或EXCLUSIVE模式为当前线程创建节点,并加入 CLH 队列

在加入的时候,先假定CLH并未等待执行的任务。若无,通过CAS保证添加到CLH尾部,否则调用enq方法加入。

    private Node addWaiter(Node mode) {
        // 以特定模式为当前线程创建CLH节点
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail;
        
        // CLH 中包含其它节点时
        if (pred != null) {
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        // CLH中不包含其它节点,
        enq(node);
        return node;
    }

AQS.unparkSuccessor:唤醒node的后继节点(如果存在)

    private void unparkSuccessor(Node node) {
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);
        
        Node s = node.next;

        // 如果后继节点为null或者后继节点的执行为CANCELLED状态
        // 则从 CLH 尾部向前遍历,找到一个可以唤醒的前继节点
        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);
    }

    
    // CAS next field of a node.
    private static final boolean compareAndSetWaitStatus(Node node,
                                                         int expect,
                                                         int update) {
        return unsafe.compareAndSwapInt(node, waitStatusOffset,
                                        expect, update);
    }

AQS.doReleaseShared

Release action for shared mode -- signals successor and ensures propagation. (Note: For exclusive mode, release just amounts to calling unparkSuccessor of head if it needs signal.) 

共享模式下的释放操作,作用在于唤醒后继节点的线程。 

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

AQS.acquireQueued

Acquires in exclusive uninterruptible mode for thread already in queue. Used by condition wait methods as well as acquire.

以独占不间断模式获取已在队列中的线程。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的Coder*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值