ReentrantLock幾乎擁有了synchronized的一切基本功能,而且它還做了相應(yīng)的擴(kuò)展。比如,它繼承了Lock接口,對(duì)資源的保護(hù)更加精細(xì)化。它是AQS的派生類,同時(shí)支持公平鎖FairSync和非公平鎖NonFairSync兩種鎖模式。它總是以Lock()和unlock()的形式,成對(duì)使用。
private void ReentrantLockDemo() {
ReentrantLock lock = new ReentrantLock();
try {
lock.lock();
Thread.sleep(100);
} catch (InterruptedException e) {
Log.d(TAG,"ReentrantLock#InterruptedException = " + e.getMessage());
} finally {
lock.unlock();
}
}
上面的demo就是我們經(jīng)常用的一種ReentrantLock方式,我們從構(gòu)造方法開(kāi)始分析。
/**
* Creates an instance of {@code ReentrantLock}.
* This is equivalent to using {@code ReentrantLock(false)}.
*/
public ReentrantLock() {
sync = new NonfairSync();
}
默認(rèn)的構(gòu)造方法,生成了一個(gè)非公平鎖,其實(shí)還有一個(gè)構(gòu)造方法可以生成公平鎖。NonfairSync的繼承關(guān)系如下:

NonfairSync是ReentrantLock的內(nèi)部類,繼承了同樣是內(nèi)部類的Sync。這也就不難理解,返回的實(shí)例是Sync了。而Sync又繼承了AbstractQueuedSynchronizer類,也就是我們前面提到的AQS。
請(qǐng)求鎖
demo中調(diào)用了lock.lock()方法,而NonfairSync中正好有對(duì)該方法的實(shí)現(xiàn):
/**
* Performs lock. Try immediate barge, backing up to normal
* acquire on failure.
*/
final void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
方法中直接執(zhí)行鎖操作,這里的同步策略采用的CAS方式,如果設(shè)置成功,代表得到鎖,將當(dāng)前線程設(shè)為獨(dú)占式線程。如果請(qǐng)求失敗,執(zhí)行acquire請(qǐng)求方法。
CAS是一種直接操作JVM內(nèi)存的方式,其工作原理:給出一個(gè)期望值expect與內(nèi)存中的值value進(jìn)行比較,如果兩者相等。說(shuō)明內(nèi)存沒(méi)有被修改過(guò),當(dāng)前線程就可以修改這塊內(nèi)存,寫入自己攜帶的另一個(gè)值expect。這樣內(nèi)存區(qū)被修改后,別的持有expect的線程就無(wú)法修改這塊內(nèi)存,直到當(dāng)前線程釋放掉這塊內(nèi)存,并將其改為持有之前的值為止。
但是需要注意的是,這種方法雖然避免了加鎖造成的時(shí)間浪費(fèi),但是它容易運(yùn)行失敗引起性能問(wèn)題,而且還要通過(guò)AutomicStampedReference處理ABA問(wèn)題
知道了CAS的原理,我們就可以接著分析。compareAndSetState方法實(shí)際上是AbstractQueuedSyncronizer提供的一個(gè)方法,其源碼如下:
/**
* Atomically sets synchronization state to the given updated
* value if the current state value equals the expected value.
* This operation has memory semantics of a {@code volatile} read
* and write.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that the actual
* value was not equal to the expected value.
*/
protected final boolean compareAndSetState(int expect, int update) {
return U.compareAndSwapInt(this, STATE, expect, update);
}
從注釋中我們就可以知道這是CAS的一種實(shí)現(xiàn)方式,內(nèi)存讀寫操作是基于volatile修飾符的操作,換句話說(shuō),能夠保證對(duì)內(nèi)存的可見(jiàn)性和有序性操作。
它真正的操作是Unsafe類的compareAndSwapInt方法。該方法才是可以直接操作JVM內(nèi)存的后門。this代表當(dāng)前對(duì)象,STATE代表的是當(dāng)前對(duì)象的state字段在內(nèi)存中存儲(chǔ)的位置相對(duì)于,對(duì)象起始位置的偏移量。起始位置+偏移量,就是state在內(nèi)存中的保存地址。而state就是我們剛剛在解釋CAS原理時(shí)提到的value這個(gè)值。如果你對(duì)Unsafe和CAS特別感興趣,可以看看這兩篇文章:《Java Unsafe 類》和《Java中Unsafe使用詳解》
我們繼續(xù)說(shuō)剛剛的state字段,它同樣是在AQS中聲明的一個(gè)同步變量,
/**
* The synchronization state.
*/
private volatile int state;
看到了吧,它不但被volatile修飾,而且是private的字段,也許這并沒(méi)有什么稀奇!但是:
/**
* Returns the current value of synchronization state.
* This operation has memory semantics of a {@code volatile} read.
* @return current state value
*/
protected final int getState() {
return state;
}
/**
* Sets the value of synchronization state.
* This operation has memory semantics of a {@code volatile} write.
* @param newState the new state value
*/
protected final void setState(int newState) {
state = newState;
}
但是他的set和get方法全部加了final和protected修飾,換句話用戶想使用它只能在其派生類里,想要覆蓋它門都沒(méi)有。當(dāng)然這也避免了用戶在使用鎖時(shí)調(diào)用修改該狀態(tài),從一定程度上降低了同步操作的復(fù)雜性。
我們接著聊NonfairSync.lock()方法,如果請(qǐng)求鎖成功了,compareAndSetState(0, 1)將state內(nèi)存塊的值設(shè)為1,別的線程就訪問(wèn)不了,那當(dāng)前線程就對(duì)這個(gè)內(nèi)存區(qū)域在一定時(shí)間內(nèi)獨(dú)占,直接調(diào)用AbstractOwnableSynchronizer【注意,不是AQS。它是AQS的父類】的setExclusiveOwnerThread方法將當(dāng)前線程設(shè)置為獨(dú)占線程。
如果請(qǐng)求鎖失敗,compareAndSetState(0, 1)方法返回false,那就通過(guò)調(diào)用AQS#acquire方法繼續(xù)發(fā)起請(qǐng)求。
/**
* Acquires in exclusive mode, ignoring interrupts. Implemented
* by invoking at least once {@link #tryAcquire},
* returning on success. Otherwise the thread is queued, possibly
* repeatedly blocking and unblocking, invoking {@link
* #tryAcquire} until success. This method can be used
* to implement method {@link Lock#lock}.
*
* @param arg the acquire argument. This value is conveyed to
* {@link #tryAcquire} but is otherwise uninterpreted and
* can represent anything you like.
*/
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
該方法以獨(dú)占方式發(fā)起請(qǐng)求鎖,忽略中斷。發(fā)起請(qǐng)求是通過(guò)調(diào)用至少一次tryAcquire方法完成的。如果tryAcquire也請(qǐng)求失敗了,系統(tǒng)就會(huì)把當(dāng)前線程加入到等待隊(duì)列里,這中間可能會(huì)重復(fù)的阻塞和解阻塞,直到調(diào)用tryAcquire請(qǐng)求成功。
step1:調(diào)用tryAcquire。
該方法在ReentrantLock#NonfairSync具體實(shí)現(xiàn),tryAcquire將請(qǐng)求任務(wù)交給了nonfairTryAcquire完成請(qǐng)求。
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
來(lái)看看nonfairTryAcquire方法的源碼:
/**
* 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();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
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;
}
代碼中通過(guò)getState獲取當(dāng)前鎖的狀態(tài),如果是0說(shuō)明鎖空閑將狀態(tài)設(shè)為acquires這個(gè)請(qǐng)求數(shù),并將當(dāng)前線程設(shè)為獨(dú)占線程,請(qǐng)求鎖成功。否則的話,就要對(duì)比當(dāng)前線程current和持有鎖的獨(dú)占線程是否為同一線程,如果是,直接調(diào)用setState()設(shè)置鎖狀態(tài)。如果以上兩個(gè)條件都無(wú)法滿足,不好意思請(qǐng)求鎖失敗。
注意:請(qǐng)求鎖的條件2滿足,請(qǐng)求成功,state = c + acquires。它是大于1的,而且條件2沒(méi)有調(diào)用CAS方法改變state,速度自然快很多。這就是鎖的可重入性!也就是說(shuō)同一個(gè)Thread聯(lián)系調(diào)用了N次lock,一旦獲取鎖成功,后續(xù)請(qǐng)求鎖state依次疊加不用排隊(duì)競(jìng)爭(zhēng)。同樣,每一個(gè)lock都要對(duì)應(yīng)一個(gè)unlock的調(diào)用。
那么問(wèn)題來(lái)了,可重入鎖可以被一個(gè)線程獨(dú)占state次,那些沒(méi)有獲取到鎖的線程怎么辦?
step2:排隊(duì)等待。
對(duì)于暫時(shí)無(wú)法獲取到鎖的線程,調(diào)用tryAcquire必然返回false,代碼就要執(zhí)行acquireQueued方法,該方法是通過(guò)addWaiter(Node.EXCLUSIVE)方法傳入了一個(gè)獨(dú)占式final節(jié)點(diǎn)。我們先來(lái)看看Node節(jié)點(diǎn):
- 該節(jié)點(diǎn)構(gòu)成的等待隊(duì)列是一個(gè)“CLH(Craig, Landin, and Hagersten)”鎖隊(duì)列的變體,CLH鎖隊(duì)列通常用于自旋鎖。Node僅使用其基本功能,并作了相應(yīng)的改造。
- Node有兩個(gè)字段prev和next分別指向節(jié)點(diǎn)的前任節(jié)點(diǎn)和后續(xù)節(jié)點(diǎn),足見(jiàn)這是一個(gè)雙向鏈表。
- Node在首次構(gòu)造時(shí),會(huì)創(chuàng)建一個(gè)啞結(jié)點(diǎn)作為頭結(jié)點(diǎn)。
- Node構(gòu)成的等待隊(duì)列既有頭節(jié)點(diǎn),又有尾節(jié)點(diǎn)。在入隊(duì)時(shí),僅僅把新節(jié)點(diǎn)拼接作為尾節(jié)點(diǎn)。出隊(duì)時(shí),僅僅設(shè)置頭節(jié)點(diǎn)。
- Node提供了一個(gè)waitStatus代表當(dāng)前節(jié)點(diǎn)的等待狀態(tài):
CANCELLED==1,因?yàn)槌瑫r(shí)或中斷等,線程取消了鎖請(qǐng)求;
SIGNAL==-1,表示繼任節(jié)點(diǎn)被阻塞,當(dāng)前節(jié)點(diǎn)在釋放鎖或取消時(shí)需要通知它的繼任節(jié)點(diǎn)解除等待,發(fā)起鎖請(qǐng)求;
CONDITION==-2,節(jié)點(diǎn)當(dāng)前處于一個(gè)競(jìng)爭(zhēng)隊(duì)列里,不能用于同步隊(duì)列,直到狀態(tài)發(fā)生變化;
PROPAGATE==-3,用于共享模式,通知其他節(jié)點(diǎn);
0,以上狀態(tài)都不是。 - Node支持SHARED和EXCLUSIVE兩種模式的節(jié)點(diǎn),通過(guò)nextWaiter字段存儲(chǔ)模式值。
- thread:存貯當(dāng)前線程
- 所有字段均被volatile修飾,保證內(nèi)存操作的可見(jiàn)性和有序性
知道了節(jié)點(diǎn)的功能,我們就可以繼續(xù)分析addWaiter(Node.EXCLUSIVE)方法了,源碼如下:
/**
* Creates and enqueues node for current thread and given mode.
*
* @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
* @return the new node
*/
private Node addWaiter(Node mode) {
Node node = new Node(mode); // 代碼1
for (;;) { // 代碼2
Node oldTail = tail;
if (oldTail != null) { // 代碼3
U.putObject(node, Node.PREV, oldTail);
if (compareAndSetTail(oldTail, node)) {
oldTail.next = node;
return node;
}
} else { // 代碼4
initializeSyncQueue();
}
}
}
該方法毫不含糊,直接表明通過(guò)當(dāng)前線程和指定的模式創(chuàng)建和入隊(duì)節(jié)點(diǎn)。
代碼1處,通過(guò)Node構(gòu)造方法創(chuàng)建了一個(gè)目標(biāo)節(jié)點(diǎn)node,構(gòu)造方法如下:
/** Constructor used by addWaiter. */
Node(Node nextWaiter) {
this.nextWaiter = nextWaiter;
U.putObject(this, THREAD, Thread.currentThread());
}
nextWaiter就是我們傳入的請(qǐng)求模式EXCLUSIVE,當(dāng)前線程被保存到Node的thread字段中。
由于等待隊(duì)列是一個(gè)雙向鏈表,代碼2處通過(guò)一個(gè)無(wú)限for循環(huán)輪詢鏈表,而進(jìn)入等待隊(duì)列的當(dāng)前節(jié)點(diǎn)是第一次使用隊(duì)列,代碼3處oldTail自然是null,代碼4處的initializeSyncQueue()方法被執(zhí)行。看看整個(gè)方法的源碼:
/**
* Initializes head and tail fields on first contention.
*/
private final void initializeSyncQueue() {
Node h;
if (U.compareAndSwapObject(this, HEAD, null, (h = new Node())))
tail = h;
}
好簡(jiǎn)單有木有,直接創(chuàng)建一個(gè)啞結(jié)點(diǎn)(設(shè)為h)作為當(dāng)前隊(duì)列的頭結(jié)點(diǎn),由于目前只有一個(gè)節(jié)點(diǎn)所有head、tail這兩個(gè)頭尾指針都指向它。對(duì)了,你是不是一直疑惑,volatile不支持原子性操作,為啥能賦值對(duì)象?答案是CAS操作是原子性的。
繼續(xù)回到addWaiter方法的代碼2,循環(huán)繼續(xù)。此時(shí)oldTail = tail不再為null,代碼3處的條件為真, U.putObject(node, Node.PREV, oldTail);這一行代碼的意思是:把我們剛剛創(chuàng)建的持有當(dāng)前線程的目標(biāo)節(jié)點(diǎn)node的prev字段用oldTail賦值。由于oldTail指向啞結(jié)點(diǎn)h,那么node.prev = 啞結(jié)點(diǎn)。接著調(diào)用compareAndSetTail(oldTail, node)方法將目標(biāo)節(jié)點(diǎn)node設(shè)為尾節(jié)點(diǎn)。如果設(shè)置成功,oldTail也就是啞結(jié)點(diǎn)或者當(dāng)前的頭結(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)next就是我們剛剛創(chuàng)建的目標(biāo)節(jié)點(diǎn)node,這一步是通過(guò)oldTail.next = node完成的。
這樣,當(dāng)前線程所在節(jié)點(diǎn)node插入等待隊(duì)列測(cè)操作就完成了。
如果這個(gè)時(shí)候,又來(lái)了新的線程thread2、thread3……他們都會(huì)被依次插入隊(duì)列中等待。
節(jié)點(diǎn)創(chuàng)建好了,什么時(shí)候調(diào)用呢?還記得我們的acquireQueued(addWaiter(Node.EXCLUSIVE), arg)方法嗎?它就是用來(lái)發(fā)起二次鎖請(qǐng)求的。源碼如下:
/**
* Acquires in exclusive uninterruptible mode for thread already in
* queue. Used by condition wait methods as well as acquire.
*
* @param node the node
* @param arg the acquire argument
* @return {@code true} if interrupted while waiting
*/
final boolean acquireQueued(final Node node, int arg) {
try {
boolean interrupted = false;
for (;;) { // 代碼1
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) { // 代碼2
setHead(node);
p.next = null; // help GC
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt()) // 代碼3
interrupted = true;
}
} catch (Throwable t) {
cancelAcquire(node);
throw t;
}
}
代碼1處,通過(guò)一個(gè)for循環(huán)不間斷的發(fā)起請(qǐng)求。代碼2有兩個(gè)條件,雖然條件1目前滿足p == head。但是條件2tryAcquire在鎖被占用的情況下是無(wú)法請(qǐng)求成功的。
代碼走入代碼3的邏輯,同樣有兩個(gè)條件:shouldParkAfterFailedAcquire(p, node) 和parkAndCheckInterrupt()。
- **shouldParkAfterFailedAcquire(p, node) **
/**
* Checks and updates status for a node that failed to acquire.
* Returns true if thread should block. This is the main signal
* control in all acquire loops. Requires that pred == node.prev.
*
* @param pred node's predecessor holding status
* @param node the node
* @return {@code true} if thread should block
*/
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
pred.compareAndSetWaitStatus(ws, Node.SIGNAL);
}
return false;
}
該方法是用來(lái)核對(duì)和修改請(qǐng)求鎖失敗的線程的等待狀態(tài)waitStatus的,由于外層的for循環(huán)和acquire獲取鎖失敗,所以pred節(jié)點(diǎn)也就是當(dāng)前節(jié)點(diǎn)的前一個(gè)節(jié)點(diǎn)的狀態(tài)必然會(huì)被改為SIGNAL,并且返回true。而Node節(jié)點(diǎn)被設(shè)置為SIGNAL就是為了告訴持有鎖的線程,釋放鎖時(shí)請(qǐng)喚醒隊(duì)列中擁有SIGNAL狀態(tài)的節(jié)點(diǎn)的繼任節(jié)點(diǎn)線程。整個(gè)繼任在掛起狀態(tài)。
條件2 parkAndCheckInterrupt
既然繼任線程設(shè)置了鬧鐘,他就高枕無(wú)憂了,系統(tǒng)是通過(guò)parkAndCheckInterrupt方法來(lái)完成掛起線程的。源碼如下:
/**
* Convenience method to park and then check if interrupted.
*
* @return {@code true} if interrupted
*/
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
當(dāng)前線程先通過(guò)LockSupport.park(this)方法掛起,通常只有LockSupport.unpark方法或中斷才能把它喚醒,然后執(zhí)行Thread.interrupted()中斷操作。
park方法的源碼如下:
/**
* Disables the current thread for thread scheduling purposes unless the
* permit is available.
*
* <p>If the permit is available then it is consumed and the call returns
* immediately; otherwise
* the current thread becomes disabled for thread scheduling
* purposes and lies dormant until one of three things happens:
*
* <ul>
* <li>Some other thread invokes {@link #unpark unpark} with the
* current thread as the target; or
*
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* the current thread; or
*
* <li>The call spuriously (that is, for no reason) returns.
* </ul>
*
* <p>This method does <em>not</em> report which of these caused the
* method to return. Callers should re-check the conditions which caused
* the thread to park in the first place. Callers may also determine,
* for example, the interrupt status of the thread upon return.
*
* @param blocker the synchronization object responsible for this
* thread parking
* @since 1.6
*/
public static void park(Object blocker) {
Thread t = Thread.currentThread();
setBlocker(t, blocker);
U.park(false, 0L);
setBlocker(t, null);
}
注意它仍然是通過(guò)Unsafe方法直接操作JVM內(nèi)存將線程刮起,0L代表無(wú)限掛起。
Thread.interrupted()不但可以判斷當(dāng)前線程是否中斷,而且可以清除中斷狀態(tài)。如果連續(xù)調(diào)用偶數(shù)次該方法,相當(dāng)于沒(méi)有調(diào)用。另外,如果線程已經(jīng)處于中斷狀態(tài),該方法返回true,否則返回false。所以,parkAndCheckInterrupt方法第一次調(diào)用會(huì)返回false,使得acquireQueued繼續(xù)循環(huán)調(diào)用tryAcquire(arg)方法獲取鎖。
釋放鎖
整個(gè)請(qǐng)求鎖的邏輯,到此就算告一段落了。那么,要想請(qǐng)求成功,持有當(dāng)前鎖的線程必須執(zhí)行ReentrantLock#unlock方法,釋放鎖。源碼如下:
/**
* Attempts to release this lock.
*
* <p>If the current thread is the holder of this lock then the hold
* count is decremented. If the hold count is now zero then the lock
* is released. If the current thread is not the holder of this
* lock then {@link IllegalMonitorStateException} is thrown.
*
* @throws IllegalMonitorStateException if the current thread does not
* hold this lock
*/
public void unlock() {
sync.release(1);
}
看看人家怎么說(shuō)的,如果當(dāng)前線程是鎖的持有者,持有的數(shù)量減1,接著看AQS#release的源碼:
/**
* Releases in exclusive mode. Implemented by unblocking one or
* more threads if {@link #tryRelease} returns true.
* This method can be used to implement method {@link Lock#unlock}.
*
* @param arg the release argument. This value is conveyed to
* {@link #tryRelease} but is otherwise uninterpreted and
* can represent anything you like.
* @return the value returned from {@link #tryRelease}
*/
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
以獨(dú)占模式釋放鎖,如果tryRelease方法返回true,等待隊(duì)列中的頭結(jié)點(diǎn)的繼任節(jié)點(diǎn)會(huì)被喚醒。ReentrantLock#tryRelease的源碼如下:
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
沒(méi)什么新鮮的,就是通過(guò)getState和setState設(shè)置鎖的狀態(tài),當(dāng)state為0時(shí),說(shuō)明鎖被徹底釋放,等待隊(duì)列中線程可以訪問(wèn)鎖。
一旦鎖釋放成功。release方法就會(huì)執(zhí)行,unparkSuccessor(h);代碼喚醒繼任節(jié)點(diǎn)中的線程。源碼如下:
/**
* Wakes up node's successor, if one exists.
*
* @param node the node
*/
private void unparkSuccessor(Node node) {
/*
* If status is negative (i.e., possibly needing signal) try
* to clear in anticipation of signalling. It is OK if this
* fails or if status is changed by waiting thread.
*/
int ws = node.waitStatus;
if (ws < 0)
node.compareAndSetWaitStatus(ws, 0);
/*
* Thread to unpark is held in successor, which is normally
* just the next node. But if cancelled or apparently null,
* traverse backwards from tail to find the actual
* non-cancelled successor.
*/
Node s = node.next;
if (s == null || s.waitStatus > 0) {
s = null;
for (Node p = tail; p != node && p != null; p = p.prev)
if (p.waitStatus <= 0)
s = p;
}
if (s != null)
LockSupport.unpark(s.thread);
}
代碼中寫的很清晰,如果頭節(jié)點(diǎn)的等待狀態(tài)waitStatus是負(fù)值,比如SIGNAL,就把置為0還原。通常情況下,頭結(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)就是繼任節(jié)點(diǎn)successer,但是如果該節(jié)點(diǎn)取消等待了或者值為null,就通過(guò)反向從tail尾節(jié)點(diǎn)查找的辦法,找到待喚醒的節(jié)點(diǎn)s。其中,喚醒任務(wù)是LockSupport.unpark(s.thread);來(lái)完成的。
這樣,被喚醒的線程就可以通過(guò)acquire方法獲取到鎖了。
公平鎖
我們上面分析的加鎖和釋放鎖都是基于NonfairSync這把非公平鎖的,那么公平鎖FairSync到底公平在何處?其實(shí)主要是tryAcquire方法的實(shí)現(xiàn)不一樣:
NonfairSync#nonfairTryAcquire
/**
* 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();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
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;
}
FairSync#tryAcquire源碼
/**
* 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;
}
}
注意:在請(qǐng)求鎖的過(guò)程中,公平鎖多了AQS的hasQueuedPredecessors()方法的判斷,該方法源碼如下:
/**
* Queries whether any threads have been waiting to acquire longer
* than the current thread.
*
* <p>An invocation of this method is equivalent to (but may be
* more efficient than):
* <pre> {@code
* getFirstQueuedThread() != Thread.currentThread()
* && hasQueuedThreads()}</pre>
*
* <p>Note that because cancellations due to interrupts and
* timeouts may occur at any time, a {@code true} return does not
* guarantee that some other thread will acquire before the current
* thread. Likewise, it is possible for another thread to win a
* race to enqueue after this method has returned {@code false},
* due to the queue being empty.
*
* <p>This method is designed to be used by a fair synchronizer to
* avoid <a href="AbstractQueuedSynchronizer.html#barging">barging</a>.
* Such a synchronizer's {@link #tryAcquire} method should return
* {@code false}, and its {@link #tryAcquireShared} method should
* return a negative value, if this method returns {@code true}
* (unless this is a reentrant acquire). For example, the {@code
* tryAcquire} method for a fair, reentrant, exclusive mode
* synchronizer might look like this:
*
* <pre> {@code
* protected boolean tryAcquire(int arg) {
* if (isHeldExclusively()) {
* // A reentrant acquire; increment hold count
* return true;
* } else if (hasQueuedPredecessors()) {
* return false;
* } else {
* // try to acquire normally
* }
* }}</pre>
*
* @return {@code true} if there is a queued thread preceding the
* current thread, and {@code false} if the current thread
* is at the head of the queue or the queue is empty
* @since 1.7
*/
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;
return h != t &&
((s = h.next) == null || s.thread != Thread.currentThread());
}
該方法檢查隊(duì)列中是否存在等待獲取鎖的線程,比當(dāng)前線程的等待時(shí)間還長(zhǎng)。注意(s = h.next) == null這句代碼,它表示隊(duì)列中剛?cè)腙?duì)了一個(gè)新的等待節(jié)點(diǎn)node,只是還未賦值給head.next。
通過(guò)該方法可以防止如下非公平現(xiàn)象的發(fā)生:如果一個(gè)新的線程發(fā)起請(qǐng)求的時(shí)刻,正好當(dāng)前持有鎖的線程釋放了鎖,那對(duì)于正在喚醒的等待了很長(zhǎng)時(shí)間的線程是不公平的。
但是,使用公平鎖比較耗性能,兩害相侵取其輕,官方把非公平鎖作為ReentrantLock的默認(rèn)鎖,說(shuō)明這種非公平情況在大部分情況下是可以接受的。
AQS作為一種工具,除了能夠?qū)崿F(xiàn)ReentrantLock之外,還實(shí)現(xiàn)了CyclicBarrier、CountdownLatch、ReentrantReadWriteLock、ThreadPoolExecutor.Worker、Semaphore等。此外,它還提供了可以代替wait/notify的Condition接口封裝,后期我們逐一分析。