博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
翻译 AbstractQueuedSynchronizer ( AQS )类注释
阅读量:4222 次
发布时间:2019-05-26

本文共 9378 字,大约阅读时间需要 31 分钟。

学习笔记, 分享之.

版本: Java 8

Class: java.util.concurrent.locks.AbstractQueuedSynchronizer

本类提供了一个框架, 用于实现阻塞锁及其相关的同步器( 信号量, 事件等 ), 框架依赖FIFO等待队列. 设计这个类, 是为了给那些各种各样的同步器提供一个有用的基础, 那些同步器有一个共同特征: 使用一个int原子类型描述其状态. 本类的子类需定义修改该状态的protected方法, 也要定义这些状态对于该对象被获取或释放的意义. 基于此, 该类中其他方法执行排队和阻塞机制. 子类可以管理其他的状态字段, 但就同步而言, 只有使用了getState/setState/cas进行原子更新的int值能够被追踪.

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 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 int value manipulated using methods getState, setState and compareAndSetState is tracked with respect to synchronization.

子类应该定义一个非公开的内部帮助类, 用于实现它的内部类的同步属性. 本类没有实现任何同步接口. 取而代之的是acquireInterruptibly方法, 它可以在适当的时候由具体的锁和相关的同步器调用, 以实现他们的公共方法.

Subclasses should be defined as non-public internal helper classes that are used to implement the synchronization properties of their enclosing class. Class AbstractQueuedSynchronizer does not implement any synchronization interface. Instead it defines methods such as acquireInterruptibly that can be invoked as appropriate by concrete locks and related synchronizers to implement their public methods.

本类同时支持独占模式和共享模式, 或者其中之一. 在独占模式下, 其他线程不能获取本类. 在共享模式下, 多线程也许能获取, 但不一定. 但本类不去理解这两种的区别, 本类只能说: 当一个线程成功取得本类, 下一个线程必须判断自己是否也能取得. 不同模式的线程等待的时候, 使用是相同的FIFO队列. 通常子类只实现一种模式, 但两者可以同时工作, 例如ReadWriteLock. 只支持一种模式的子类, 无需再为另一种模式定义方法.

This class supports either or both a default exclusive mode and a shared 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 ReadWriteLock. Subclasses that support only exclusive or only shared modes need not define the methods supporting the unused mode.

本类定义了一个内部类AbstractQueuedSynchronizer.ConditionObject, 可以当做Condition的实例供支持独占模式的子类使用, 对于独占模式, 方法isHeldExclusively可以告诉你, 对于当前的线程来说同步是否是独占的( 即独占锁? ), 使用getStat()的值调用release()完全释放这个对象, 使用这个值调用acquire(), 最终恢复到前一个获取锁的状态. AbstractQueuedSynchronizer中没有其他方法创建这个条件, 所以如果不能满足这个约束,就不要使用它. AbstractQueuedSynchronizer.ConditionObject的行为当然是基于它的实现类的语义.

This class defines a nested AbstractQueuedSynchronizer.ConditionObject class that can be used as a Condition implementation by subclasses supporting exclusive mode for which method isHeldExclusively reports whether synchronization is exclusively held with respect to the current thread, method release invoked with the current getState value fully releases this object, and acquire, given this saved state value, eventually restores this object to its previous acquired state. No AbstractQueuedSynchronizer method otherwise creates such a condition, so if this constraint cannot be met, do not use it. The behavior of AbstractQueuedSynchronizer.ConditionObject depends of course on the semantics of its synchronizer implementation.

该类为内部类提供了 检查/仪表化/监视 方法, 以及类似的用于condition对象的方法. 这些可以导出到使用AbstractQueuedSynchronizer作为同步机制的类中.

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 AbstractQueuedSynchronizer for their synchronization mechanics.

该类的序列化仅仅存储原子整数的维护状态, 所以反序列化对象得到的线程队列是空的. 子类若需要序列化, 要定义readObject()用于恢复自己到一个已知的初始状态.

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 readObject method that restores this to a known initial state upon deserialization.

用法:

若将该类用作同步器的基础, 请使用getState()/setState()/cas这些用于检查或修改同步状态的方法对下面的方法进行重新定义:
tryAcquire
tryRelease
tryAcquireShared
tryReleaseShared
isHeldExclusively

Usage

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 getState, setState and/or compareAndSetState:
tryAcquire
tryRelease
tryAcquireShared
tryReleaseShared
isHeldExclusively

这些方法默认抛出UnsupportedOperationException, 这些方法内部必须保证线程安全, 并且通常应该是简短且无锁的. 定义这些方法是使用该类的意义所在. 其他方法因为不能独立的变化, 所以声明为final.

Each of these methods by default throws UnsupportedOperationException. Implementations of these methods must be internally thread-safe, and should in general be short and not block. Defining these methods is the only supported means of using this class. All other methods are declared final because they cannot be independently varied.

