上文学习了JUC的AQS工具,下面看下可重入显示锁的实现(如何基于AQS),要看ReentrantLock,还是先看下显示锁内部对AQS的几种子类实现。
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;
/**
* Performs {@link Lock#lock}. The main reason for subclassing
* is to allow fast path for nonfair version.
*/
abstract void lock();//lock留给子类实现
/**
* Performs non-fair tryLock. tryAcquire is implemented in
* subclasses, but both need nonfair try for trylock method.
final boolean nonfairTryAcquire(int acquires) {//实现非公平获取
final Thread current = Thread.currentThread();
int c = getState();//AQS的state属性,这里被用来当作锁资源
if (c == 0) {//state在AQS中默认为0,说明此时到达的是第一个线程,尚未有线程修改过state,acquires是要获取的资源数,在互斥锁下为1
if (compareAndSetState(0, acquires)) {//CAS修改state为acquires
setExclusiveOwnerThread(current);//将当前线程赋值给AQS的exclusiveOwnerThread属性
return true;
}
}
else if (current == getExclusiveOwnerThread()) {//state!=0说明已有线程获取了资源,检查AQS的互斥线程是否是线程自身
int nextc = c + acquires;//将请求资源数增加
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);//更改state(未使用cas,因为只有exclusiveOwnerThread可以修改此值)
return true;
}
return false;
}
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())//只有exclusiveOwnerThread当前拥有着才可以release释放
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {//state==0,则当前exclusiveOwnerThread线程已释放所有资源
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
protected final boolean isHeldExclusively() {
// While we must in general read state before owner,
// we don't need to do so to check if current thread is owner
return getExclusiveOwnerThread() == Thread.currentThread();
}
final ConditionObject newCondition() {//条件对象,拥有await和signal等方法,用于条件上的线程阻塞和唤醒
return new ConditionObject();
}
// Methods relayed from outer class
final Thread getOwner() {
return getState() == 0 ? null : getExclusiveOwnerThread();
}
final int getHoldCount() {
return isHeldExclusively() ? getState() : 0;
}
final boolean isLocked() {
return getState() != 0;
}
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
setState(0); // reset to unlocked state
}
}
非公平Sync和公平Sync实现:
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
/**
* Performs lock. Try immediate barge, backing up to normal
* acquire on failure.
*/
final void lock() {
if (compareAndSetState(0, 1))//cas(0,1)返回true则获取成功将此线程设置为exclusiveOwnerThread线程
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);//调用AQS的acquires方法
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);//调用Sync的方法
}
}
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
final void lock() {//公平获取方法,对比非公平的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();
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;
}
}
对于AQS的使用,我们直接从ReentrantLock的lock和unlock方法看起就好
public void lock() {
sync.lock();
}
public void unlock() {
sync.release(1);
}
其实内部的源码,还是我们前面看到的,AQS的内容以及公平和非公平两种子类的实现,ReentrantLock的实现就是调用这些方法。下面上一张我画的图。
线程ABC获取lock,队列的变过程等,以及释放锁的过程。
其中BC都调用了park阻塞自身,然后添加到队尾,当前线程释放锁时,清空exclusiveOwnerThread,并唤醒head的后继,调用unpark。
另外,当A线程运行结束,释放锁之后,唤醒了B节点,这里只是进行了唤醒,却没有任何将head出队的操作,这让我很疑惑,当B线程被唤醒后,去竞争锁失败,岂不是又会将一个包含了B线程的新节点添加到队尾?并且head节点的后继仍然是刚才的B节点?
当B节点线程B被唤醒后,仍然还在循环内,此时直接在acquireQueued内的循环内执行,并不会新增加节点,而当此线程获取成功时,会将head出队,B作为头节点。
这里要感谢高级交流群的广州-浪子,帮我解答了我的问题:
独占模式下,假设现在有 A B C三个线程。
A线程先进来,成功获取锁, tryAcuire = true = !true = false. 此时A线程不需要进入等待队列
B线程进来,tryAcquire= false= !false= true.进入acquireQueued(addWaiter(Node.EXCLUSIVE), arg)
跳过入队
如果B线程被唤醒后,且能成功tryAcuire的话,那么就成功出队。tryAcuire失败的话再次阻塞(为什么会失败?可能他这次被唤醒的资源给别的线程抢去了)