重入鎖,獨佔式
一、ReentrantLock.lock()->sync.lock()
1、NonfairSync
final void lock() {
if (compareAndSetState(0, 1))//嘗試修改狀態,若成功說明沒有線程修改過,獲取鎖
setExclusiveOwnerThread(Thread.currentThread());//設置當前線程
else
acquire(1);//失敗,則變成公平鎖
}
2、FairSync
final void lock() {
acquire(1);
}
3、AbstractQueuedSynchronizer.acquire(int arg)
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();//中斷本線程
}
4、NonfairSync.tryAcquire(int acquires)
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
//if嘗試修改狀態獲取鎖
//else if 檢查是否是本線程已經獲取到了鎖,是則狀態+1
//else 獲取失敗
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;
}
5、FairSync.tryAcquire(int acquires)
//if嘗試修改狀態獲取鎖,比上面上方多一步校驗
//即當前線程必須在AQS的同步隊列的頭結點,或者同步隊列爲空,這樣來保證公平
//else if 檢查是否是本線程已經獲取到了鎖,是則狀態+1
//else 獲取失敗
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;
}
6、第3步的acquireQueued(addWaiter(Node.EXCLUSIVE), arg)
addWaiter把當前線程包裝成一個獨佔式(EXCLUSIVE)節點,CAS放到AQS的同步隊列尾部,更新尾節點
acquireQueued自旋新加入的節點,嘗試獲取直到成功,返回true應該中斷
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())
// true如果該線程應該阻塞 && true 如果線程被中斷了,
//private final boolean parkAndCheckInterrupt() {
// LockSupport.park(this);//阻塞線程
// return Thread.interrupted();
//}
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(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.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
二、ReentrantLock.unlock()->sync.release(1)
1、AQS.release
//完全釋放返回true
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);//完全釋放後,喚醒繼承者
return true;
}
return false;
}
//完全釋放,state置爲0,返回true
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;
}
/**
* 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)
compareAndSetWaitStatus(node, ws, 0);//頭結點waitStatus置爲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;//從尾節點往前找到最靠前的,waitStatus<=0的,不等於頭結點的節點
}
if (s != null)
LockSupport.unpark(s.thread);//喚醒
}