通过看重入锁对AQS看法有感
AQS队列入队的时候,这个过程是需要保证原子性的,这个原子性是通过CAS完成的。
方法java.util.concurrent.locks.AbstractQueuedSynchronizer#addWaiter
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
// 这个地方是判断当前进来的节点是否是尾节点,是的话就将当前自己的next指针指向自己,返回
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
方法java.util.concurrent.locks.AbstractQueuedSynchronizer#enq
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
// cas让自己成为队列头
if (compareAndSetHead(new Node()))
tail = head;
} else {
// cas让自己成为队列尾,next指针指向自己
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
公平锁状态state,也是通过CAS跟自旋去完成的,这个有意思的是这个tryAcquire的方法是下放到ReentrantLock去做的,开闭原则保证就很好
java.util.concurrent.locks.ReentrantLock.FairSync#tryAcquire
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
// 这个地方就是CAS去做了
if (!hasQueuedPredecessors() &&
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;
}
}
AQS加锁的核心逻辑
方法java.util.concurrent.locks.AbstractQueuedSynchronizer#doAcquireNanos
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;
// 这个地方有意思,当前节点决定是否进入睡眠,
// 重点是shouldParkAfterFailedAcquire方法
if (shouldParkAfterFailedAcquire(p, node) &&
nanosTimeout > spinForTimeoutThreshold)
LockSupport.parkNanos(this, nanosTimeout);
// 中断异常
if (Thread.interrupted())
throw new InterruptedException();
}
} finally {
// 这一步也是至关重要,如果获取到锁了,那就取消竞争状态
if (failed)
cancelAcquire(node);
}
}
检查状态,决定是否唤醒
java.util.concurrent.locks.AbstractQueuedSynchronizer#shouldParkAfterFailedAcquire
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
// 前驱节点过是等待状态,那就返回true,当前节点进入睡眠
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
return true;
// 前驱节点如果是大于0的状态,就是前驱节点已经放弃竞争了,那么就会将当前节点一直往前怼。这个地方其实涉及到多个节点同时处理的情况(但是已经排好队了,就不会出现节点错乱的问题。)
if (ws > 0) {
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
}
// 这个地方就是,将前驱节点的状态改成waitStatus等待
else {
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
AQS的cancelAcquire,如果当前节点自旋超时后没有获取到锁,会执行这个方法
java.util.concurrent.locks.AbstractQueuedSynchronizer#cancelAcquire
// 执行这个方法,意味着当前线程要放弃获取锁了
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 {
// 前驱不是头节点,前驱节点的状态是竞争状态,而且节点里面的线程不为空,进入f
int ws;
if (pred != head &&
((ws = pred.waitStatus) == Node.SIGNAL ||
(ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
pred.thread != null) {
// 这个地方就是判断node节点的子节点,如果处于竞争状态,就将其重新链上pred节点
Node next = node.next;
if (next != null && next.waitStatus <= 0)
compareAndSetNext(pred, predNext, next);
} else {
// 这个地方就是唤醒node的下一个节点,修改node的状态
unparkSuccessor(node);
}
// 回收node节点,竞争失败
node.next = node; // help GC
}
}
接着上述cancelAcquire方法的外部调用unparkSuccessor
java.util.concurrent.locks.AbstractQueuedSynchronizer#unparkSuccessor
private void unparkSuccessor(Node node) {
// 修改状态为0,实际上为什么要设置0呢
// 从AQS上看到,不少if (t.waitStatus <= 0)这种条件判断为可以跳过的节点
// 其实可以理解为在其他线程上,能加速这个节点断开在整个等待队列上
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);
// 从尾节点搜索,找到离node最近的一个竞争节点,唤醒这个节点的线程
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);
}
ReentrantLock又是如何实现公平与非公平锁的
实际上,公平锁就是每次都老老实实进去到AQS的等待队列排队,非公平锁就是开始先cas获取,获取失败后才进入队列排队
首先新建的ReentrantLock时候,传入一个boolean,这个值就是判断是否是公平锁
// sync对象是继承了AQS的ReentrantLock内部类
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
最最核心的就是,公平锁进来就先排队,判断节点,非公平锁进来就是先cas获取锁状态,不行再排队
// 公平锁尝试获取状态
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
// 先判断前驱节点,再进行cas获取
if (!hasQueuedPredecessors() &&
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;
}
// 非公平锁尝试获取锁状态
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
// 非公平锁上来就先cas获取,获取不到后再入队列
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
解锁操作
解锁其实就非常好理解了,调整当前节点状态为解锁,设置拥有线程为空,但没有删除自身的节点(具体节点清除其实是在加锁的时候做的)。然后唤醒下个等待队列中还继续竞争的节点。
java.util.concurrent.locks.AbstractQueuedSynchronizer#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;
}
java.util.concurrent.locks.ReentrantLock.Sync#tryRelease
// 这个方法就是调整当前节点的状态,释放线程
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;
}
java.util.concurrent.locks.AbstractQueuedSynchronizer#unparkSuccessor
// 唤醒下个竞争线程的方法
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)
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);
}