ReentrantReadWriteLock寫(xiě)鎖嘗試獲取鎖
protected final boolean tryAcquire(int acquires) {
/*
* Walkthrough:
* 1. If read count nonzero or write count nonzero
* and owner is a different thread, fail.
* 2. If count would saturate, fail. (This can only
* happen if count is already nonzero.)
* 3. Otherwise, this thread is eligible for lock if
* it is either a reentrant acquire or
* queue policy allows it. If so, update state
* and set owner.
*/
Thread current = Thread.currentThread();
// 獲取鎖的狀態(tài)
int c = getState();
// 獲取鎖中寫(xiě)的狀態(tài)
int w = exclusiveCount(c);
/**
* 如果c不為0蝴罪,說(shuō)明鎖已經(jīng)被某個(gè)線(xiàn)程持有每强,當(dāng)然有可能是當(dāng)前線(xiàn)程(重入)。
*/
if (c != 0) {
// (Note: if c != 0 and w == 0 then shared count != 0)
/**
* w == 0, 說(shuō)明沒(méi)有寫(xiě)鎖百揭,即使是當(dāng)前線(xiàn)程持有,無(wú)法獲取到鎖蜒灰,
* 因?yàn)殒i不支持升級(jí)授舟,所以返回false
*
* 走到第二個(gè)條件牡直,說(shuō)明是有寫(xiě)鎖
* 判斷重入:current != getExclusiveOwnerThread()
* 判斷時(shí)否為當(dāng)前線(xiàn)程,如果不是纳决,則返回false
*/
if (w == 0 || current != getExclusiveOwnerThread())
return false;
/**
* 判斷是否大于最大重入次數(shù)碰逸,最大次數(shù):2^16-1
*/
if (w + exclusiveCount(acquires) > MAX_COUNT)
throw new Error("Maximum lock count exceeded");
// Reentrant acquire
// 鎖的次數(shù)+1(state:readLock(16位2進(jìn)制)| writeLock(16位2進(jìn)制))
setState(c + acquires);
return true;
}
/**
* c == 0 沒(méi)有被人持有
* writerShouldBlock()作用:判斷是否需要排隊(duì),通過(guò)隊(duì)列中是否存在線(xiàn)程
* 1.非公平鎖阔加,不管是否有線(xiàn)程排隊(duì)饵史,都返回false(不需要排隊(duì))
* 2.公平鎖,判斷隊(duì)列中是否存在線(xiàn)程胜榔,如果有胳喷,就排隊(duì)。
* (跳過(guò)第二條執(zhí)行夭织,直接返回false)吭露;反之(執(zhí)行第二條語(yǔ)句)
*
* !compareAndSetState(c, c + acquires)作用:獲取鎖,如果獲取不到鎖尊惰,返回false
*/
if (writerShouldBlock() ||
!compareAndSetState(c, c + acquires))
return false;
// 加鎖成功讲竿,把鎖中的線(xiàn)程,設(shè)置為當(dāng)前線(xiàn)程择浊。
setExclusiveOwnerThread(current);
return true;
}