前言
本文从源码来介绍下ReentrantLock的实现细节
源码
话不多说直接上源码,从lock方法开始看 当我们不传参是,默认是NonfairSync,非公平锁,本文只看非公平锁,看懂了非公平锁,则公平锁只是一些细节的差异
public ReentrantLock() {
sync = new NonfairSync();
}
public void lock() {
sync.lock();
}
final void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
上面前半部分可以看出来非公平锁,一进来就尝试去获取锁,这就是非公平锁的特性,可以插队,即使当前有人在排队,我也可以插队
继续看acquire(1)
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
这里要分步骤看了,先看tryAcquire
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
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;
}
也就是tryAcquire主要是再次抢占锁和判断是否当前可以重入的
继续看,当没有抢占到锁则addWaiter(Node.EXCLUSIVE)
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;
}
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) {
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
到这里没有抢占到锁的线程构建成双向Node节点形成了一个链
继续看acquireQueued
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;
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
parkAndCheckInterrupt()方法
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
到这里lock的方法就分析完了
看一下unLock()
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;
}
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;
}
看unparkSuccessor(h)
private void unparkSuccessor(Node node) {
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);
}
当s节点被唤醒后会从之前lock方法里面pack的地方继续往下走,也就是这里
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;
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
到这里源码就看完了,并不是很复杂,其中使用了一个Sync继承了AQS同步器
总结
大致流程:
- state=0没有锁,state=1有线程占用了锁,并且存储了当前线程exclusiveOwnerThread,state>1重入锁,进入了多次
- 每次有线程调用lock,则先cas修改state的值,修改成功或者发现当前线程就是exclusiveOwnerThread则说明重入,那么抢占锁成功,直接返回即可
- 如果抢占锁失败,则构建一个双向的Node链表,并且节点调用LockSupport.park(this)进入阻塞
- unLock之后唤醒head节点的下一个节点,唤醒节点再次去抢占锁,抢占成功则设置state=1和exclusiveOwnerThread,然后返回,失败则再次加入链表的尾部并且阻塞
上文使用了AQS同步器,AQS是一个扩展性非常好的同步器,juc下的很多组件都使用了AQS,基于AQS实现一个我们需要的阻塞唤醒的组件是非常简单的
|