阅读 104

AQS源码浅析

AQS基本结构

private transient volatile Node head;  //头节点

private transient volatile Node tail; //尾节点 , 每个新的结点进来,都插入到最后,也就形成了一个链表

//表示当前锁的状态  0 表示没有被占用 ,大于 0 表示有线程持有了当前锁  state 的值大于1 是因为被重入了多次
private volatile int state;
阻塞队列图

阻塞队列是从head后的结点开始的,也即 不包含头节点head

哨兵结点head作用

因为AQS本身实现的目的是要在无锁操作的情况下实现一个线程安全的同步队列, 它实现线程安全就是靠这个哨兵节点把出入队操作隔离开:

  1. 如果没有哨兵节点,那么每次执行入队操作,都需要判断head是否为空,如果为空则head=new Node如果不为空则head.next=new Node,而有哨兵节点则可以大胆的head.next=new Node

  2. 如果没有哨兵节点,可能存在之前所说的安全性问题,当只有一个节点的时候执行入队方法,无法保证tail和head不为空。哪怕执行入队方法之前tail和head还指向一个节点,可能由于并发性在具体调用入队方法操作tail的时候head和tail共同指向的头节点已经完成出队,此时tailhead都为null,所以入队方法中的tail.next=new node会抛空指针异常,由于线程并发性的问题,tail始终可能随时为空的问题不使用哨兵节点是无法解决的。

Node结构

node结点的数据结构 构成 thread + waitStatus + prev + next

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;  //当前node结点的后继结点对应的线程需要被唤醒
     
        static final int CONDITION = -2;
     
        static final int PROPAGATE = -3;

      
        volatile int waitStatus;

        volatile Node prev;  //前驱结点引用

       
        volatile Node next;  //后继线程引用

        
        volatile Thread thread;  //当前线程

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

线程抢锁

ReentrantLock举例

公平锁下

//ReentrantLock 公平锁
static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

        final void lock() {
            acquire(1);
        }
    //父类AQS 实现
      public final void acquire(int arg) {  //此时arg == 1
        if (!tryAcquire(arg) &&                // tryAcquire() 再次尝试 若尝试成功则返回true  不需要进队等待
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))  // !false() && (入队)  addWaiter()将线程包装成node
            selfInterrupt();
    }

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

acquire() 分析

public final void acquire(int arg) {  
        if (!tryAcquire(arg) &&                // tryAcquire() 再次尝试 若尝试成功则返回true  不需要进队等待
            // !false() && (入队)    tryAcquire(arg)没有成功,这个时候需要把当前线程挂起,放到阻塞队列中。
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))  
            selfInterrupt();
    }

tryAcquire() 分析

//AQS 实现方式
protected boolean tryAcquire(int arg) {
        throw new UnsupportedOperationException();  //若子类没有对该方法进行覆写 , 则抛出异常
    }

//FairSync 实现方式

 //尝试获取锁 返回值boolean ,代表是否获取到锁
 //返回true:1.没有线程在等待锁;2.重入锁,线程本来就持有锁,也就可以理所当然可以直接获取
protected final boolean tryAcquire(int acquires) {  //对tryAcquire 进行覆写 且使用 `final` 进行修饰 不可被更改
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                // 虽然此时此刻锁是可以用的,但是这是公平锁,既然是公平,就得讲究先来后到,
                // 看看有没有别人在队列中等了半天了  hasQueuedPredecessors() 查看队列中是否有等待的线程
                if (!hasQueuedPredecessors() &&
                         // 如果没有线程在等待,那就用CAS尝试一下,成功了就获取到锁了,
                        // 不成功的话,只能说明一个问题,就在刚刚几乎同一时刻有个线程抢先了
                    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;
            }
            //获取锁失败   回到上层 判断acquireQueued(addWaiter(Node.EXCLUSIVE), arg)
            return false;
        }

addWaiter()和 enq()分析

// 此方法的作用是把线程包装成node,同时进入到队列中
    // 参数mode此时是Node.EXCLUSIVE,代表独占模式
 private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);  //根据当前线程 实例化一个node对象 入队
        // Try the fast path of enq; backup to full enq on failure

        //将node 结点加入到链表的最后面去 , 也即 进入阻塞队列
        Node pred = tail;
        if (pred != null) {  //此时 队尾为空
            node.prev = pred; //设置队尾node 为该元素的前驱
            if (compareAndSetTail(pred, node)) {  // cas 将自己设置为队尾 , 成功后 tail  == node
                pred.next = node;  //建立后继链接
                return node;
            }
        }
        enq(node); //此时tail == null  入队
        return node;
    }


