以前虽然看过一次AQS的源码实现,但在过一段时间后与同学交流时,发觉自己理解并不够深,印像太浅。需要做一个记录整理,帮助自己消化。
AQS中Node的设计:
几个点:
1. Node实现作者: "CLH" (Craig, Landin, and * Hagersten) ,有名的CLH queue
2. 是一个FIFO的链表的实现,对于队列的控制经常要做double-check。
3. Node节点通过一个int waiteStatus代表一些不同意义的状态。
- SIGNAL=-1,代表是需要当前Node节点需要唤起后一个Node节点。在Node节点enqueue时,会设置前一个节点的状态。这样链式的唤醒,完成这样的一个交接棒。
- CONDITION = -2 ,
1.private Node addWaiter(Node mode) {
2. Node node = new Node(Thread.currentThread(), mode);
3. // Try the fast path of enq; backup to full enq on failure
4. Node pred = tail;
5. if (pred != null) {
6. node.prev = pred;
7. if (compareAndSetTail(pred, node)) { // 位置1
8. pred.next = node;
9. return node;
10. }
11. }
12. enq(node);
13. return node;
14. }
15.
16.private Node enq(final Node node) {
17. for (;;) {
18. Node t = tail;
19. if (t == null) { // Must initialize // 位置3
20. Node h = new Node(); // Dummy header
21. h.next = node;
22. node.prev = h;
23. if (compareAndSetHead(h)) { // 位置4
24. tail = node;
25. return h;
26. }
27. }
28. else {
29. node.prev = t;
30. if (compareAndSetTail(t, node)) { // 位置2
31. t.next = node;
32. return t;
33. }
34. }
35. }
36. }
1.private void setHead(Node node) {
2. head = node;
3. node.thread = null;
4. node.prev = null;
5. }
1.final Node p = node.predecessor(); // 位置1
2. if (p == head && tryAcquire(arg)) {
3. setHead(node);
4. p.next = null; // help GC
5. return interrupted;
6.}
1.private void unparkSuccessor(Node node) {
2. /*
3. * Try to clear status in anticipation of signalling. It is
4. * OK if this fails or if status is changed by waiting thread.
5. */
6. compareAndSetWaitStatus(node, Node.SIGNAL, 0);
7.
8. /*
9. * Thread to unpark is held in successor, which is normally
10. * just the next node. But if cancelled or apparently null,
11. * traverse backwards from tail to find the actual
12. * non-cancelled successor.
13. */
14. Node s = node.next;
15. if (s == null || s.waitStatus > 0) { //位置1
16. s = null;
17. for (Node t = tail; t != null && t != node; t = t.prev)
18. if (t.waitStatus <= 0)
19. s = t;
20. }
21. if (s != null)
22. LockSupport.unpark(s.thread);
23. }
acquire , release , cancel三个动作设计
按照原先作者的设计:
1.Acquire:
2. while (!tryAcquire(arg)) {
3. enqueue thread if it is not already queued;
4. possibly block current thread;
5. }
6.
7.Release:
8. if (tryRelease(arg))
9. unblock the first queued thread;
预留了5个protected方法,用于client自己实现相关的处理,进行业务行为控制,因为cocurrent很多Lock,Future的实现都是基于此扩展,定义了自己的处理。
具体的一些方法使用,后续再补。
acquire动作:
独占锁:
1.public final void acquire(int arg) {
2. if (!tryAcquire(arg) &&
3. acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
4. selfInterrupt();
5. }
1.final boolean acquireQueued(final Node node, int arg) {
2. try {
3. boolean interrupted = false;
4. for (;;) {
5. final Node p = node.predecessor(); <span style="color: rgb(255, 0, 0);"> <span style="color: rgb(0, 0, 0);"> // 位置1</span></span>
6. if (p == head && tryAcquire(arg)) {
7. setHead(node);
8. p.next = null; // help GC
9. return interrupted;
10. }
11. if (shouldParkAfterFailedAcquire(p, node) && // 位置2
12. parkAndCheckInterrupt()) // 位置3
13. interrupted = true;
14. }
15. } catch (RuntimeException ex) {
16. cancelAcquire(node); // 位置4
17. throw ex;
18. }
19. }
1.private void doAcquireInterruptibly(int arg)
2. throws InterruptedException {
3. final Node node = addWaiter(Node.EXCLUSIVE);
4. try {
5. for (;;) {
6. final Node p = node.predecessor(); // 位置1
7. if (p == head && tryAcquire(arg)) {
8. setHead(node);
9. p.next = null; // help GC
10. return;
11. }
12. if (shouldParkAfterFailedAcquire(p, node) && // 位置2
13. parkAndCheckInterrupt())
14. break; // 位置3
15. }
16. } catch (RuntimeException ex) {
17. cancelAcquire(node);
18. throw ex;
19. }
20. // Arrive here only if interrupted
21. cancelAcquire(node);
22. throw new InterruptedException(); // 位置4
23. }
1.private boolean doAcquireNanos(int arg, long nanosTimeout)
2. throws InterruptedException {
3. long lastTime = System.nanoTime();
4. final Node node = addWaiter(Node.EXCLUSIVE);
5. try {
6. for (;;) {
7. final Node p = node.predecessor(); // 位置1
8. if (p == head && tryAcquire(arg)) {
9. setHead(node);
10. p.next = null; // help GC
11. return true;
12. }
13. if (nanosTimeout <= 0) { // 位置2
14. cancelAcquire(node);
15. return false;
16. }
17. if (nanosTimeout > spinForTimeoutThreshold && // 位置3
18. shouldParkAfterFailedAcquire(p, node)) // 位置4
19. LockSupport.parkNanos(this, nanosTimeout); // 位置5
20. long now = System.nanoTime(); // 位置6
21. nanosTimeout -= now - lastTime;
22. lastTime = now;
23. if (Thread.interrupted()) // 位置7
24. break;
25. }
26. } catch (RuntimeException ex) {
27. cancelAcquire(node);
28. throw ex;
29. }
30. // Arrive here only if interrupted
31. cancelAcquire(node);
32. throw new InterruptedException(); // 位置8
33. }
public final void acquireShared(int arg)
和独占锁处理方式基本类似,来看一下核心代码:
1.private void doAcquireShared(int arg) {
2. final Node node = addWaiter(Node.SHARED);
3. try {
4. boolean interrupted = false;
5. for (;;) {
6. final Node p = node.predecessor();
7. if (p == head) {
8. int r = tryAcquireShared(arg);
9. if (r >= 0) {
10. setHeadAndPropagate(node, r); // 位置1
11. p.next = null; // help GC
12. if (interrupted)
13. selfInterrupt();
14. return;
15. }
16. }
17. if (shouldParkAfterFailedAcquire(p, node) &&
18. parkAndCheckInterrupt())
19. interrupted = true;
20. }
21. } catch (RuntimeException ex) {
22. cancelAcquire(node);
23. throw ex;
24. }
25. }
这里设计上有点小技巧,原先思考一个共享锁的典型场景:读写锁。 一旦写锁释放,应该是唤起所有的读锁。而原先在看setHeadAndPropagate,并没有一个循环释放锁的过程。后来思考了下,采用的是一个链式释放的过程,前一个shared的锁对象释放下一个,在释放的时候继续进行tryAccquireShared控制。
一点感悟:在写并发程序时,一些传统编程的思路要有所改变。
public final void acquireSharedInterruptibly(int arg) throws InterruptedException
public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) throws InterruptedException
这两个实现上和独占锁类似,也就是setHeadAndPropagate处理上的不同点而已。
release动作:
public final boolean release(int arg)
1.if (tryRelease(arg)) {
2. Node h = head;
3. if (h != null && h.waitStatus != 0)
4. unparkSuccessor(h);
5. return true;
6. }
7. return false;
没啥特别好将的,一看基本也就明白了,出队列的时候,同时唤醒下一个Node。
cancel动作:
private void cancelAcquire(Node node)
代码就不贴了,几个处理:
1. 从链表上删除cancel节点
2. 如果cancel节点是head,则尝试唤醒cancel节点的下一个节点。
ConditionObject的理解
几个主要方法:
- public final void await() throws InterruptedException
- public final void awaitUninterruptibly()
- public final long awaitNanos(long nanosTimeout) throws InterruptedException
- public final boolean awaitUntil(Date deadline) throws InterruptedException
- public final boolean await(long time, TimeUnit unit) throws InterruptedException
- public final void signal()
- public final void signalAll()
伪代码如下:
1.Array queue;
2.Object empty = new Object();
3.Object full = new Object();
4.
5.// 生产者
6.if(queue 是否满了)
7. full.wait() //阻塞等待
8.else
9. put(queue , data) //放入数据
10. empty.single(); // 已经放了一个,通知一下
11.
12.
13.// 消费者
14.if(queue 是否空了)
15. empty.wait() // 阻塞等待
16.else
17. data = get(queue);
18. full.single() // 已经消费了,通知一下
整体概念
在整个AQS存在两种链表。 一个链表就是整个Sync Node链表,横向链表。另一种链表就是Condition的wait Node链表,相对于Sync node,它属于node节点的一个纵向链表。当纵向列表被single通知后,会进入对应的Sync Node进行排队处理。
通过这样的纵横队列,实现了ConditionObject共享lock锁数据。
