java并发编程—ReentrantLock公平锁实现原理
如果一个线程组里,能保证每个线程都能拿到锁,那么这个锁就是公平锁。相反,如果保证不了每个线程都能拿到锁,也就是存在有线程饿死,那么这个锁就是非公平锁。
先看非公平锁
static final class NonfairSync extends Sync {
final void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
非公平锁最后调用nonfairTryAcquire方法
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
//如果还没有获得锁
if (c == 0) {
//尝试用cas获得,这里体现了非公平性:不去检查AQS队列
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
//如果已经获得了锁,线程还是当前线程,表示发生`static final class FairSync extends Sync {了锁重入
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;
}
公平锁的实现
static final class FairSync extends Sync {
final void lock() {
acquire(1);
}
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
//与非公平锁主要区别在于tryAcquire方法的实现
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
//先检查AQS队列中是否有前驱节点,没有才去竞争
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()
不成立才会去调用compareAndSetState
,去抢线程。如果hasQueuedPredecessors()
成立,相当于队列中有其他的线程,下面的compareAndSetState
就不会执行。
注意&&
是短路运算。
//判断队列中是否有一个前驱的节点
public final boolean hasQueuedPredecessors() {
Node t = tail; // Read fields in reverse initialization order
Node h = head;
Node s;
// h != t 时表示队列中有Node
return h != t &&
//情况一,(s = h.next) == null 表示队列中还没有老二
//情况二,队列中老二线程不是此线程
((s = h.next) == null || s.thread != Thread.currentThread());
}
头不等于尾,队列中有节点。
队列中还没有老二,队列中老二线程不是此线程,则返回true
。
这说明队列中有优先级比你高的线程在等待,则不会往下去执行竞争锁compareAndSetState(0, acquires))
。
参考资料
http://www.codeceo.com/article/reentrantlock-learn.html