ReentrantLock
类信息
- 内部抽象类:Sync 继承 AbstractQueuedSynchronizer
- 内部类:非公平锁:NonfairSync 继承 Sync
加锁过程
lock():CAS修改同步状态 成功则设置exclusiveOwnerThread为当前线程,然后执行业务,失败则调用acquire(1);
final void lock() {
//设置AbstractQueuedSynchronizer的state为1
if (compareAndSetState(0, 1))
//成功后设置AbstractOwnableSynchronizer的thread为当前线程
setExclusiveOwnerThread(Thread.currentThread());
else
//失败时线程阻塞
acquire(1);
}
acquire(1): AbstractQueuedSynchronizer中的方法,执行tryAcquire(1),acquireQueued(Node, 1),addWaiter(Node.EXCLUSIVE),接下来依次看这三个方法;
public final void acquire(int arg) {
//尝试获取锁,如果获取成功则已,不成功则加入等待队列
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
tryAcquire(1):执行nonfairTryAcquire(acquires),即Sync类的方法nonfairTryAcquire
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
nonfairTryAcquire(acquires):非公平锁获取
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
//再次获取同步状态,如果是0则获取锁执行
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
/**
* 如果是当前线程是已经获取锁的线程
* 让某个线程可以多次调用同一个ReentrantLock,每调用一次给state+1,
* 由于某个线程已经持有了锁,所以这里不会有竞争,
* 因此不需要利用CAS设置state(相当于一个偏向锁)。从这段代码可以看到,nextc每次加1,
* 当nextc<0的时候抛出error,那么同一个锁最多能重入Integer.MAX_VALUE次,也就是2147483647。
*/
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;
}
addWaiter(Node.EXCLUSIVE):AbstractQueuedSynchronizer中的方法,为当前线程和指定模式创建并扩充一个等待队列。Node.EXCLUSIVE标记表示节点正在独占模式下等待
private Node addWaiter(Node mode) {
//为当前线程创建一个等待节点
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
//将需要等待的线程加入到等待队列,如果没有队列则新建执行enq
//查看等待队列的尾部节点是否为空
Node pred = tail;
if (pred != null) {
//设置当前线程的节点为尾节点,扩充队列,并返回当前线程节点
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
enq(node):判断尾节点是否为空,为空则初始化头尾节点(如果尾节点为空,则头节点一定为空,头节点为懒加载,只有队列中插入第一个节点时才初始化),否则插入新节点
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
acquireQueued(Node, 1):加入队列的节点再次尝试获取锁,否则进入阻塞状态
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;
}
//如果获取不到锁
// 1、shouldParkAfterFailedAcquire:判断是否进入阻塞,进入等待
// 2、parkAndCheckInterrupt 进入等待,中断线程
// 条件满足时,修改中断状态,再次进入循环获取锁
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
shouldParkAfterFailedAcquire(p, node):判断是否进入阻塞或者进入等待,通过判断当前节点的前驱节点状态,如果是SIGNAL表示自己被阻塞,返回true;如果小于0,则表示前驱节点为取消状态,跳过,直到链接到不是取消状态的节点,返回false;如果两种都不符合,则通过CAS修改前驱节点状态为Node.SIGNAL,返回false.
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 {
//跳过状态值为1的Node节点
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;
}
parkAndCheckInterrupt():
//禁用当前线程进入等待状态并中断线程本身
private final boolean parkAndCheckInterrupt() {
//除非许可证可用,否则禁用当前线程以进行线程调度。
LockSupport.park(this);
return Thread.interrupted();
}
cancelAcquire(node):如果发生异常,取消正在进行的Node获取锁的尝试
private void cancelAcquire(Node node) {
// Ignore if node doesn't exist
if (node == null)
return;
node.thread = null;
// Skip cancelled predecessors
//跳过取消的前驱节点
Node pred = node.prev;
while (pred.waitStatus > 0)
node.prev = pred = pred.prev;
// predNext is the apparent node to unsplice. CASes below will
// fail if not, in which case, we lost race vs another cancel
// or signal, so no further action is necessary.
Node predNext = pred.next;
// Can use unconditional write instead of CAS here.
// After this atomic step, other Nodes can skip past us.
// Before, we are free of interference from other threads.
//设置此节点的状态为CANCELLED,代表取消状态
node.waitStatus = Node.CANCELLED;
// If we are the tail, remove ourselves.
//如果node是tail,更新tail为pred,并使pred.next指向null
if (node == tail && compareAndSetTail(node, pred)) {
compareAndSetNext(pred, predNext, null);
} else {
// If successor needs signal, try to set pred's next-link
// so it will get one. Otherwise wake it up to propagate.
//如果node既不是tail,又不是head的后继节点
//则将node的前继节点的waitStatus置为SIGNAL
//并使node的前继节点指向node的后继节点(相当于将node从队列中删掉了)
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 {
//如果node是head的后继节点,则直接唤醒node的后继节点
//唤醒后继节点线程后,在做出队操作时将node节点删除
unparkSuccessor(node);
}
node.next = node; // help GC
}
}