// 采用自旋的方式入队
    // 调用enq() 方法的情况有2种 : 1. 等待队列为空, 2. 或者有线程竞争入队,
    private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            if (t == null) { // Must initialize   初始化  队列为空时
                if (compareAndSetHead(new Node()))  //构建哨兵结点 初始时 head == null
                    // 此时head节点的waitStatus==0, 看new Node()构造方法就知道了

                    // 这个时候有了head,但是tail还是null,设置一下, 暂时将tail 指向head结点 , 下一次自旋tail就会移动
                    tail = head;
            } else {
                node.prev = t;  //将当前结点入队
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
}

acquireQueued()分析

acquireQueued(addWaiter(Node.EXCLUSIVE), arg) 此时线程已经经过addWaiter()被包装成node结点,且进入了阻塞队列

  final boolean acquireQueued(final Node node, int arg) {  // 进行park
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                // p == head 说明当前节点虽然进到了阻塞队列,但是是阻塞队列的第一个,因为它的前驱是head
                //为何是第一个排队的元素就有资格进行 尝试一次  head一般指的是占有锁的线程,head后面的才称为阻塞队列
                    // 首先,①它是队头,这个是第一个条件,其次,②当前的head有可能是刚刚初始化的node,
                    // enq(node) 方法里面有提到,head是延时初始化的,而且new Node()的时候没有设置任何线程
                    // 也就是说,当前的head不属于任何一个线程,所以作为队头,可以去试一试,
                if (p == head && tryAcquire(arg)) {  // 第一个排队的人(哨兵后的第一个结点)  调用tryAcquire()自旋一次
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                //此时 要么node结点不是第一个排队的元素  要么竞争失败
//shouldParkAfterFailedAcquire 返回为true (即前驱结点 waitStutas == -1)正常调用parkAndCheckInterrupt() 将线程挂起
//                             返回为false  此时前驱结点有 非-1 cas到 - 1 ,下次自旋的时候就会返回true
                if (shouldParkAfterFailedAcquire(p, node) && 
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)   // true : 在自旋过程种出现了异常 , failed 本就被初始化 true
                cancelAcquire(node);
        }
    }

shouldParkAfterFailedAcquire()

当前线程没有抢到锁,是否需要挂起当前线程?

private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {  //pred为前驱结点  node为当前结点
        int ws = pred.waitStatus;  //前驱结点的状态信息
        if (ws == Node.SIGNAL)  //waitStatus == -1 标识前驱结点正常,需要挂起当前线程 ,直接返回true
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;
        if (ws > 0) {  
            //waitStatus > 0 说明前驱结点取消了排队 ,需要为当前结点顺延找到一个 排队的结点(也即 waitStatus == - 1)
            //进入阻塞队列排队的线程会被挂起,而唤醒的操作是由前驱节点完成的。
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {  //此时waitStatus不为 - 1 和 1  可能的值为 0,-2,-3
            /*
             * 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);  //将前驱结点的waitStatus 设置为 -1 ,便于后续唤醒node
        }
    
           // 这个方法返回 false,那么会在外部自旋一次, 再走一次 for 循序,
        //     然后再次进来此方法,此时会从第一个分支返回 true
        return false;
    }

线程解锁

同样以ReentrantLock举例

release()分析

 public void unlock() {  // 解锁方式直接为ReentrantLock 方法
        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;
    }
//AQS 实现方式
protected boolean tryRelease(int arg) {
        throw new UnsupportedOperationException();
    }

//ReentrantLock 实现方式(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;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }

unparkSuccessor()分析

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;  //node 为头节点
        if (ws < 0)   //头节点waitStatus < 0
            compareAndSetWaitStatus(node, ws, 0);     // 如果head节点当前waitStatus<0, 将其修改为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.
         */

       //从队尾往前找,找到waitStatus<=0的所有节点中排在最前面的  不直接从对头找 可能后继结点取消了排队 (waitStutas == 1)
        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);
    }

唤醒后

线程本来在acquireQueued()中的parkAndCheckInterrupt()被挂起,继续执行

private final boolean parkAndCheckInterrupt() {
    LockSupport.park(this); // 刚刚线程被挂起在这里了
    return Thread.interrupted();
}

回到竞争锁流程中,acquireQueued(final Node node, int arg),这个时候,node的前驱是head了

AQS获取锁和释放锁流程图

aqs获取和释放锁流程图

总结:

AQS的实现是围绕这自旋、park--unpark、cas来进行实现的。
AQS的加锁和解锁需要三个部件协调:

  • 锁状态 state :需要知道当前锁是否被占有了

  • 线程的阻塞和解除阻塞 : AQS中采用 LockSupport.park(thread) 来挂起线程,用 unpark 来唤醒线程

  • 阻塞队列 : 因为争抢锁的线程可能很多,但是只能有一个线程拿到锁,其他的线程都必须等待,这个时候就需要一个 queue 来管理这些线程,AQS 用的是一个 FIFO 的队列,就是一个链表,每个 node 都持有后继节点的引用

作者:wxxhfg

原文链接:https://www.jianshu.com/p/26269ca2162f

文章分类
后端
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