解析任务(JAVA 1.8环境下)
- AbstractOwnableSynchronizer
- AbstractQueuedSynchronizer
应用到的框架
AbstractOwnableSynchronizer
简称:AOS
可以看到,它里面有一个 exclusiveOwnerThread 属性,它是用于指向当前拿到锁的线程。
AbstractQueuedSynchronizer
AbstractQueuedSynchronizer 简称(AQS)
如它的名称所说,这是一个在并发环境下维护队列的抽象类,它负责提供工具(积木),至于想实现什么样的功能(形状)由子类自己决定。
类继承关系及构造方法实现
public abstract class AbstractQueuedSynchronizer
extends AbstractOwnableSynchronizer
implements java.io.Serializable {
protected AbstractQueuedSynchronizer() { }
}
- 可以看到它继承了上述的AOS抽象类并实现了Serializable ,这就表明,它也可以指向一个线程!
- 并且它的构造方法没有做任何事情
内部类及涉及到的内容
它里面定义的内部类如下,根据注解它们的应用场景分别为
- Node:等待队列的节点类
- ConditionObject:条件队列
Node(等待队列节点类)
Node节点又名CLH
等待队列是“CLH”(Craig、Landin 和 Hagersten)锁定队列的变体。 CLH 锁通常用于自旋(循环)锁。
抽象图如下:
因为篇幅原因简化后的代码如下:
static final class Node {
//SHARED 和 EXCLUSIVE 用于标识当前节点是共享还是独占的
///Node是共享的
static final Node SHARED = new Node();
///Node是独占的
static final Node EXCLUSIVE = null;
//以下四个常量用于标识节点所处的状态
///CANCELLED :线程取消(异常,或其它原因线程不能执行的)
static final int CANCELLED = 1;
///SIGNAL :后面有线程需要解锁(唤醒)
static final int SIGNAL = -1;
///CONDITION : 指示线程正在等待条件(条件达成就唤醒)
static final int CONDITION = -2;
///PROPAGATE : 指示下一个acquireShared方法应该广播(通知所有线程)
static final int PROPAGATE = -3;
//当前线程的状态,默认为0(初始化状态),取值范围为上面的四个状态常量与0
volatile int waitStatus;
//当前节点的上一个节点
volatile Node prev;
//当前节点的下一个节点
volatile Node next;
//当前节点指向的线程
volatile Thread thread;
//下一个等待条件的节点,或特殊值 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持有的线程,及当前节点是否共享*/
Node(Thread thread, Node mode) { // Used by addWaiter
this.nextWaiter = mode;
this.thread = thread;
}
/**构造方法:初始化Node持有的线程,及节点状态*/
Node(Thread thread, int waitStatus) { // Used by Condition
this.waitStatus = waitStatus;
this.thread = thread;
}
}
总结:可以看到这个节点可以指向前后节点,线程对象,并拥有两个变量标识自己的状态。
ConditionObject(条件队列)
该类继承自Condition,我们先来看看这个接口要实现什么功能,代码如下:
public interface Condition {
//等待相对于新增元素
//使当前线程等待,直到它收到信号或被中断。
void await() throws InterruptedException;
//导致当前线程等待,直到它被发出信号。
void awaitUninterruptibly();
//使当前线程等待,直到它被发出信号或被中断,或者指定的等待时间过去。
//nanosTimeout – 等待的最长时间,以纳秒为单位
long awaitNanos(long nanosTimeout) throws InterruptedException;
//使当前线程等待,直到它被发出信号或被中断,或者指定的等待时间过去
//time – 等待的最长时间
//unit – 时间参数的时间单位
boolean await(long time, TimeUnit unit) throws InterruptedException;
//导致当前线程等待,直到它被发出信号或被中断,或者指定的截止日期过去。
截止日期 - 等待的绝对时间
boolean awaitUntil(Date deadline) throws InterruptedException;
//唤醒相对于移除元素
//唤醒一个等待线程。
void signal();
//唤醒所有等待的线程。
void signalAll();
}
总结:可用看到,继承了Condition,我们就要实现等待与唤醒两种操作。
我们再来看看AQS中的实现,代码如下:
public class ConditionObject implements Condition, java.io.Serializable {
private static final long serialVersionUID = 1173984872572414699L;
/**条件队列的第一个节点。 */
private transient Node firstWaiter;
/**条件队列的最后一个节点。 */
private transient Node lastWaiter;
/**无参构造方法。 */
public ConditionObject() { }
// 内部方法区
/**添加一个新的等待节点*/
private Node addConditionWaiter() {
Node t = lastWaiter;
// If lastWaiter is cancelled, clean out.
if (t != null && t.waitStatus != Node.CONDITION) {
//从条件队列中取消链接取消的服务员节点
//里面逻辑为:从队头开始找可用节点,去除不符合条件节点重新组成一条可用链
unlinkCancelledWaiters();
t = lastWaiter;
}
Node node = new Node(Thread.currentThread(), Node.CONDITION);
if (t == null)
firstWaiter = node;
else
t.nextWaiter = node;
lastWaiter = node;
return node;
}
/**执行 将当前条件队列的节点移除,并加入到CLH队列里*/
private void doSignal(Node first) {
do {
if ( (firstWaiter = first.nextWaiter) == null)
lastWaiter = null;
first.nextWaiter = null;
//transferForSignal(first):将节点从条件队列转移到同步队列。如果成功则返回真。
} while (!transferForSignal(first) &&
(first = firstWaiter) != null);
}
/**执行 将当前条件队列的节点一个个移除,并加入到CLH队列里*/
private void doSignalAll(Node first) {
lastWaiter = firstWaiter = null;
do {
Node next = first.nextWaiter;
first.nextWaiter = null;
transferForSignal(first);
first = next;
} while (first != null);
}
/**从条件队列中取消链接已取消的等待节点。仅在持有锁时调用*/
private void unlinkCancelledWaiters() {
Node t = firstWaiter;
Node trail = null;
while (t != null) {
Node next = t.nextWaiter;
if (t.waitStatus != Node.CONDITION) {
t.nextWaiter = null;
if (trail == null)
firstWaiter = next;
else
trail.nextWaiter = next;
if (next == null)
lastWaiter = trail;
}
else
trail = t;
t = next;
}
}
// 公共方法区
//Condition接口要求实现的唤醒方法
//将等待时间最长的线程(如果存在)从此条件的等待队列移动到拥有锁的等待队列。
public final void signal() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
doSignal(first);
}
//Condition接口要求实现的唤醒所有方法
//将所有线程从此条件的等待队列移动到拥有锁的等待队列。
public final void signalAll() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
doSignalAll(first);
}
//实现不间断条件等待。
public final void awaitUninterruptibly() {
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
boolean interrupted = false;
while (!isOnSyncQueue(node)) {
LockSupport.park(this);
if (Thread.interrupted())
interrupted = true;
}
if (acquireQueued(node, savedState) || interrupted)
selfInterrupt();
}
//是重新中断状态常量
/// 模式意味着:当前线程重新中断
private static final int REINTERRUPT = 1;
/// 模式意味着:直接抛出中断异常
private static final int THROW_IE = -1;
//检查中断,如果在发出信号之前中断,则返回 THROW_IE,
//如果发出信号则返回 REINTERRUPT
//如果未中断则返回 0。
private int checkInterruptWhileWaiting(Node node) {
return Thread.interrupted() ?
(transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
0;
}
//抛出 InterruptedException,重新中断当前线程,或者什么都不做,取决于模式
private void reportInterruptAfterWait(int interruptMode)
throws InterruptedException {
if (interruptMode == THROW_IE)
//直接抛出中断异常
throw new InterruptedException();
else if (interruptMode == REINTERRUPT)
//当前线程重新中断
selfInterrupt();
}
//Condition接口要求实现的等待方法
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
LockSupport.park(this);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null) // clean up if cancelled
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
}
//Condition接口要求实现的定时条件等待方法
public final long awaitNanos(long nanosTimeout)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
final long deadline = System.nanoTime() + nanosTimeout;
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
if (nanosTimeout <= 0L) {
transferAfterCancelledWait(node);
break;
}
if (nanosTimeout >= spinForTimeoutThreshold)
LockSupport.parkNanos(this, nanosTimeout);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
nanosTimeout = deadline - System.nanoTime();
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null)
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
return deadline - System.nanoTime();
}
//Condition接口要求实现的定时条件等待方法
public final boolean awaitUntil(Date deadline)
throws InterruptedException {
long abstime = deadline.getTime();
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
boolean timedout = false;
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
if (System.currentTimeMillis() > abstime) {
timedout = transferAfterCancelledWait(node);
break;
}
LockSupport.parkUntil(this, abstime);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null)
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
return !timedout;
}
//Condition接口要求实现的定时条件等待方法
public final boolean await(long time, TimeUnit unit)
throws InterruptedException {
long nanosTimeout = unit.toNanos(time);
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
final long deadline = System.nanoTime() + nanosTimeout;
boolean timedout = false;
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
if (nanosTimeout <= 0L) {
timedout = transferAfterCancelledWait(node);
break;
}
if (nanosTimeout >= spinForTimeoutThreshold)
LockSupport.parkNanos(this, nanosTimeout);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
nanosTimeout = deadline - System.nanoTime();
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null)
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
return !timedout;
}
//Returns true if this condition was created by the given synchronization object.
//如果此条件是由给定的同步对象创建的,则返回 true。
final boolean isOwnedBy(AbstractQueuedSynchronizer sync) {
return sync == AbstractQueuedSynchronizer.this;
}
//查询是否有线程在此条件下等待
protected final boolean hasWaiters() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
if (w.waitStatus == Node.CONDITION)
return true;
}
return false;
}
//返回等待此条件的线程数的估计值。
protected final int getWaitQueueLength() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
int n = 0;
for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
if (w.waitStatus == Node.CONDITION)
++n;
}
return n;
}
//得到等待的线程集合
protected final Collection<Thread> getWaitingThreads() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
ArrayList<Thread> list = new ArrayList<Thread>();
for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
if (w.waitStatus == Node.CONDITION) {
Thread t = w.thread;
if (t != null)
list.add(t);
}
}
return list;
}
}
总结:通过创建该对象可以得到一个队列,一个对象对应一个条件,await相当于入队,signal相当于出队,而且是出队到CLH队列,需要注意的是条件队列不能获取锁,只有CLH队列可以获取锁。
注意:CLH队列由AQS维护!
静态构造方法及涉及到的变量
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long stateOffset;
private static final long headOffset;
private static final long tailOffset;
private static final long waitStatusOffset;
private static final long nextOffset;
static {
try {
stateOffset = unsafe.objectFieldOffset
(AbstractQueuedSynchronizer.class.getDeclaredField("state"));
headOffset = unsafe.objectFieldOffset
(AbstractQueuedSynchronizer.class.getDeclaredField("head"));
tailOffset = unsafe.objectFieldOffset
(AbstractQueuedSynchronizer.class.getDeclaredField("tail"));
waitStatusOffset = unsafe.objectFieldOffset
(Node.class.getDeclaredField("waitStatus"));
nextOffset = unsafe.objectFieldOffset
(Node.class.getDeclaredField("next"));
} catch (Exception ex) { throw new Error(ex); }
}
查看它的方法注解可知上面的对象使用了compareAndSet(CAS)来保证原子性,只所以不用AtomicInteger 是为了未来的可扩展性。
其中使用到了以下方法:
AbstractQueuedSynchronizer.class.getDeclaredField():使用反射获取成员变量
unsafe.objectFieldOffset(): 得到成员变量的地址
它在里面通过反射为一些静态变量赋地址,分别为:
- stateOffset:标识状态对象的变量地址
- headOffset:标识头部对象的变量地址
- tailOffset:标识尾部对象的变量地址
- waitStatusOffset:标识等待状态对象的变量地址
- nextOffset:标识下一个对象的变量地址
总结:获取到了变量的地址,用与 进行CAS算法的方法 入参
ASQ逻辑解析
经过前面的基础知识铺垫,终于要开始正题了!
查看剩下的代码我们可以看到,
/**
*指向等待队列(CLH)队列的头,懒加载方式加载
* 除了初始化外,仅通过setHead方法修改
* 注意:假如它存在,则要保证其waitStatus不会被CANCELLED。
*/
private transient volatile Node head;
/**
*等待队列(CLH)的尾部,延迟初始化。仅通过方法enq 修改以添加新的等待节点
*/
private transient volatile Node tail;
/**
* 同步状态
*/
private volatile int state;
是不是很熟悉,没错,我们在静态构造方法拿到的就是这几个对象的地址,现在AQS的抽象图如下:
其它剩下的代码都是方法,我们一个个介绍过去(忽略了一些方法),代码如下:
/** 返回同步状态的当前值。 因为有加了volatile关键字保证了及时可见性*/
protected final int getState() {
return state;
}
/**设置同步状态的值。*/
protected final void setState(int newState) {
state = newState;
}
/**CAS 方式设置同步状态的值, 返回是否成功(true:是,false 否) */
protected final boolean compareAndSetState(int expect, int update) {
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
// Queuing utilities(排队方法层)
/** 自旋机制提供的自旋纳秒数,提高响应能力*/
static final long spinForTimeoutThreshold = 1000L;
/**
*自旋入队, 将节点插入CLH队列
* 必要时初始化(tail==null):队列一定要先初始化有一个节点,再把属性插入到该节点后面
*/
private Node enq(final Node node) {
//自旋
for (;;) {
//拿到CLH队列尾部节点
Node t = tail;
if (t == null) { // Must initialize
//假如尾部节点为Null,则进行初始化
if (compareAndSetHead(new Node()))
//假如强盗锁,则将头部结点指针赋值给尾部结点指针,它们共同指向CLH队列第一个结点
tail = head;
//没抢到锁的话就进行下一个循环
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
//抢到了锁,没抢到就进入下一个循环继续抢
t.next = node;
return t;
}
}
}
}
/** 根据模式节点创建或加入队列*/
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
/**
* 将传入的节点设置为CLH队列头节点
* 为了 GC 和抑制不必要的信号和遍历,还清空了未使用的字段。
*/
private void setHead(Node node) {
head = node;
node.thread = null;
node.prev = null;
}
/**唤醒节点的后续节点, 如果存在的话。 */
private void unparkSuccessor(Node node) {
//判断传入节点的等待状态是否<0,假如是的话,尝试将其置为0
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);
//通常只找下一个节点,但是如果取消等待或者为空的话,从队尾向前遍历找到一个可用的节点
Node s = node.next;
if (s == null || s.waitStatus > 0) {
s = null;
//从队尾节点一直遍历到当前节点
for (Node t = tail; t != null && t != node; t = t.prev)
if (t.waitStatus <= 0)
s = t;
}
if (s != null)
//唤醒线程
LockSupport.unpark(s.thread);
}
/**
* 共享模型下是否共享值
*更改head的状态为广播(PROPAGATE)
*如果抢到锁则释放下一个节点的线程并更改head的等待状态并继续抢锁
*如果都抢到了,则将当前节点的状态更改为广播状态
*/
private void doReleaseShared() {
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
unparkSuccessor(h);
}
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
/**设置队列的头部 */
private void setHeadAndPropagate(Node node, int propagate) {
Node h = head; // Record old head for check below
setHead(node);
if (propagate > 0 || h == null || h.waitStatus < 0 ||
(h = head) == null || h.waitStatus < 0) {
Node s = node.next;
if (s == null || s.isShared())
doReleaseShared();
}
}
//锁获取方法层
/**放弃获取锁(取消尝试acquire操作) */
private void cancelAcquire(Node node) {
if (node == null)
return;
node.thread = null;
Node pred = node.prev;
while (pred.waitStatus > 0)
node.prev = pred = pred.prev;
Node predNext = pred.next;
node.waitStatus = Node.CANCELLED;
if (node == tail && compareAndSetTail(node, pred)) {
compareAndSetNext(pred, predNext, null);
} else {
int ws;
if (pred != head &&
((ws = pred.waitStatus) == Node.SIGNAL ||
(ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
pred.thread != null) {
Node next = node.next;
if (next != null && next.waitStatus <= 0)
compareAndSetNext(pred, predNext, next);
} else {
unparkSuccessor(node);
}
node.next = node; // help GC
}
}
/**
* 检查和更新未能获取的节点的状态
* 假如前一个节点没有取消等待的话,将node节点 赋给前一个节点
* 假如前面的节点取消等待,则一直往前找,直到找到可用的 节点,并将node赋给它
*/
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
return true;
if (ws > 0) {
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
/**
* 中断当前线程方法
*/
static void selfInterrupt() {
Thread.currentThread().interrupt();
}
/**
* 阻塞住本线程,阻塞完后清除中断标志位
* 因为有中断标志位的话 LockSupport.park(this);无效
*/
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
/**条件等待方法以及获取 */
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 doAcquireInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.EXCLUSIVE);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
/**独占时间模式获取*/
private boolean doAcquireNanos(int arg, long nanosTimeout)
throws InterruptedException {
if (nanosTimeout <= 0L)
return false;
final long deadline = System.nanoTime() + nanosTimeout;
final Node node = addWaiter(Node.EXCLUSIVE);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return true;
}
nanosTimeout = deadline - System.nanoTime();
if (nanosTimeout <= 0L)
return false;
if (shouldParkAfterFailedAcquire(p, node) &&
nanosTimeout > spinForTimeoutThreshold)
LockSupport.parkNanos(this, nanosTimeout);
if (Thread.interrupted())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
/**共享不可中断模式获取 */
private void doAcquireShared(int arg) {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
if (interrupted)
selfInterrupt();
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
/** 共享中断模式获取*/
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
/**共享时间模式获取*/
private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
throws InterruptedException {
if (nanosTimeout <= 0L)
return false;
final long deadline = System.nanoTime() + nanosTimeout;
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return true;
}
}
nanosTimeout = deadline - System.nanoTime();
if (nanosTimeout <= 0L)
return false;
if (shouldParkAfterFailedAcquire(p, node) &&
nanosTimeout > spinForTimeoutThreshold)
LockSupport.parkNanos(this, nanosTimeout);
if (Thread.interrupted())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
// Main exported methods (Api层)
/** 独占模式获取锁*/
protected boolean tryAcquire(int arg) {
throw new UnsupportedOperationException();
}
/**独占模式释放锁*/
protected boolean tryRelease(int arg) {
throw new UnsupportedOperationException();
}
/** 共享模式获取锁*/
protected int tryAcquireShared(int arg) {
throw new UnsupportedOperationException();
}
/**共享模式释放锁 */
protected boolean tryReleaseShared(int arg) {
throw new UnsupportedOperationException();
}
/**是否是独占模式,调用ConditionObject都会调用这个方法 */
protected boolean isHeldExclusively() {
throw new UnsupportedOperationException();
}
/**独占模式忽略中断 */
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
/**独占模式中断即停止 */
public final void acquireInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (!tryAcquire(arg))
doAcquireInterruptibly(arg);
}
/**独占模式忽略中断*/
public final boolean tryAcquireNanos(int arg, long nanosTimeout)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
return tryAcquire(arg) ||
doAcquireNanos(arg, nanosTimeout);
}
/**独占模式释放*/
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
/**共享模式获取*/
public final void acquireShared(int arg) {
if (tryAcquireShared(arg) < 0)
doAcquireShared(arg);
}
/** 共享模式中断即停止 */
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
/** 共享模式忽略中断*/
public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
return tryAcquireShared(arg) >= 0 ||
doAcquireSharedNanos(arg, nanosTimeout);
}
/**释放共享锁*/
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
// Queue inspection methods(队列方法层)
/**查询是否有线程正在等待获取*/
public final boolean hasQueuedThreads() {
return head != tail;
}
/**查询是否有线程争用过此同步器*/
public final boolean hasContended() {
return head != null;
}
/**
* 返回队列中的第一个线程
*/
public final Thread getFirstQueuedThread() {
return (head == tail) ? null : fullGetFirstQueuedThread();
}
/** Version of getFirstQueuedThread called when fastpath fails*/
private Thread fullGetFirstQueuedThread() {
Node h, s;
Thread st;
if (((h = head) != null && (s = h.next) != null &&
s.prev == head && (st = s.thread) != null) ||
((h = head) != null && (s = h.next) != null &&
s.prev == head && (st = s.thread) != null))
return st;
Node t = tail;
Thread firstThread = null;
while (t != null && t != head) {
Thread tt = t.thread;
if (tt != null)
firstThread = tt;
t = t.prev;
}
return firstThread;
}
/**判断给定的线程是否在排队*/
public final boolean isQueued(Thread thread) {
if (thread == null)
throw new NullPointerException();
for (Node p = tail; p != null; p = p.prev)
if (p.thread == thread)
return true;
return false;
}
/**判断第一个节点是否为独占模式 */
final boolean apparentlyFirstQueuedIsExclusive() {
Node h, s;
return (h = head) != null &&
(s = h.next) != null &&
!s.isShared() &&
s.thread != null;
}
/**是否还有节点在排队*/
public final boolean hasQueuedPredecessors() {
Node t = tail;
Node h = head;
Node s;
return h != t &&
((s = h.next) == null || s.thread != Thread.currentThread());
}
// Instrumentation and monitoring methods(测量与监控队列方法)
/**得到队列长度 */
public final int getQueueLength() {
int n = 0;
for (Node p = tail; p != null; p = p.prev) {
if (p.thread != null)
++n;
}
return n;
}
/**得到队列线程数*/
public final Collection<Thread> getQueuedThreads() {
ArrayList<Thread> list = new ArrayList<Thread>();
for (Node p = tail; p != null; p = p.prev) {
Thread t = p.thread;
if (t != null)
list.add(t);
}
return list;
}
/**得到属于独占模式的线程数*/
public final Collection<Thread> getExclusiveQueuedThreads() {
ArrayList<Thread> list = new ArrayList<Thread>();
for (Node p = tail; p != null; p = p.prev) {
if (!p.isShared()) {
Thread t = p.thread;
if (t != null)
list.add(t);
}
}
return list;
}
/**得到属于共享模式的线程数*/
public final Collection<Thread> getSharedQueuedThreads() {
ArrayList<Thread> list = new ArrayList<Thread>();
for (Node p = tail; p != null; p = p.prev) {
if (p.isShared()) {
Thread t = p.thread;
if (t != null)
list.add(t);
}
}
return list;
}
// Internal support methods for Conditions(条件队列方法层)
/*** 该节点是否正在等待重新获取同步队列*/
final boolean isOnSyncQueue(Node node) {
if (node.waitStatus == Node.CONDITION || node.prev == null)
return false;
if (node.next != null) // If has successor, it must be on queue
return true;
return findNodeFromTail(node);
}
/*** 自旋查找该节点是否属于CLH节点*/
private boolean findNodeFromTail(Node node) {
Node t = tail;
for (;;) {
if (t == node)
return true;
if (t == null)
return false;
t = t.prev;
}
}
/** * 唤醒并将node传输到CLH队列里*/
final boolean transferForSignal(Node node) {
if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
return false;
Node p = enq(node);
int ws = p.waitStatus;
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
LockSupport.unpark(node.thread);
return true;
}
/** 将节点从条件队列转移到同步队列。如果成功则返回真。*/
final boolean transferForSignal(Node node) {
if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
enq(node);
return true;
}
while (!isOnSyncQueue(node))
Thread.yield();
return false;
}
/**
* Invokes release with current state value; returns saved state.
* Cancels node and throws exception on failure.
*/
final int fullyRelease(Node node) {
boolean failed = true;
try {
int savedState = getState();
if (release(savedState)) {
failed = false;
return savedState;
} else {
throw new IllegalMonitorStateException();
}
} finally {
if (failed)
node.waitStatus = Node.CANCELLED;
}
}
// Instrumentation methods for conditions
/** * 查询这个条件队列是否是这个锁的 */
public final boolean owns(ConditionObject condition) {
return condition.isOwnedBy(this);
}
/** * 查询是否有任何线程正在等待与此同步器关联的给定条件 */
public final boolean hasWaiters(ConditionObject condition) {
if (!owns(condition))
throw new IllegalArgumentException("Not owner");
return condition.hasWaiters();
}
/** *得到等待此条件的队列长度 */
public final int getWaitQueueLength(ConditionObject condition) {
if (!owns(condition))
throw new IllegalArgumentException("Not owner");
return condition.getWaitQueueLength();
}
/**得到等待此条件的线程集合 */
public final Collection<Thread> getWaitingThreads(ConditionObject condition) {
if (!owns(condition))
throw new IllegalArgumentException("Not owner");
return condition.getWaitingThreads();
}