자바 동시 프로그래밍 -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