ReentrantLock与AQS
类结构
ReentrantLock实现了Lock, java.io.Serializable这两个接口,里面有三个静态内部类:Sync、NonfairSync和FairSync。其中Sync继承了AbstractQueuedSynchronizer,也就是AQS。另外两个内部类是对抽象类Sync的实现。
加锁
在JDK8中,加锁的流程和JDK11有些区别,JDK8参考美团的代码:
// java.util.concurrent.locks.ReentrantLock#NonfairSync
// 非公平锁
static final class NonfairSync extends Sync {
...
final void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
...
}
// java.util.concurrent.locks.ReentrantLock#FairSync
static final class FairSync extends Sync {
...
final void lock() {
acquire(1);
}
...
}
而在JDK11中,,不管是构建ReentrantLock时,指定的是公平锁还是非公平锁,加锁后都会进入下面的流程:
public void lock() {
sync.acquire(1);
}
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
其中,公平锁和非公平锁对tryAcquire()的实现有一些区别:
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
@ReservedStackAccess
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) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
/**
* Sync object for fair locks
*/
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
/**
* Fair version of tryAcquire. Don't grant access unless
* recursive call or no waiters or is first.
*/
@ReservedStackAccess
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
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;
}
}
可以看出,无论是公平锁还是非公平锁,实现流程都是类似的,只是公平锁需要通过hasQueuedPredecessors()判断当前线程有没有前驱节点,如果有的话就不去抢锁,而是加入等待队列后等待。
排队
再看acquire():
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
当前线程会通过addWaiter()方法变为等待队列上的一个节点,然后这个节点会传入acquireQueued()去执行相应的流程:
private Node addWaiter(Node mode) {
Node node = new Node(mode);
for (;;) {
Node oldTail = tail;
if (oldTail != null) {
node.setPrevRelaxed(oldTail);
if (compareAndSetTail(oldTail, node)) {
oldTail.next = node;
return node;
}
} else {
initializeSyncQueue();
}
}
}
首先新建一个节点,然后采用自旋(for循环)的方式将节点加入等待队列之中。此时会先获取一下队列的尾节点,但是由于此时可能有多个线程在操作这个队列,所以仅仅能把当前节点指向这个获取的尾节点,只有通过CAS(compareAndSetTail)判断并修改尾节点为当前节点后,才能将刚才的尾节点指向当当前节点,否则就一直自旋,直到成功将节点加入队列。如果当前没有尾节点,就要将队列初始化。最终将当前节点返回:
final boolean acquireQueued(final Node node, int arg) {
boolean interrupted = false;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node))
interrupted |= parkAndCheckInterrupt();
}
} catch (Throwable t) {
cancelAcquire(node);
if (interrupted)
selfInterrupt();
throw t;
}
}
自旋判断当前节点的前驱节点是不是头节点,如果是,就去尝试获取锁。如果获取失败或者不是头节点,就判断当前节点是否需要阻塞,也就是当前线程是否需要挂起以避免空转浪费CPU资源。这里注意第7行的setHead(node)方法,实现是这样:
private void setHead(Node node) {
head = node;
node.thread = null;
node.prev = null;
}
因为当前节点的线程已经获取了锁,所以就把当前节点设置为虚节点,把不必要的属性置为null。
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) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
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.
*/
pred.compareAndSetWaitStatus(ws, Node.SIGNAL);
}
return false;
}
/** Marker to indicate a node is waiting in shared mode */
static final Node SHARED = new Node();
/** Marker to indicate a node is waiting in exclusive mode */
static final Node EXCLUSIVE = null;
/** waitStatus value to indicate thread has cancelled. */
static final int CANCELLED = 1;
/** waitStatus value to indicate successor's thread needs unparking. */
static final int SIGNAL = -1;
/** waitStatus value to indicate thread is waiting on condition. */
static final int CONDITION = -2;
/**
* waitStatus value to indicate the next acquireShared should
* unconditionally propagate.
*/
static final int PROPAGATE = -3;
如果前置节点的状态是SIGNAL,就需要将当前线程挂起,其他情况都不挂起。但是由于自旋,这个方法会逐渐将所有空闲线程都挂起。具体流程由parkAndCheckInterrupt()执行:
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
当线程被唤醒后,线程会执行上面代码块的第3行,return这个线程当前的中断状态。
唤醒
public void unlock() {
sync.release(1);
}
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.compareAndSetWaitStatus(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 p = tail; p != node && p != null; p = p.prev)
if (p.waitStatus <= 0)
s = p;
}
if (s != null)
LockSupport.unpark(s.thread);
}
选择去唤醒一个waitStatus状态小于0的节点。为什么倒着遍历呢?因为之前构建等待队列的时候,将当前节点挂在获取的尾节点之后,可能存在多个线程并发的问题,更新尾节点要通过CAS。这时候如果正着遍历就有断链的危险。虽然说倒着遍历,但是最终选择的还是最靠近队列头的节点。
被唤醒的节点重新获取锁:
final boolean acquireQueued(final Node node, int arg) {
boolean interrupted = false;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node))
interrupted |= parkAndCheckInterrupt();
}
} catch (Throwable t) {
cancelAcquire(node);
if (interrupted)
selfInterrupt();
throw t;
}
}
本文来自博客园,作者:imissinstagram,转载请注明原文链接:https://www.cnblogs.com/LostSecretGarden/p/16000972.html

浙公网安备 33010602011771号