理解AQS原理一之阅读注释
程序员文章站
2022-07-14 16:38:49
...
理解AQS原理一之阅读注释
自己学习使用,大神勿喷
为了深入了解AQS运行原理,先读了AbstractQueuedSynchronizer
类中大量的英文注释,并对部分进行翻译、阅读,简单理解该类的功能作用。该篇为AQS原理第一篇,主要通过阅读注释简单了解其功能。具体的源码解析会另开文章分析。此篇注释翻译,也会不断更新。
AQS类的UML图示
生成的此UML图示,带有field字段和内部类;由于方法个数较多,篇幅有限,未带有method方法,方便简洁查看。
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.
* 为实现那些依赖于先进先出等待队列的阻塞式锁和相关同步器(信号量、事件等),提供了框架。
* 设计这个类的目的是:为大多数依赖于单个原子int变量来表示状态的同步器 提供有用的基础。
* 子类必须定义那些改变state的protected方法,以及这些方法定义了该state在获取或释放该对象方面的含义。
* 鉴于此,该类中的其余方法用来执行队列和阻塞机制。
* 子类可以维持其他状态,但是只有使用getState、setState、compareAndSetState方法原子地更新int值(指代state),才能同步跟踪状态值。
*
*
* <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.
* 子类必须定义为非public内部辅助类,用于实现其封闭类的同步属性。
* AQS类未实现任何同步接口。
* 取而代之的是,它定义了诸如acquireInterruptibly的方法,具体锁和相关同步器可以根据需要调用它来实现它们的公共方法
*
* <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.
* 该类既支持默认的独占模式,又支持共享模式。
* 在独占模式中获取时,其他线程的试图获取不会成功。
* 在共享模式时,多个线程获取时可能会(但不需要)成功。
* 这个类不“理解”这些差异,除非从机械意义上说,当共享模式获取成功时,下一个等待的线程(如果存在的话)必须确定得知其是否可获取成功。
* 不同模式下的等待线程共享一个FIFO队列。
* 通常,实现子类仅支持一种模式,但这两种模式都可以发挥作用,比如: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.
*
* <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.
* 此类为内部队列提供了检查、检测和监控的方法,也为condition对象提供了类似的方法。
* 可以使用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.
* 该类的序列化仅存储底层维持状态的原子整数,所以反序列化对象有空线程对象。
* 需要序列化的子类将定义一个readObject方法,在反序列化时来恢复它到一个已知的初始化状态。
*
* <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}:
* 想要使用这个类作为同步器的基础,通过使用(getState、setState)方法和/或compareAndSetState方法,
* 检查和/或修改同步状态,来按照需求重新定义以下方法
*
*
* <ul>
* <li> {@link #tryAcquire}
* <li> {@link #tryRelease}
* <li> {@link #tryAcquireShared}
* <li> {@link #tryReleaseShared}
* <li> {@link #isHeldExclusively}
* </ul>
*
* Each of these methods by default throws {@link
* UnsupportedOperationException}. Implementations of these methods
* must be internally thread-safe, and should in general be short and
* not block. Defining these methods is the <em>only</em> supported
* means of using this class. All other methods are declared
* {@code final} because they cannot be independently varied.
* 默认情况下,上述的每一个方法抛出UnsupportedOperationException异常。
* 这些方法的实现必须是内部线程安全的,并且处理同流程通常应该较短且非阻塞。
* 定义这些方法是使用该类唯一被支持的方式。
* 所有这些方法应该被声明为final,因为他们不能被独立更改。
*
* <p>You may also find the inherited methods from {@link
* AbstractOwnableSynchronizer} useful to keep track of the thread
* owning an exclusive synchronizer. You are encouraged to use them
* -- this enables monitoring and diagnostic tools to assist users in
* determining which threads hold locks.
* 你可能也发现继承自AbstractOwnableSynchronizer类的方法,对于跟踪拥有独占同步器的线程非常有用。
* 我们被鼓励使用它们--这使得监视和诊断工具能帮助用户确定哪些线程持有锁。
*
* <p>Even though this class is based on an internal FIFO queue, it
* does not automatically enforce FIFO acquisition policies. The core
* of exclusive synchronization takes the form:
* 尽管这个类基于一个内部FIFO队列,但它不会自动执行FIFO获取策略。
* 独占同步的核心遵循以下形式
*
* <pre>
* Acquire:// 获取锁
* while (!tryAcquire(arg)) {
* <em>enqueue thread if it is not already queued</em>;
* <em>possibly block current thread</em>;
* // 如果线程未排队,则入队
* // 可能阻塞当前线程
* }
*
* Release:// 释放锁
* if (tryRelease(arg))
* <em>unblock the first queued thread</em>;
* // 解除第一个排队线程的阻塞
* </pre>
*
* (Shared mode is similar but may involve cascading signals.)
* 共享模式可能类似,当时可能包含级联signals
*
* <p id="barging">Because checks in acquire are invoked before
* enqueuing, a newly acquiring thread may <em>barge</em> ahead of
* others that are blocked and queued. However, you can, if desired,
* define {@code tryAcquire} and/or {@code tryAcquireShared} to
* disable barging by internally invoking one or more of the inspection
* methods, thereby providing a <em>fair</em> FIFO acquisition order.
* In particular, most fair synchronizers can define {@code tryAcquire}
* to return {@code false} if {@link #hasQueuedPredecessors} (a method
* specifically designed to be used by fair synchronizers) returns
* {@code true}. Other variations are possible.
* 因为acquire过程中的检查在排队之前被调用,一个最新acquire的线程可能会在其他被阻塞和排队的线程之前闯入(barge)。
* 无论如何,在必要时,你可以定义tryAcquire和/或tryAcquireShared来禁用barging,通过内部调用一个或多个检查方法的方式,从而提供一个公平的FIFO获取顺序。
* 特别地,大部分公平同步锁可以定义tryAcquire方法来返回false,如果hasQueuedPredecessors返回true。
* hasQueuedPredecessors是一个专门为公平同步器设计的方法。
* 其他变化是可能的。
*
* <p>Throughput and scalability are generally highest for the
* default barging (also known as <em>greedy</em>,
* <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy.
* While this is not guaranteed to be fair or starvation-free, earlier
* queued threads are allowed to recontend before later queued
* threads, and each recontention has an unbiased chance to succeed
* against incoming threads. Also, while acquires do not
* "spin" in the usual sense, they may perform multiple
* invocations of {@code tryAcquire} interspersed with other
* computations before blocking. This gives most of the benefits of
* spins when exclusive synchronization is only briefly held, without
* most of the liabilities when it isn't. If so desired, you can
* augment this by preceding calls to acquire methods with
* "fast-path" checks, possibly prechecking {@link #hasContended}
* and/or {@link #hasQueuedThreads} to only do so if the synchronizer
* is likely not to be contended.
* 吞吐量和可伸缩性通常是默认barging(也称为贪心、放弃和避免护送)策略的*别,
* 虽然不能保证这是公平或无中断的,但允许更早排队的线程在比较晚排队线程之前重新竞争,而且每次重新竞争又一次公平地机会同传入的线程竞争成功。
* 另外,虽然通常情况acquires不会“自旋”,但在阻塞之前,他们可能执行多次tryAcquire的调用,并附带着其他计算。
* 当独占同步被短暂挂起时,就提供了自旋的大部分好处,没有了大部分不利因素。
* 如果需要,你可以通过前面的调用来增强这一点,即使用“fast-path”检查来获取方法,可能会预检查hasContended()和/或hasQueuedThreads(),只有在同步器可能不存在竞争的情况下才这样做。
*
*
* <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.
* 这个类为同步提供了有效的和可伸缩的基础,通过将其使用范围专业化到(可以依赖int状态、获取和释放参数以及内部FIFO等待队列)的同步器。
* 当这还未足够,你可以从使用了atomic类、自定义队列类和LockSupport阻塞支持,从较低的级别,来构建同步器
*
* <h3>Usage Examples</h3>
*
* <p>Here is a non-reentrant mutual exclusion lock class that uses
* the value zero to represent the unlocked state, and one to
* represent the locked state. While a non-reentrant lock
* does not strictly require recording of the current owner
* thread, this class does so anyway to make usage easier to monitor.
* It also supports conditions and exposes
* one of the instrumentation methods:
* 这有一个使用0值来表示未锁状态、1值表示加锁状态的不可重入互斥独占锁类。
* 虽然一个不可重入锁不严格要求计入当前owner的线程,但是这类还是这么做了,以便于容易见识使用状况。
*
* <pre> {@code
* class Mutex implements Lock, java.io.Serializable {
*
* // Our internal helper class
* private static class Sync extends AbstractQueuedSynchronizer {
* // Reports whether in locked state
* protected boolean isHeldExclusively() {
* return getState() == 1;
* }
*
* // Acquires the lock if state is zero
* public boolean tryAcquire(int acquires) {
* assert acquires == 1; // Otherwise unused
* if (compareAndSetState(0, 1)) {
* setExclusiveOwnerThread(Thread.currentThread());
* return true;
* }
* return false;
* }
*
* // Releases the lock by setting state to zero
* protected boolean tryRelease(int releases) {
* assert releases == 1; // Otherwise unused
* if (getState() == 0) throw new IllegalMonitorStateException();
* setExclusiveOwnerThread(null);
* setState(0);
* return true;
* }
*
* // Provides a Condition
* Condition newCondition() { return new ConditionObject(); }
*
* // Deserializes properly
* private void readObject(ObjectInputStream s)
* throws IOException, ClassNotFoundException {
* s.defaultReadObject();
* setState(0); // reset to unlocked state
* }
* }
*
* // The sync object does all the hard work. We just forward to it.
* private final Sync sync = new Sync();
*
* public void lock() { sync.acquire(1); }
* public boolean tryLock() { return sync.tryAcquire(1); }
* public void unlock() { sync.release(1); }
* public Condition newCondition() { return sync.newCondition(); }
* public boolean isLocked() { return sync.isHeldExclusively(); }
* public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
* public void lockInterruptibly() throws InterruptedException {
* sync.acquireInterruptibly(1);
* }
* public boolean tryLock(long timeout, TimeUnit unit)
* throws InterruptedException {
* return sync.tryAcquireNanos(1, unit.toNanos(timeout));
* }
* }}</pre>
*
* <p>Here is a latch class that is like a
* {@link java.util.concurrent.CountDownLatch CountDownLatch}
* except that it only requires a single {@code signal} to
* fire. Because a latch is non-exclusive, it uses the {@code shared}
* acquire and release methods.
* 这是一个类似于CountDownLatch类的latch类,只不过它仅需一个signal来触发。
* 因为latch是非独占的,所以它使用共享模式的acquire和release方法。
*
* <pre> {@code
* class BooleanLatch {
*
* private static class Sync extends AbstractQueuedSynchronizer {
* boolean isSignalled() { return getState() != 0; }
*
* protected int tryAcquireShared(int ignore) {
* return isSignalled() ? 1 : -1;
* }
*
* protected boolean tryReleaseShared(int ignore) {
* setState(1);
* return true;
* }
* }
*
* private final Sync sync = new Sync();
* public boolean isSignalled() { return sync.isSignalled(); }
* public void signal() { sync.releaseShared(1); }
* public void await() throws InterruptedException {
* sync.acquireSharedInterruptibly(1);
* }
* }}</pre>
*
* @since 1.5
* @author Doug Lea
*/
public abstract class AbstractQueuedSynchronizer
extends AbstractOwnableSynchronizer
implements java.io.Serializable {
/**
* Creates a new {@code AbstractQueuedSynchronizer} instance
* with initial synchronization state of zero.
*/
protected AbstractQueuedSynchronizer() { }
/**
* Wait queue node class.
* 等待队列Node静态内部类声明
*
* <p>The wait queue is a variant of a "CLH" (Craig, Landin, and
* Hagersten) lock queue. CLH locks are normally used for
* spinlocks. We instead use them for blocking synchronizers, but
* use the same basic tactic of holding some of the control
* information about a thread in the predecessor of its node. A
* "status" field in each node keeps track of whether a thread
* should block. A node is signalled when its predecessor
* releases. Each node of the queue otherwise serves as a
* specific-notification-style monitor holding a single waiting
* thread. The status field does NOT control whether threads are
* granted locks etc though. A thread may try to acquire if it is
* first in the queue. But being first does not guarantee success;
* it only gives the right to contend. So the currently released
* contender thread may need to rewait.
* 这个等待队列是“CLH”锁队列的变体。“CLH”锁通常用于自旋锁。
* 相反,我们使用其阻塞同步器,但使用相同的基本策略,即在该节点的前继续节点中持有线程的一些控制信息。
* 每个节点中的“status”字段跟踪线程是否应该阻塞。该节点的前继节点release时,该节点释放信号。
* 否则,队列中的每个节点都充当持有单个等待线程的“特定通知样式”的监视器。
* “status”字段不控制线程是否被授予锁。如果一个线程是队列中的第一个,它可能尝试acquire。
* 但是成为首个并不能保证成功;它仅仅被赋予了竞争的权利。
* 所以最近发布的竞争线程,可能需要重新等待。
*
* <p>To enqueue into a CLH lock, you atomically splice it in as new
* tail. To dequeue, you just set the head field.
* 要进入CLH锁队列,你需要原子地拼接新节点到队列,并作为新的tail。
* 要退出队列,你仅仅设置head字段即可。
*
* <pre>
* +------+ prev +-----+ +-----+
* head | | <---- | | <---- | | tail
* +------+ +-----+ +-----+
* </pre>
*
* <p>Insertion into a CLH queue requires only a single atomic
* operation on "tail", so there is a simple atomic point of
* demarcation from unqueued to queued. Similarly, dequeuing
* involves only updating the "head". However, it takes a bit
* more work for nodes to determine who their successors are,
* in part to deal with possible cancellation due to timeouts
* and interrupts.
* 插入CLH队列只需要在“tail”的一个原子操作,因此从无队列到队列只有一个简单的原子点划分。
* 相似地,退出队列仅包含更新“head”节点。
* 但是,节点需要更多的工作去驹诶定他们的继承者是谁,一定程度上是为了解决超时和中断可能引起的取消。
*
*
* <p>The "prev" links (not used in original CLH locks), are mainly
* needed to handle cancellation. If a node is cancelled, its
* successor is (normally) relinked to a non-cancelled
* predecessor. For explanation of similar mechanics in the case
* of spin locks, see the papers by Scott and Scherer at
* http://www.cs.rochester.edu/u/scott/synchronization/
* 这个"prev"指针链接(不用于原始CLH锁)主要用于处理取消。
* 如果一个节点被取消,它的继承者(通常)会重新连接到一个未被取消的前继节点。
* 有关自旋锁的类似机制的解释见以下地址:
*
* <p>We also use "next" links to implement blocking mechanics.
* The thread id for each node is kept in its own node, so a
* predecessor signals the next node to wake up by traversing
* next link to determine which thread it is. Determination of
* successor must avoid races with newly queued nodes to set
* the "next" fields of their predecessors. This is solved
* when necessary by checking backwards from the atomically
* updated "tail" when a node's successor appears to be null.
* (Or, said differently, the next-links are an optimization
* so that we don't usually need a backward scan.)
* 我们使用“next”指针链接来实现阻塞机制。
* 每个节点对应的线程Id都保存在自身节点中,故前继节点通过遍历next链接,来通知下一个节点苏醒,以确定他是哪个线程。
* 确定继承节点必须避免和新排队的节点竞争,以设置前继节点的“next”指针域。
* 当节点的继承节点可能为空时(或者换句话说,下一个链接是一个优化,因此我们通常不需要向后扫描),从原子更新的“tail”向后检查,从而在必要时解决这个问题。
*
* <p>Cancellation introduces some conservatism(保守性) to the basic
* algorithms. Since we must poll for cancellation of other
* nodes, we can miss noticing whether a cancelled node is
* ahead or behind us. This is dealt with by always unparking
* successors upon cancellation, allowing them to stabilize on
* a new predecessor, unless we can identify an uncancelled
* predecessor who will carry this responsibility.
* 取消在基本算法中引入了一定的保守性。
* 由于我们必须轮询以取消其他节点,因此我们可能遗漏注意到一个已取消的节点是在前面还是后面。
* 解决这个问题的方法是:总是在取消后继节点前unparking,允许后继节点稳定在一个新的前继节点上。
* 除非我们可以确定一个未被取消的,可以由其承担责任的前继节点
*
* <p>CLH queues need a dummy header node to get started. But
* we don't create them on construction, because it would be wasted
* effort if there is never contention. Instead, the node
* is constructed and head and tail pointers are set upon first
* contention.
* CLH队列需要一个虚拟的header节点来启动。
* 但是我们不用在结构上创建,因为假如从没有竞争,这将白白浪费。
* 反而,虚拟节点被构造,head和tail指针在第一次竞争时被设置。
*
* <p>Threads waiting on Conditions use the same nodes, but
* use an additional link. Conditions only need to link nodes
* in simple (non-concurrent) linked queues because they are
* only accessed when exclusively held. Upon await, a node is
* inserted into a condition queue. Upon signal, the node is
* transferred to the main queue. A special value of status
* field is used to mark which queue a node is on.
* 在Conditions条件等待的线程使用相同的节点,不过使用的另外一个链接。
* 条件只需要在简单(非并发)链接队列中链接节点,因为他们只要在独占持有时才会刚被访问。
* 等待时,将节点插入到条件队列中。
* 接到新号时,将节点传输到主队列。
* status字段的一个特殊值用于标记节点所在的队列
*
* <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill
* Scherer and Michael Scott, along with members of JSR-166
* expert group, for helpful ideas, discussions, and critiques
* on the design of this class.
*/
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;
static final int CONDITION = -2;
static final int PROPAGATE = -3;
/**
* Status field, taking on only the values: // 状态字段,仅接受以下的值
* SIGNAL: The successor of this node is (or will soon be)
* blocked (via park), so the current node must
* unpark its successor when it releases or
* cancels. To avoid races, acquire methods must
* first indicate they need a signal,
* then retry the atomic acquire, and then,
* on failure, block.
* 这个节点的后继节点是(或即将是)阻塞的(通过park),所以当它释放或取消时,当前节点必须unpark它的后继节点。
* 为了避免竞争,acquire方法必须首先表明他们需要一个信号,然后重新尝试原子获取,然后在失败、阻塞。
* CANCELLED: This node is cancelled due to timeout or interrupt.
* Nodes never leave this state. In particular,
* a thread with cancelled node never again blocks.
* 此节点由于超时或中断而被取消。节点永远不会离开这个状态。特别是,具有取消节点的线程永远不会阻塞。
*
* CONDITION: This node is currently on a condition queue.
* It will not be used as a sync queue node
* until transferred, at which time the status
* will be set to 0. (Use of this value here has
* nothing to do with the other uses of the
* field, but simplifies mechanics.)
* 此节点当前处于条件队列中。它将不会被用作同步队列节点,直到被传输到主队列,此时的状态将被设置为0。(此处使用此值与该字段的其他用途无关,只是简化了机制。)
*
* PROPAGATE: A releaseShared should be propagated to other
* nodes. This is set (for head node only) in
* doReleaseShared to ensure propagation
* continues, even if other operations have
* since intervened.
* 已发布共享的节点应该被传播到其他节点。这是在doReleaseShared中设置(仅针对head节点)来确保传播继续,即使后来又其他操作干预
*
* 0: None of the above
*
* The values are arranged numerically to simplify use.
* Non-negative values mean that a node doesn't need to
* signal. So, most code doesn't need to check for particular
* values, just for sign.
* 该字段使用数值以简化使用。非负值意味着节点不需要发出信号。因此,大多数代码不需要检查特定的值,只需检查签名即可。
*
* 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(-2)。它使用CAS进行修改(或者在可能的情况下,无条件volatile写)。
*
*/
volatile int waitStatus;
volatile Node prev;
volatile Node next;
volatile Thread thread;
Node nextWaiter;
.....
}
private transient volatile Node head;
private transient volatile Node tail;
private volatile int state;
....
}
上一篇: 详述Java程序注释
下一篇: Java程序注释
推荐阅读
-
深入理解PHP原理之Session Gc的一个小概率Notice
-
理解AQS原理一之阅读注释
-
你真的懂AQS吗?透彻理解AQS源码分析系列之AQS基础一
-
你真的懂AQS吗?透彻理解AQS源码分析系列之AQS基础一
-
深入理解PHP原理之Session Gc的一个小概率Notice_php技巧
-
深入理解PHP原理之Session Gc的一个小概率Notice_php技巧
-
深入理解PHP原理之Session Gc的一个小概率Notice
-
深入理解PHP原理之Session Gc的一个小概率Notice
-
深入理解PHP原理之Session Gc的一个小概率Notice
-
深入理解PHP原理之Session Gc的一个小概率Notice_PHP