你也能看到继承自AbstractOwnableSynchronizer的方法, 用于跟踪那些独占了同步器的线程. 鼓励你使用这些方法, 它们开启了监视和诊断功能, 可以帮助用户判断那些线程持有锁.

You may also find the inherited methods from 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.

即使该类基于内部FIFO队列, 但也不会执行默认的FIFO策略, 独占同步的核心使用以下策略:

Acquire:       while (!tryAcquire(arg)) {
enqueue thread if it is not already queued; possibly block current thread; } Release: if (tryRelease(arg)) unblock the first queued thread;

(共享模式类似, 但可能涉及级联信号.) 因为对获取锁的检查是在入队之前进行, 所以一个新线程可能会插入到其他已经入队的线程之前. 不管咋地吧, 你要是愿意, 可以通过调用内部的一个或多个检查方法去定义 tryAcquire() / tryAcquireShared()方法, 从而提供一个公平的FIFO获取顺序. 特别是, 大多数公平同步器在 hasQueuedPredecessors()(这是一个专门设计用于公平同步器的)返回true的时候, 让tryAcquire()返回false. 当然, 其他方法也有可能.

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:

Acquire:
while (!tryAcquire(arg)) {
enqueue thread if it is not already queued;
possibly block current thread;
}
Release:
if (tryRelease(arg))
unblock the first queued thread;

(Shared mode is similar but may involve cascading signals.)

Because checks in acquire are invoked before enqueuing, a newly acquiring thread may barge ahead of others that are blocked and queued. However, you can, if desired, define tryAcquire and/or tryAcquireShared to disable barging by internally invoking one or more of the inspection methods, thereby providing a fair FIFO acquisition order. In particular, most fair synchronizers can define tryAcquire to return false if hasQueuedPredecessors (a method specifically designed to be used by fair synchronizers) returns true. Other variations are possible.

对于默认的插队策略(也叫greedy/renouncement/convoy-avoidance), 吞吐量和可伸缩性通常最高. 尽管这不能保证公平, 但允许早入队的线程在后来的线程之前重新竞争, 每个重新竞争的线程拥有公平的机会打败新来的线程. 尽管获取行为通常不会一直进行, 但线程在被阻塞之前, 伴随着其他计算过程, 他们可能会多次调用 tryAcquire(). 当独占同步器只是短暂的被持有时, 这对于自旋来说很有好处, 没有太多负担. 你可以通过前面的调用增强这一点, 以获得带有"fast-path"的方法. 如果同步器可能没有被争夺, 或许只会预先检查 hasContended() 和 hasQueuedThreads().

Throughput and scalability are generally highest for the default barging (also known as greedy, renouncement, and convoy-avoidance) 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 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 hasContended and/or hasQueuedThreads to only do so if the synchronizer is likely not to be contended.

这个类为同步提供了有效的可扩展的基础, 部分原因是把范围集中在那些依赖数字状态、 获取/释放参数、 以及内部FIFO的同步器上. 当这些不能满足需要时, 你可以使用原子类、 你自己的 java.util.Queue 类、 LockSuppor 来构建更底层的同步器.

This class provides an efficient and scalable basis for synchronization in part by specializing its range of use to synchronizers that can rely on 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 atomic classes, your own custom java.util.Queue classes, and LockSupport blocking support.

用法示例:

这是一个不可重入互斥锁, 0表示打开, 1表示锁定. 虽然不可重入锁无需严格记录本地拥有者的线程, 但这个类还是这么做了, 以便更容易监视. 同时也支持 conditions 并且公开了一个检测方法. ( 代码略… )

Usage Examples

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:

转载地址:http://mzgmi.baihongyu.com/

你可能感兴趣的文章
对指定文件或目录进行压缩和解压缩的工具类总结
查看>>
Java中如何遍历Map对象的4种方法
查看>>
图片延时加载例子详解
查看>>
js获取url参数值的两种方式详解
查看>>
java中System.getProperty()方法详解
查看>>
MyEclipse设置默认注释的格式
查看>>
同一服务器部署多个tomcat时的端口号修改详情
查看>>
常用正则表达式集锦
查看>>
Spring定时器的时间表达式
查看>>
fastdfs简介
查看>>
主键和唯一索引的区别
查看>>
linux下使用yum安装gcc详解
查看>>
aclocal安装依赖的库
查看>>
FastDFS 安装及使用详解
查看>>
ERROR 1045 (28000): Access denied for user root@localhost (using password: NO)解决方案
查看>>
Host 'XXX' is not allowed to connect to this MySQL server解决方案
查看>>
corosync pacemaker 配置高可用集群(一)
查看>>
5种IO模型、阻塞IO和非阻塞IO、同步IO和异步IO
查看>>
nginx(一) nginx详解
查看>>
nginx(二) nginx编译安装 及 配置WEB服务
查看>>