部分摘抄自
https://www.cnblogs.com/daydaynobug/p/6752837.html
概述
以JUC locks包中的ReentrantLock为例,其内部有一个对象,并实现了该对象的类是ReentrantLock类中的一个内部类。这是JUC lock的典型实现。AbstractQueuedSynchronizer是设计模式中的模版方法,提供了典型的锁的行为。
private final Sync sync;
abstract static class Sync extends AbstractQueuedSynchronizer {
...
}
AbstractQueuedSynchronizer这个类虽然号称Abstract,但是已经拥有一个完整的锁的实现。
##CLH队列
多线程争用资源时会进入此队列
以ReentrantLock为例,state初始化为0,表示未锁定状态。A线程lock()时,会调用tryAcquire()独占该锁并将state+1。此后,其他线程再tryAcquire()时就会失败,直到A线程unlock()到state=0(即释放锁)为止,其它线程才有机会获取该锁。当然,释放锁之前,A线程自己是可以重复获取此锁的(state会累加),这就是可重入的概念。但要注意,获取多少次就要释放多么次,这样才能保证state是能回到零态的。
private volatile int state;
一个节点表示一个线程,它保存着线程的引用(thread)、状态(waitStatus)、前驱节点(prev)、后继节点(next)
NODE节点的代码段如下
/**
* Status field, taking on only the values:
* SIGNAL: 它的下一个节点接下来需要唤醒(unpack)的线程(-1)
* CANCELLED: 因为线程被中断或者等待超市,节点请求锁处于被取消状态。是节点的终态。(1)节点在处于CANCELLED状态时会被删除
*
* 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.)(-1)
* 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.(-3)
* 0: 表示当前节点正等待在队列中
*
* 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).
*/
volatile int waitStatus;
CLH队列是一个双向队列。
AQS
AQS定义两种资源共享方式:Exclusive(独占,只有一个线程能执行,如ReentrantLock)和Share(共享,多个线程可同时执行,如Semaphore/CountDownLatch)。
sHeldExclusively()//该线程是否正在独占资源。只有用到condition才需要去实现它。
tryAcquire(int)//独占方式。尝试获取资源,成功则返回true,失败则返回false。
tryRelease(int)//独占方式。尝试释放资源,成功则返回true,失败则返回false。
tryAcquireShared(int)//共享方式。尝试获取资源。负数表示失败;0表示成功,但没有剩余可用资源;正数表示成功,且有剩余资源。
tryReleaseShared(int)//共享方式。尝试释放资源,成功则返回true,失败则返回false。
线程的中断机制
如果一个线程处于了阻塞状态(如线程调用了thread.sleep、thread.join、thread.wait、1.5中的condition.await、以及可中断的通道上的 I/O 操作方法后可进入阻塞状态),则在线程在检查中断标示时如果发现中断标示为true,则会在这些阻塞方法(sleep、join、wait、1.5中的condition.await及可中断的通道上的 I/O 操作方法)调用处抛出InterruptedException异常,并且在抛出异常后立即将线程的中断标示位清除,即重新设置为false。抛出异常是为了线程从阻塞状态醒过来,并在结束线程前让程序员有足够的时间来处理中断请求。
aquire流程
//acquire算法是不许覆盖的,所以所有子类都要使用这个方法
public final void acquire(int arg) {
if (!tryAcquire(arg) &&//tryAcquire必须在子类实现,否则就会抛出UnsupportedOperationException异常
//EXCLUSIVE是Node中的一个类字段,初始固定为null
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
//清除中断标志位
selfInterrupt();
}
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
Node pred = tail;
if (pred != null) {//CLH已经进行初始化的状态
node.prev = pred;
//CAS操作追加到队尾
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);//CLH还没进行初始化的状态
return node;
}
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 final boolean parkAndCheckInterrupt() {
LockSupport.park(this);//使用Unsafe机制暂停线程,使用当前对象作为blocker
return Thread.interrupted();
}
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
if (ws > 0) {
//ws大于0表示pred节点已经被取消。删除之。
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
Release流程
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
private void unparkSuccessor(Node node) {
/*
* If status is negative (i.e., possibly needing signal) try
* to clear in anticipation of signalling. It is OK if this
* fails or if status is changed by waiting thread.
*/
int ws = node.waitStatus;
if (ws < 0)
//将node中的WaitStatus原子性的置为0
compareAndSetWaitStatus(node, ws, 0);
/*
* Thread to unpark is held in successor, which is normally
* just the next node. But if cancelled or apparently null,
* traverse backwards from tail to find the actual
* non-cancelled successor.
*/
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);
}
//CAS操作也是采用unsafe包实现的
private static final boolean compareAndSetWaitStatus(Node node,
int expect,
int update) {
return unsafe.compareAndSwapInt(node, waitStatusOffset,
expect, update);
}
ReentrantLock为例
ReentrantLock内部的Sync进一步实现AbstractQueuedSynchronizer的部分留空的逻辑。但是Sync类也是抽象类,FairSync,NonfairSync最终实现了完整逻辑。
Sync类实现了tryRelease的逻辑。就是尝试给state减去releases值,一般为1。
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
NonfairSync和FairSync的主要区别就是在tryAcquire这个方法上。他们也最终提供了lock方法
首先看公平版本
final void lock() {
acquire(1);
}
/**
* Fair version of tryAcquire. Don't grant access unless
* recursive call or no waiters or is first.
*/
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
//如果当前state为0,检查下队列里是否有节点,如果没有,赶紧抢占
if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
//如果发现虽然state不是0,但是就是占有锁的线程就是自己,从容给state+1
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;//一般为1
if (nextc < 0)//最多支持的锁的数量不能超过int的最大值
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
//抢占失败,乖乖去排队
return false;
}
再来对比不公平版本
final void lock() {
//先抢一波
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
//差别就在于不检查队列里是否有其他节点,我就是要抢,管你有没有人排队,抢第二波
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
//仍然抢占失败,乖乖去排队
return false;
}
有timeout的实现
//这是final的方法,子类不能覆盖,是提供给子类的标准模版
public final boolean tryAcquireNanos(int arg, long nanosTimeout)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
return tryAcquire(arg) ||
doAcquireNanos(arg, nanosTimeout);
}
private boolean doAcquireNanos(int arg, long nanosTimeout)
throws InterruptedException {
if (nanosTimeout <= 0L)
return false;
//计算自己的deadline
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;
}
//计算当前到deadline的时间
nanosTimeout = deadline - System.nanoTime();
if (nanosTimeout <= 0L)
return false;
//如果当前时间到dealine的时间超过了spinForTimeoutThreshold,那就不自旋了,直接park
if (shouldParkAfterFailedAcquire(p, node) &&
nanosTimeout > spinForTimeoutThreshold)
LockSupport.parkNanos(this, nanosTimeout);
//检查线程是否被打断
if (Thread.interrupted())
throw new InterruptedException();
}
//java基础:finally语句是在return执行之后,return返回之前执行的
} finally {
//检查标志位,取消节点
if (failed)
cancelAcquire(node);
}
}
共享锁的实现
这篇文章太长了,请看续集【JUC之AQS:共享锁部分】