
ReentrantLock.png
FairSync
lock
final void lock() {
// 可以跟非公平鎖做對比,這里會去調(diào)用acquire來通過公平原則來加鎖
acquire(1);
}
tryAcquire
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
// 等于0,說明鎖還沒有被其他線程持有
if (c == 0) {
// 當(dāng)hasQueuedPredecessors為false的情況才會去拿鎖,也就是隊(duì)列中第一個(gè)等待的當(dāng)前線程
if (!hasQueuedPredecessors() &&
// 設(shè)置狀態(tài),并綁定持有人為當(dāng)前線程
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
// 下面是重入鎖的處理,如果是當(dāng)前線程持有,重入計(jì)數(shù)累加
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
public final boolean hasQueuedPredecessors() {
// The correctness of this depends on head being initialized
// before tail and on head.next being accurate if the current
// thread is first in queue.
Node t = tail; // Read fields in reverse initialization order
Node h = head;
Node s;
// 而這里返回false的情況也就兩種
// 1. head=tail,說明隊(duì)列還沒有waiter
// 2. 隊(duì)列中有waiter,且當(dāng)前線程是第一個(gè)
return h != t &&
((s = h.next) == null || s.thread != Thread.currentThread());
}
NonfairSync
lock
final void lock() {
// 非公平鎖的意義在于,誰先來,誰搶鎖。所以,這里一上來直接試著搶鎖,如果能搶到,最好不過了。
// 直接設(shè)置為當(dāng)前線程
// 如果沒搶到,那沒辦法,走非公平鎖的正常流程
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
tryAcquire
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
// 等于0,說明鎖還沒有被其他線程持有
if (c == 0) {
// 可以跟公平鎖比較下,這里不會去看是否是隊(duì)列的第一個(gè),直接去拿鎖,誰先拿到誰獨(dú)占
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
// 下面還是重入鎖的計(jì)數(shù)邏輯
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;
}
tryRelease
protected final boolean tryRelease(int releases) {
// 重入計(jì)數(shù)自減
int c = getState() - releases;
// 如果持有人不是當(dāng)前線程,當(dāng)然也就沒有資格釋放鎖,報(bào)異常
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
// 如果重入計(jì)數(shù)歸零,說明該鎖已經(jīng)完成釋放,清理現(xiàn)場
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
// 更新state
setState(c);
return free;
}