3.4 Template Method node
AbstractQueuedSynchronizer提供了如下几个protected方法用于子类改写 多线程
Java代码
- protected boolean tryAcquire(int arg)
- protected boolean tryRelease(int arg)
- protected int tryAcquireShared(int arg)
- protected boolean tryReleaseShared(int arg)
- protected boolean isHeldExclusively()
这几个方法的默认实现是抛出UnsupportedOperationException,子类能够根据须要进行改写。 并发
AbstractQueuedSynchronizer中最基本的acquire流程的相关代码以下: app
Java代码
- public final void acquire(int arg) {
- if (!tryAcquire(arg) &&
- acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
- selfInterrupt();
- }
-
- 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);
- }
- }
若是tryAcquire失败,那么当前线程可能会被enqueue到WaitQueue,而后被阻塞。 shouldParkAfterFailedAcquire方法会确保每一个线程在被阻塞以前,其对应WaitQueue中的节点的waitStatus被设置为Node.SIGNAL(-1),以便在release时避免没必要要的unpark操做。此外shouldParkAfterFailedAcquire还会清理WaitQueue中已经超时或者取消的Node。须要注意的是,在某个线程最终被阻塞以前,tryAcquire可能会被屡次调用。 ide
AbstractQueuedSynchronizer中最基本的release流程的相关代码以下: 函数
Java代码
- 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);
- }
release方法中,老是总head节点开始向后查找sucessor。只有当该sucessor的waitStatus被设置的状况下才会调用unparkSuccessor。unparkSuccessor方法中首先清除以前设置的Node.waitStatus,而后向后查找而且唤醒第一个须要被唤醒的sucessor。须要注意的是,if (s == null || s.waitStatus > 0)这个分支中,查找是从tail节点开始,根据prev引用向前进行。在Inside AbstractQueuedSynchronizer (2) 中提到过,Node.next为null并不必定意味着没有sucessor,虽然WaitQueue是个双向链表,可是根据next引用向后查找sucessor不靠谱,而根据prev引用向前查找predecessor老是靠谱。 ui
3.5 Fairness this
到目前为止咱们已经知道,WaitQueue是个FIFO的队列,唤醒也老是从head开始。可是AbstractQueuedSynchronizer却并不必定是公平的(实际上,大多数状况下都是在非公平模式下工做)。若是在看一遍acquire方法会发现,tryAcquire的调用顺序先于acquireQueued,也就是说后来的线程可能在等待中的线程以前acquire成功。这种场景被称为barging FIFO strategy,它能提供更高的吞吐量。 spa
大多数AbstractQueuedSynchronizer的子类都同时提供了公平和非公平的实现,例如ReentrantLock提供了NonfairSync和FairSync。例如其FairSync的tryAcquire方法以下: .net
Java代码
- 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;
- }
tryAcquire方法返回true的条件之一是!hasQueuedPredecessors() 。hasQueuedPredecessors的代码以下:
Java代码
- public final boolean hasQueuedPredecessors() {
- // The correctness of this depends on head being initialized
- // before tail and on head.next being accurate if the current
- // thread is first in queue.
- Node t = tail; // Read fields in reverse initialization order
- Node h = head;
- Node s;
- return h != t &&
- ((s = h.next) == null || s.thread != Thread.currentThread());
- }
综上, FairSync优先确保等待中线程先acquire成功。可是公平性也不是绝对的:在一个多线程并发的环境下,就算锁的获取是公平的,也不保证后续的其它处理过程的前后顺序。
既然默认状况下使用的都是NonfairSync,那么FairSync适合什么样的场景呢?若是被锁所保护的代码段的执行时间比较长,而应用又不能接受线程饥饿(NonfairSync可能会致使虽然某个线程长时间排队,可是仍然没法得到锁的状况)的场景下能够考虑使用FairSync。对于ReentrantLock,在其构造函数中传入true,便可构造一把公平锁。