AQS
1, state and co-operation of the state's two-way linked list.
2, a front view for the doubly linked list node status
3, CAS + Volitile state (current status acquired by the head, tail queue element is added)
. 4, volitile state is modified, setting the state method, there is the setState () and compareAndState () [ the unsafe];
. 5, the AQS main methods: tryAcquire, tryRelease, tryAcquireShared, tryReleaseShared , isHeldExclusively
//reentrantLock
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();//获取state
if (c == 0) {
if (compareAndSetState(0, acquires)) {//CAS
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;
}
//aqs
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);//mode,exclusive,Shared
// 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)) {//cas自旋锁插入到链表最后一个节点
pred.next = node;
return node;
}
}
enq(node);
return node;
}
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);
}
}
Acquires the lock
releases the lock
AQS, release-> tryRelease, release attempt by state-1, state if the release is zero