随笔分类
AQS
一般称为队列同步器
AQS是用来构建锁和其他同步组件的基础框架,其也是Java三大并发工具(CountDownLatch、CyclicBarrier、Semaphore)的基础,可见其重要性.
通过AQS可以来实现公平锁
AQS的设计与实现中实际上是体现了模板模式
的
java.util.concurrent.locks
AbstractQueuedSynchronizer,队列同步器
/**
* Provides a framework for implementing blocking locks and related
* synchronizers (semaphores, events, etc) that rely on
* first-in-first-out (FIFO) wait queues. # 提供一个框架来实现先进先出(FIFO)等待队列的阻塞锁和相关的同步器(信号灯,事件等)
* 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.
* # 为大多数依赖单个原子int值表示状态的同步器提供有用的基础(即:通过提供一个原子int来表示锁的状态),该状态用于表示锁是独占中合适已释放,通过指定的方法来修改锁的状态,并定义此状态对于获取或释放此对象意味着什么.
* 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.
* # 子类可以来维护其它的状态字段,但是相对于同步,仅跟踪使用方法 getState、setState、compareAndSetState操作的原子更新的int值
* <p>Subclasses should be defined as non-public internal helper
* classes that are used to implement the synchronization properties
* of their enclosing class. Class
* {@code AbstractQueuedSynchronizer} does not implement any
* synchronization interface. Instead it defines methods such as
* {@link #acquireInterruptibly} that can be invoked as
* appropriate by concrete locks and related synchronizers to
* implement their public methods.
* # 子类一般使用内部类来实现需要同步的工作
* <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 "understand" 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.
* # 这个类提供了两种模式,独占和共享. 以独占方式获取成功时,其它线程尝试获取会失败. 由多个线程获取的共享模式可能(但不一定)成功. 通常,实现子类仅支持这些模式之一,但是ReadWriteLock两种模式都支持(即:读共享,写互斥,写时不一定能读(除非是以副本的方式进行写)).
* <p>This class defines a nested {@link ConditionObject} class that
* can be used as a {@link Condition} implementation by subclasses
* supporting exclusive mode for which method {@link
* #isHeldExclusively} reports whether synchronization is exclusively
* held with respect to the current thread, method {@link #release}
* invoked with the current {@link #getState} value fully releases
* this object, and {@link #acquire}, given this saved state value,
* eventually restores this object to its previous acquired state. No
* {@code AbstractQueuedSynchronizer} method otherwise creates such a
* condition, so if this constraint cannot be met, do not use it. The
* behavior of {@link ConditionObject} depends of course on the
* semantics of its synchronizer implementation.
* # 这个类定义了ConditionObject内部类,提供方法进行一系列的操作
* <p>This class provides inspection, instrumentation, and monitoring
* methods for the internal queue, as well as similar methods for
* condition objects. These can be exported as desired into classes
* using an {@code AbstractQueuedSynchronizer} for their
* synchronization mechanics.
* # 此类提供了内部队列的检查,监测和监视方法,以及条件对象的类似方法. 可以根据需要使用AbstractQueuedSynchronizer将它们导出到类中以来实现同步机制
* <p>Serialization of this class stores only the underlying atomic
* integer maintaining state, so deserialized objects have empty
* thread queues. Typical subclasses requiring serializability will
* define a {@code readObject} method that restores this to a known
* initial state upon deserialization.
* # 序列化相关:子类一般需要定义realObject方法;来记住已经初始化的记录(否则反序列化,这些状态可能会丢失)
* <h3>Usage</h3>
*
* <p>To use this class as the basis of a synchronizer, redefine the
* following methods, as applicable, by inspecting and/or modifying
* the synchronization state using {@link #getState}, {@link
* #setState} and/or {@link #compareAndSetState}:
*
* <ul>
* <li> {@link #tryAcquire}
* <li> {@link #tryRelease}
* <li> {@link #tryAcquireShared}
* <li> {@link #tryReleaseShared}
* <li> {@link #isHeldExclusively}
* </ul>
* # 一般使用都要去实现这些方法
..省略
* <p>This class provides an efficient and scalable basis for
* synchronization in part by specializing its range of use to
* synchronizers that can rely on {@code int} state, acquire, and
* release parameters, and an internal FIFO wait queue. When this does
* not suffice, you can build synchronizers from a lower level using
* {@link java.util.concurrent.atomic atomic} classes, your own custom
* {@link java.util.Queue} classes, and {@link LockSupport} blocking
* support.
* # 这个类提供了state、获取、释放,以及内部的队列给我们去实现同步. 如果觉得功能不够的话,可以自己去使用atomic包和Queue类来自己实现
源码解读
注释其实就是最好的解读!
重要的成员变量
AQS中主要维护了一个state
(锁状态的表示)和一个可阻塞的等待队列(CLH)
CLH
队列由链表
实现,以自旋的方式获取资源,是可阻塞的先进先出的队列. 通过自旋
和CAS
保证节点插入和移除的原子性. 当线程获取锁失败时,就加入到队列尾部.
/**
* Head of the wait queue, lazily initialized. Except for
* initialization, it is modified only via method setHead. Note:
* If head exists, its waitStatus is guaranteed not to be
* CANCELLED.
* 等待队列的头,延迟初始化. 除了初始化外,只能通过setHeader方法来进行修改.
* 如果header存在,则保证其waitStatus不为 CANCELLED.
*/
private transient volatile Node head;
/**
* Tail of the wait queue, lazily initialized. Modified only via
* method enq to add new wait node.
* 等待队列的尾部,延迟初始化. 仅通过方法 enq来添加新的等待节点
*/
private transient volatile Node tail;
/**
* The synchronization state.
*/
private volatile int state;//临界资源,锁状态的描述,保证可见性
内部类-Node
AQS的工作模式分为独占模式
和共享模式
,记录在节点的信息中
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; //释放资源后需要唤醒后续线程 --> 等待一个唤醒信号 signal
/** waitStatus value to indicate thread is waiting on condition */
static final int CONDITION = -2; //指示线程正在等待条件(等待unparking)
/**
* waitStatus value to indicate the next acquireShared should
* unconditionally propagate
*/
static final int PROPAGATE = -3; //若工作于共享锁状态,需要向后传播
/*
* The field is initialized to 0 for normal sync nodes, and
* CONDITION for condition nodes. It is modified using CAS
* (or when possible, unconditional volatile writes).
* 对于普通的同步节点,该字段初始化为0;对于条件节点,该字段初始化为 CONDITION.
* 使用CAS对其进行修改
*/
volatile int waitStatus;//等待状态,有0,1,-1,-2,-3五个值,分别对应上面的值
/**
* Link to predecessor node that current node/thread relies on
* for checking waitStatus. Assigned during enqueuing, and nulled
* out (for sake of GC) only upon dequeuing. Also, upon
* cancellation of a predecessor, we short-circuit while
* finding a non-cancelled one, which will always exist
* because the head node is never cancelled: A node becomes
* head only as a result of successful acquire. A
* cancelled thread never succeeds in acquiring, and a thread only
* cancels itself, not any other node.
*/
volatile Node prev; //前驱结点
/**
* Link to the successor node that the current node/thread
* unparks upon release. Assigned during enqueuing, adjusted
* when bypassing cancelled predecessors, and nulled out (for
* sake of GC) when dequeued. The enq operation does not
* assign next field of a predecessor until after attachment,
* so seeing a null next field does not necessarily mean that
* node is at end of queue. However, if a next field appears
* to be null, we can scan prev's from the tail to
* double-check. The next field of cancelled nodes is set to
* point to the node itself instead of null, to make life
* easier for isOnSyncQueue.
*/
volatile Node next; //后继节点
/**
* The thread that enqueued this node. Initialized on
* construction and nulled out after use.
*/
volatile Thread thread; //等待锁的线程
Node nextWaiter; //等待条件的下一个节点,ConditionObject中会用到.