zoukankan      html  css  js  c++  java
  • AQS源码解析

    JAVA的众多锁的机制,包括Semaphore/ReentrantLock/ReentrantReadWriteLock等都是通过 AQS实现的,因为写了上述几个锁实现的源码分析,经常使用到AQS的原理和代码,因此这里做下AQS的源码分析。这样之后再翻看以AQS为基础的各种各样的锁实现就会好理解的多了。

    基本思想:

    我们结合着源码文件中的注释来看下。

    源代码英文注释:

    /**
     * Provides a framework for implementing blocking locks and related
     * synchronizers (semaphores, events, etc) that rely on
     * first-in-first-out (FIFO) wait queues.  This class is designed to
     * be a useful basis for most kinds of synchronizers that rely on a
     * single atomic {@code int} value to represent state. Subclasses
     * must define the protected methods that change this state, and which
     * define what that state means in terms of this object being acquired
     * or released.  Given these, the other methods in this class carry
     * out all queuing and blocking mechanics. Subclasses can maintain
     * other state fields, but only the atomically updated {@code int}
     * value manipulated using methods {@link #getState}, {@link
     * #setState} and {@link #compareAndSetState} is tracked with respect
     * to synchronization.
     */

    提供一个依赖FIFO等待队列来实现阻塞锁和关联同步机制(信号量、事件等)的框架。该类被作为多数类型的同步机制的一个实用的基础,设计依赖一个atomic类型的int数据来代表一个状态。子类必须实现其protected类型的方法来改变这个状态,这个状态意味着对象被请求或者释放的一个说明。提供了这些,本类的其他方法都用来执行所有的队列和阻塞结构。子类可以维护其他的字段,但只有state状态的原子更新操作通过#getState, #setState, #compareAndSetState 被追踪来实现同步。

    AQS的这段类文件中最开始的注释,解释了AQS类的意义和实现手段。

    通过一个先进先出的队列和一个内存可见的int类型状态,来提供一个队列的阻塞结构,作为众多同步机制(Semaphore/ReentrantLock等)的基础算法结构。

    源代码英文注释:

    <p>This class supports either or both a default <em>exclusive</em>
     * mode and a <em>shared</em> mode. When acquired in exclusive mode,
     * attempted acquires by other threads cannot succeed. Shared mode
     * acquires by multiple threads may (but need not) succeed. This class
     * does not &quot;understand&quot; these differences except in the
     * mechanical sense that when a shared mode acquire succeeds, the next
     * waiting thread (if one exists) must also determine whether it can
     * acquire as well. Threads waiting in the different modes share the
     * same FIFO queue. Usually, implementation subclasses support only
     * one of these modes, but both can come into play for example in a
     * {@link ReadWriteLock}. Subclasses that support only exclusive or
     * only shared modes need not define the methods supporting the unused mode.

    AQS类支持两种模式,独占模式和分享模式,默认是独占模式。独占模式时,除了当前占用线程外,其他的线程的尝试请求将失败。共享模式下,多个线程的请求将会成功。这个类不能“理解”这种不同,除了这样一种机械的功能,那就是当一个共享模式的请求成功时,另一个等待线程(如果存在的话)必须决定它是否能够请求。不同类型的线程等待使用的是同样的FIFO队列。一般来说,子类只需要实现其中的一种模式,共享or排它。但也可以一起生效比如ReadWriteLock。只支持一种模式的子类不需要定义另一种不支持的模式的方法。

    了解了基础的概括,我们来深入代码查看具体实现。

    根据上文的描述,我们知道AQS的核心是一个先进先出的队列,那么队列是如何表示的呢?翻阅代码就能知道,是一个Node的类结构来表示队列中的节点的。OK我们来看节点:

    核心构成:节点

    static final class Node {
            /** Marker to indicate a node is waiting in shared mode 标记用来标明一个分享模式的节点 */
            static final Node SHARED = new Node();
            /** Marker to indicate a node is waiting in exclusive mode 标记用来标明一个排他模式的节点 */
            static final Node EXCLUSIVE = null;
    
            /** waitStatus value to indicate thread has cancelled */
            static final int CANCELLED =  1; // 表明线程被关闭的状态
            /** waitStatus value to indicate successor's thread needs unparking */
            static final int SIGNAL    = -1; // 表明线程等待被唤醒的状态
            /** waitStatus value to indicate thread is waiting on condition */
            static final int CONDITION = -2; // 表明线程再等待condition条件的状态
            /**
             * waitStatus value to indicate the next acquireShared should
             * unconditionally propagate
             */
            static final int PROPAGATE = -3; // 表明下一个acquireShared会无条件的传递
    
            // 等待状态(值为上述几种状态CANCELLED、SINGAL、CONDITION、PROPAGATE)
            volatile int waitStatus;
    
            // 前一个节点
            volatile Node prev;
    
            // 后一个节点
            volatile Node next;
    
            // 线程引用
            volatile Thread thread;
    
            // 下一个等待者 (连接下一个等待条件者,或者是特殊的值Shared。因为条件队列的访问必须是独享模式,所以我们只能维护一个简单的队列来保存那些等待条件的node。他们之后会被
            排列去重新请求。如果不是条件等待者,那么就用一个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的代码里,除了以上的Node定义外,还有几个字段

    核心字段:

    private transient volatile Node head;
    
        /**
         * Tail of the wait queue, lazily initialized.  Modified only via
         * method enq to add new wait node.
         */
        private transient volatile Node tail;
    
        /**
         * The synchronization state.
         */
        private volatile int state;

    head 、tail 表示一个队列的头尾,state前文已经提过。剩下的就是方法了,我们来分析下AQS代码里的方法。

    方法解析:

    // 添加等待者,根据传入参数
    private
    Node addWaiter(Node mode) { // 创建节点,参数是当前线程对象和上文中体到的独占or分享模式 Node node = new Node(Thread.currentThread(), mode); // Try the fast path of enq; backup to full enq on failure // 尝试最快的路径加入队列,如果失败则退回执行enq方法 Node pred = tail; if (pred != null) { // if条件里的操作,就是将新创建的node节点,加入到队列的最后,如果成功那么跟前边链接起来pred.next = node,如果失败,则继续执行后续enq(node)代码 node.prev = pred; if (compareAndSetTail(pred, node)) { pred.next = node; return node; } } // 如果compareAndSetTail(pred, node)失败,也即多个线程争抢,那么失败的就只能乖乖的往后走了 enq(node); return node; }
    // enq 将参数node设置为tail并连接入队列中,自旋操作直至成功才退出
    private Node enq(final Node node) { for (;;) { Node t = tail; if (t == null) { // Must initialize
    // t==null 也就是说队列中,还是空,那么这时候就执行初始化的操作:创建空节点并设置为head = tail = new Node()
    if (compareAndSetHead(new Node())) tail = head; } else {
    // 经过上述初始化,或者执行到这里时队列本身就不为空,那么这里执行的其实是addWaiter里边的代码,即:将当前node加入到队列的最末尾,并设置为tail node.prev
    = t; if (compareAndSetTail(t, node)) { t.next = node; return t; } } } }
  • 相关阅读:
    解决多版本sdk兼容问题
    ios5 UIKit新特性
    iPhone网络编程–一起来做网站客户端(一)
    八数码
    IOS开发中编码转换
    修复ipa图片png方法
    创建易读链接 搭建应用通往App Store的桥梁
    如何让IOS应用从容地崩溃
    详解IOS IAP
    jquery创建并行对象或者叫合并对象
  • 原文地址:https://www.cnblogs.com/aquariusm/p/9728567.html
Copyright © 2011-2022 走看看