juc:AQS

简介

一般说AQS,都是指AbstractQueuedSynchronizer这个类,字面意思:抽象的队列同步器

juc:AQS

AQS是用来构建锁或者其它同步器组件的重量级基础框架及整个JUC体系的基石,通过内置的FIFO队列来完成资源获取线程的排队工作,并通过一个int类型变量表示持有锁的状态.

抢到资源的线程直接使用处理业务逻辑,抢不到资源的必然涉及一种排队等候机制。抢占资源失败的线程继续去等待(类似银行业务办理窗口都满了暂时没有受理窗口的顾客只能去候客区排队等候),但等候线程仍然保留获取锁的可能且获取锁流程仍在继续(候客区的顾客也在等着叫号,轮到了再去受理窗口办理业务)。

既然说到了排队等候机制,那么就一定会有某种队列形成,这样的队列是什么数据结构呢?

如果共享资源被占用,就需要一定的阻塞等待唤醒机制来保证锁分配。这个机制主要用的是CLH队列的变体实现的,将暂时获取不到锁的线程加入到队列中,这个队列就是AQS的抽象表现。它将请求共享资源的线程封装成队列的结点(Node),通过CAS、自旋以及LockSupport.park()的方式维护state变量的状态,使并发达到同步的控制效果。

juc:AQS

CLH:是一个单向链表,AQS中队列是CLH变体的虚拟双向队列FIFO

juc:AQS

AQS源码体系

AQS使用一个volatile的int类型的成员变量来表示同步状态,通过内置的FIFO队列来完成资源获取的排队工作将每条要去抢占资源的线程封装成一个Node节点来实现锁的分配,通过CAS完成对State值的修改。

juc:AQS

juc:AQS

Node类的内部结构:

    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() {    // 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同步队列的基本解构:

juc:AQS

从ReentrantLock看AQS源码

juc:AQS

由此可见ReentrantLock使用了AQS。而实际上Lock接口的实现类,基本上都是通过聚合了一个队列同步器的字类完成线程访问控制的。

通过分析,不难得出ReentrantLock和AQS的关系:

juc:AQS

juc:AQS

ReetrantLock.lock

公平锁和非公平锁:

juc:AQS

二者区别是公平锁添加了一个!hasQueuedPredecessors()判断

juc:AQS

hasQueuedPredecessors是公平锁加锁时判断等待队列中是否存在有效节点的方法

非公平锁:lock

juc:AQS

acquire( ):源码和3大流程走向

juc:AQS

tryAcquire(arg)

juc:AQS

addWaiter(Node.EXCLUSIVE)

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;
            //设置tail字段为node节点
            if (compareAndSetTail(pred, node)) {
                //原来的尾节点后续节点执行当前节点
                pred.next = node;
                return node;
            }
        }
    	//入队
        enq(node);
        return node;
    }

    private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            //第一次进来,尾节点为null
            if (t == null) { // Must initialize
                //设置头节点为哨兵节点
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }

juc:AQS

acquireQueued(final Node node, int arg)

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

	private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;
        //ws=0第一次进来,ws=-1第二次进来时,直接返回true
        if (ws == Node.SIGNAL)
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;
        if (ws > 0) {
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            /*
             * 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.
             */
            //第一次进来时,当前节点的哨兵节点的ws设置为-1
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }

    private final boolean parkAndCheckInterrupt() {
        //阻塞当前线程,等待被唤醒
        LockSupport.park(this);
        return Thread.interrupted();
    }

ReetrantLock.unlock

    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) {
        /*
         * 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;
        if (ws < 0)
        	//设置node节点的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;
        //当头节点的下一个节点为null时
        if (s == null || s.waitStatus > 0) {
            s = null;
            //遍历链表,取得当前链表中第一个部位空的节点,且不是当前node节点,且ws<0
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        if (s != null)
        	//唤醒节点,节点被唤醒后,立刻获取到锁,并出链表
            LockSupport.unpark(s.thread);
    }

juc:AQS

上一篇:让Win8自动登录免输入密码的小技巧


下一篇:VC6.0在win 8.1中的安装使用