Java中已知的鎖有兩種贰军,一種是synchronized塑悼,另一種是Lock馋嗜;這兩種的基本原理在之前的文章中已經(jīng)做了分析:
這次我們從最常用的Lock也就是ReentrantLock的Acquire和Release鎖的過(guò)程入手辐啄,一步一步的跟源代碼,探究獲取鎖和釋放鎖的步驟景鼠。
獲取鎖
ReentrantLock lock=new ReentrantLock();
lock.lock();
1.lock()
上面代碼是我們常用的獲取鎖的方式:調(diào)用ReentrantLock 的lock()方法仲翎,默認(rèn)情況下ReentrantLock是一個(gè)非公平鎖,類名NonfairSync莲蜘,屬于ReentrantLock的內(nèi)部類谭确,我們來(lái)看源碼:
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
/**
* 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);
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
這里的lock方法先去通過(guò)CAS操作將state的值從0變?yōu)?,(注:ReentrantLock用state表示“持有鎖的線程已經(jīng)重復(fù)獲取該鎖的次數(shù)”票渠。當(dāng)state等于0時(shí)逐哈,表示當(dāng)前沒(méi)有線程持有鎖),如果成功问顷,就設(shè)置ExclusiveOwnerThread的值為當(dāng)前線程(Exclusive是獨(dú)占的意思昂秃,ReentrantLock用exclusiveOwnerThread表示“持有鎖的線程”)禀梳。
如果設(shè)置失敗,說(shuō)明state>0已經(jīng)有線程持有了鎖肠骆,此時(shí)執(zhí)行acquire(1)再請(qǐng)求一次鎖算途。
2.acquire()
/**
* 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();
}
這里我們注意一下acquire方法上面的注釋,已經(jīng)說(shuō)得很清楚了蚀腿,這里我大概說(shuō)下我的理解:
請(qǐng)求獨(dú)占鎖嘴瓤,忽略所有中斷,至少執(zhí)行一次tryAcquire莉钙,如果成功就返回廓脆,否則線程進(jìn)入阻塞--喚醒兩種狀態(tài)切換中,直到tryAcquire成功磁玉。
我們對(duì)里面的tryAcquire()停忿,、addWaiter()蚊伞、acquireQueued()挨個(gè)分析席赂。
在這個(gè)方法里先執(zhí)行tryAcquire(arg):
3.tryAcquire()
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;
}
先判斷state是否為0,如果為0就執(zhí)行上面提到的lock方法的前半部分时迫,通過(guò)CAS操作將state的值從0變?yōu)?颅停,否則判斷當(dāng)前線程是否為exclusiveOwnerThread,然后把state++别垮,也就是重入鎖的體現(xiàn)便监,我們注意前半部分是通過(guò)CAS來(lái)保證同步扎谎,后半部分并沒(méi)有同步的體現(xiàn)碳想,原因是:
后半部分是線程重入,再次獲得鎖時(shí)才觸發(fā)的操作毁靶,此時(shí)當(dāng)前線程擁有鎖胧奔,所以對(duì)ReentrantLock的屬性操作是無(wú)需加鎖的。
如果tryAcquire()獲取失敗预吆,則要執(zhí)行addWaiter()向等待隊(duì)列中添加一個(gè)獨(dú)占模式的節(jié)點(diǎn)
4.addWaiter()
/**
* 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(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
這個(gè)方法的注釋:創(chuàng)建一個(gè)入隊(duì)node為當(dāng)前線程龙填,Node.EXCLUSIVE 是獨(dú)占鎖, Node.SHARED 是共享鎖。
先找到等待隊(duì)列的tail節(jié)點(diǎn)pred拐叉,如果pred岩遗!=null,就把當(dāng)前線程添加到pred后面進(jìn)入等待隊(duì)列凤瘦,如果不存在tail節(jié)點(diǎn)執(zhí)行enq()
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
這里進(jìn)行了循環(huán)宿礁,如果此時(shí)存在了tail就執(zhí)行同上一步驟的添加隊(duì)尾操作,如果依然不存在蔬芥,就把當(dāng)前線程作為head結(jié)點(diǎn)梆靖。
插入節(jié)點(diǎn)后控汉,調(diào)用acquireQueued()進(jìn)行阻塞
5.acquireQueued()
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
先獲取當(dāng)前節(jié)點(diǎn)的前一節(jié)點(diǎn)p,如果p是head的話就再進(jìn)行一次tryAcquire(arg)操作返吻,如果成功就返回姑子,否則就執(zhí)行shouldParkAfterFailedAcquire、parkAndCheckInterrupt來(lái)達(dá)到阻塞效果测僵;
6.shouldParkAfterFailedAcquire()
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.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
addWaiter()構(gòu)造的新節(jié)點(diǎn)街佑,waitStatus的默認(rèn)值是0。此時(shí)捍靠,進(jìn)入最后一個(gè)if判斷舆乔,CAS設(shè)置pred.waitStatus為SIGNAL==-1。最后返回false剂公。
回到第五步acquireQueued()中后希俩,由于shouldParkAfterFailedAcquire()返回false,會(huì)繼續(xù)進(jìn)行循環(huán)纲辽。假設(shè)node的前繼節(jié)點(diǎn)pred仍然不是頭結(jié)點(diǎn)或鎖獲取失敗颜武,則會(huì)再次進(jìn)入shouldParkAfterFailedAcquire()。上一輪循環(huán)中拖吼,已經(jīng)將pred.waitStatus設(shè)置為SIGNAL==-1鳞上,則這次會(huì)進(jìn)入第一個(gè)判斷條件,直接返回true吊档,表示應(yīng)該阻塞篙议。
7.parkAndCheckInterrupt()
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
很顯然,一旦shouldParkAfterFailedAcquire返回true也就是應(yīng)該阻塞怠硼,就會(huì)執(zhí)行parkAndCheckInterrupt()來(lái)達(dá)到阻塞效果鬼贱,此時(shí)線程阻塞在這里,需要其它線程來(lái)喚醒香璃,喚醒后就會(huì)再次循環(huán)第5步acquireQueued里的請(qǐng)求邏輯这难。
我們回到第6步,看一個(gè)留下的邏輯片段
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;
}
什么時(shí)候會(huì)遇到ws > 0的case呢葡秒?當(dāng)pred所維護(hù)的獲取請(qǐng)求被取消時(shí)(也就是node的waitStatus 值為CANCELLED)姻乓,這時(shí)就會(huì)循環(huán)移除所有被取消的前繼節(jié)點(diǎn)pred,直到找到未被取消的pred眯牧。移除所有被取消的前繼節(jié)點(diǎn)后蹋岩,直接返回false。
8.cancelAcquire()
到這里我們回到第5步可以看到主體邏輯基本走完了学少,在該方法的finally里有一個(gè)cancelAcquire()方法
private void cancelAcquire(Node node) {
// Ignore if node doesn't exist
if (node == null)
return;
node.thread = null;
// Skip cancelled predecessors
Node pred = node.prev;
while (pred.waitStatus > 0)
node.prev = pred = pred.prev;
// predNext is the apparent node to unsplice. CASes below will
// fail if not, in which case, we lost race vs another cancel
// or signal, so no further action is necessary.
Node predNext = pred.next;
// Can use unconditional write instead of CAS here.
// After this atomic step, other Nodes can skip past us.
// Before, we are free of interference from other threads.
node.waitStatus = Node.CANCELLED;
// If we are the tail, remove ourselves.
if (node == tail && compareAndSetTail(node, pred)) {
compareAndSetNext(pred, predNext, null);
} else {
// If successor needs signal, try to set pred's next-link
// so it will get one. Otherwise wake it up to propagate.
int ws;
if (pred != head &&
((ws = pred.waitStatus) == Node.SIGNAL ||
(ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
pred.thread != null) {
Node next = node.next;
if (next != null && next.waitStatus <= 0)
compareAndSetNext(pred, predNext, next);
} else {
unparkSuccessor(node);
}
node.next = node; // help GC
}
}
也就是在第5步的執(zhí)行過(guò)程中剪个,如果出現(xiàn)異常或者出現(xiàn)中斷旱易,就會(huì)執(zhí)行finally的取消線程的請(qǐng)求操作禁偎,核心代碼是node.waitStatus = Node.CANCELLED;將線程的狀態(tài)改為CANCELLED腿堤。
釋放鎖
1.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;
}
我們還是通過(guò)方法上面的注釋來(lái)理解一下:
釋放獨(dú)占鎖,如果tryRelease成功返回true的話就會(huì)解開(kāi)阻塞等待的線程
顯然如暖,tryRelease方法來(lái)釋放鎖笆檀,如果釋放成功,先判斷head節(jié)點(diǎn)是否有效盒至,最后unparkSuccessor啟動(dòng)后續(xù)等待的線程酗洒。
2.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;
}
先獲取state減去釋放的一次,然后判斷當(dāng)前線程是否和持有鎖線程一致枷遂,如果不一致樱衷,拋出異常,繼續(xù)判斷state的值酒唉,只有當(dāng)值為0時(shí)矩桂,free標(biāo)志才置為true,否則說(shuō)明是重入鎖痪伦,需要多次釋放直到state為0侄榴。
3.unparkSuccessor()
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)
compareAndSetWaitStatus(node, 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 t = tail; t != null && t != node; t = t.prev)
if (t.waitStatus <= 0)
s = t;
}
if (s != null)
LockSupport.unpark(s.thread);
}
這個(gè)方法名:?jiǎn)?dòng)后續(xù)線程,先拿到head節(jié)點(diǎn)的waitStatus并清空网沾,然后獲取next節(jié)點(diǎn)癞蚕,并做檢查,如果next節(jié)點(diǎn)失效辉哥,就從等待隊(duì)列的尾部進(jìn)行輪詢桦山,拿到第一個(gè)有效的節(jié)點(diǎn),然后通過(guò)LockSupport.unpark(s.thread);喚醒醋旦,令該線程重新進(jìn)入到獲取鎖的第5步循環(huán)去acquire鎖恒水。
疑惑點(diǎn)
1.我們?cè)讷@取鎖的很多步驟中看到tryAcquire的操作,原因是當(dāng)獲取一次失敗后浑度,程序會(huì)去執(zhí)行失敗后的邏輯代碼寇窑,但是在執(zhí)行過(guò)程中有可能鎖的狀態(tài)也同時(shí)發(fā)生了變化(釋放鎖鸦概、pred節(jié)點(diǎn)失效等情況)箩张,這時(shí)候需要去tryAcquire一下,省去了阻塞再喚醒的成本窗市。
2.等待隊(duì)列的waitStatus屬性使用很多先慷,在這里我們先讀一下源碼注釋:
/** waitStatus value to indicate thread has cancelled */
static final int CANCELLED = 1;
/** waitStatus value to indicate successor's thread needs unparking */
static final int SIGNAL = -1;
/** waitStatus value to indicate thread is waiting on condition */
static final int CONDITION = -2;
/**
* waitStatus value to indicate the next acquireShared should
* unconditionally propagate
*/
static final int PROPAGATE = -3;
/**
* Status field, taking on only the values:
* SIGNAL: The successor of this node is (or will soon be)
* blocked (via park), so the current node must
* unpark its successor when it releases or
* cancels. To avoid races, acquire methods must
* first indicate they need a signal,
* then retry the atomic acquire, and then,
* on failure, block.
* CANCELLED: This node is cancelled due to timeout or interrupt.
* Nodes never leave this state. In particular,
* a thread with cancelled node never again blocks.
* CONDITION: This node is currently on a condition queue.
* It will not be used as a sync queue node
* until transferred, at which time the status
* will be set to 0. (Use of this value here has
* nothing to do with the other uses of the
* field, but simplifies mechanics.)
* PROPAGATE: A releaseShared should be propagated to other
* nodes. This is set (for head node only) in
* doReleaseShared to ensure propagation
* continues, even if other operations have
* since intervened.
* 0: None of the above
*
* The values are arranged numerically to simplify use.
* Non-negative values mean that a node doesn't need to
* signal. So, most code doesn't need to check for particular
* values, just for sign.
*
* The field is initialized to 0 for normal sync nodes, and
* CONDITION for condition nodes. It is modified using CAS
* (or when possible, unconditional volatile writes).
*/
volatile int waitStatus;
SIGNAL:后續(xù)線程正在阻塞,所以當(dāng)前node在釋放鎖時(shí)必須啟動(dòng)后續(xù)線程咨察,為了避免競(jìng)爭(zhēng)激烈论熙,acquire 方法第一次執(zhí)行需要一個(gè)信號(hào),也就是這個(gè)啟動(dòng)信號(hào)摄狱。
CANCELLED:這個(gè)node失效了脓诡,因?yàn)槌瑫r(shí)或者被中斷等原因无午。
CONDITION:這個(gè)node當(dāng)前是屬于條件鎖
PROPAGATE:這個(gè)node是共享鎖節(jié)點(diǎn),他需要進(jìn)行喚醒傳播