java AQS 框架一些理解
最近感覺基礎有待加強,寫點理論加深下自己的理解 ,第一次寫部落格希望大家給點建議,指點下
AQS的全稱為(AbstractQueuedSynchronizer);
JAVA 主要實現類為 AbstractQueuedSynchronizer(結構如下)
AbstractQueuedSynchronizer主要結構入上圖
1.AbstractQueuedSynchronizer 主要有一個標誌鎖狀態的state 和指向佇列頭和尾的指標(主要成員變數為 state (標誌鎖的狀態) head 指向等待獲取鎖佇列的頭 tail 指向獲取佇列的尾部)
2.AbstractQueuedSynchronizer 有兩個內部類 Node(對等待獲取鎖執行緒的一個封裝) 和 ConditionObject
下面結合ReentrantLock 原始碼分析下jdk怎麼實現AQS(jdk1.7.0_67)
1.ReentrantLock 的建構函式兩個ReentrantLock(),ReentrantLock(fair)
可以看到建構函式主要初始化sync 成員變數 ,下面以ReentrantLock()建構函式來說明;
初始化一個 sync = new NonfairSync(); NonfairSync繼承Sync ,Sync 又繼承AbstractQueuedSynchronizer
NonfairSync 主要實現 lock,tryAcquire;
2,我們看下ReentrantLock.lock
我們獲取鎖的入口函式
public
void lock() {
sync.lock();
}
呼叫的是 sync.lock();
sync的程式碼如下
final
void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
acquire 方法是在AbstractQueuedSynchronizer 實現的,程式碼如下
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
簡單解釋下上面程式碼compareAndSetState(0, 1) 利用CAS 原理修改AbstractQueuedSynchronizer 的成員變數state 如果修改成功則當前執行緒獲取鎖;
並把sync 鎖所屬執行緒設定成當前執行緒
如果不成功 則呼叫acquire(1);
我們在看下acquire(1) 的執行流程
if(!tryAcquire(1)&&acquireQueued(addWaiter(Node.EXCLUSIVE), 1))
selfInterrupt();
tryAcquire(1) 會呼叫 nonfairTryAcquire(1)
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;
}
第一部分主要是當前執行緒繼續嘗試獲取鎖 第二個if是判斷鎖的持有者是不是當前執行緒
如果前兩個if都沒走則說明獲取鎖失敗
繼續走acquireQueued(addWaiter(Node.EXCLUSIVE),
addWaiter方法是將沒獲取鎖的執行緒組裝成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;
}
加入後我們看下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);
}
}
這是個死迴圈 如果p == head && tryAcquire(arg) 不滿足則會呼叫parkAndCheckInterrupt 阻塞執行緒
最終呼叫的是unsafe.park(false, 0L),阻塞執行緒這是個native方法這裡不解釋了
3.最後我們看下unlock函式怎樣釋放鎖的
public
void unlock() {
sync.release(1);
}
public
final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
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);
}
主要是修改syn的狀態變數 佇列的移除,喚醒其他執行緒