AbstractQueuedSynchronizer类源码解析

来源:互联网 发布:淘宝盗图处罚规则2016 编辑:程序博客网 时间:2024/06/07 14:04

参考网址:
http://ifeve.com/introduce-abstractqueuedsynchronizer/
http://www.cnblogs.com/xrq730/p/4979021.html
http://www.cnblogs.com/xrq730/p/4976007.html
http://blog.csdn.net/qq_19431333/article/details/70568478

1、transient是Java语言的关键字,用来表示一个域不是该对象串行化的一部分。当一个对象被串行化的时候,transient型变量的值不包括在串行化的表示中,然而非transient型的变量是被包括进去的.
即transient修饰的字段不会通过Serializable进行网络传输。
2 该同步器即可以作为排他模式也可以作为共享模式,当它被定义为一个排他模式时,其他线程对其的获取就被阻止,而共享模式对于多个线程获取都可以成功。
3 同步器的实现依赖于一个FIFO队列

AbstractOwnableSynchronizer exclusiveOwnerThread排他线程

2、Node

Node SHARED = new Node() 表示Node处于共享模式
Node EXCLUSIVE = NULL 表示Node处于独占模式
int CANCELLED = 1 因为超时或者中断,Node被设置为取消状态,被取消的Node不应该去竞争锁,只能保持取消状态不变,不能转换为其他状态,处于这种状态的Node会被踢出队列,被GC回收
int SIGNAL = -1 表示当前节点的后继节点包含的线程需要运行,也就是unpark
int CONDITION = -2 表示当前节点在等待condition,也就是在condition队列中
int PROPAGATE = -3 表示当前场景下后续的acquireShared能够得以执行;
0,表示当前节点在sync队列中,等待着获取锁

Node prev 前驱节点
Node next 后继节点
Node nextWaiter 存储condition队列中的后继节点
Thread thread 入队列时的当前线程

3、AbstractQueuedSynchronizer类
exclusiveOwnerThread 正在运行的线程,不为空则不允许其他线程获得锁资源
Node head 头节点
Node tail 尾节点
int state 状态
1:处于占用状态, 其他线程等待该资源释放锁。
0:空闲状态,其他线程可以获得资源锁

void unparkSuccessor(Node node) 如果存在的话,唤醒node的继任者
void doReleaseShared() 将head为waitStatus=-1变为0,并且唤醒head的继任者。 如果为waitStatus=0则变为-3。
void cancelAcquire(Node node) 取消正在进行的Node获取锁的尝试,将节点状态设置为取消状态,后续GC会回收该节点
boolean shouldParkAfterFailedAcquire(Node pred, Node node) 在尝试获取锁失败后将当前Node的waitStatus置为-1。
void selfInterrupt() 中断当前线程本身
boolean parkAndCheckInterrupt() 禁用当前线程,进入等待状态并中断线程本身
boolean acquireQueued(final Node node, int arg) 自旋,直到当前节点满足成为头结点的继任者,是则获取锁,不是等待队列前面的节点线程运行完.

ConditionObject类
Node firstWaiter 条件队列头节点
Node lastWaiter 条件队列尾节点

void unlinkCancelledWaiters() 将waitStatus != Node.CONDITION的所有节点移除
Node addConditionWaiter() 往条件队列里添加当前线程节点
void awaitUninterruptibly() 非中断等待,除了singal(),否则一直处于阻塞状态
void signal() 唤醒condition队列的头节点,使其进入sync队列
void signalAll() 唤醒condition队列中所有节点,使其进入sync队列排队获得锁资源
void awaitUninterruptibly() 阻塞当前线程,创建节点放入condition队列尾部,当前线程被调用interrupt()方法后提前结束,抛出异常
void await() throws InterruptedException 阻塞当前线程,释放锁资源,从sync队列进入condition队列尾部

LockSupport函数列表
// 返回提供给最近一次尚未解除阻塞的 park 方法调用的 blocker 对象,如果该调用不受阻塞,则返回 null。
static Object getBlocker(Thread t)
// 为了线程调度,禁用当前线程,除非许可可用。
static void park()
// 为了线程调度,在许可可用之前禁用当前线程。
static void park(Object blocker)
// 为了线程调度禁用当前线程,最多等待指定的等待时间,除非许可可用。
static void parkNanos(long nanos)
// 为了线程调度,在许可可用前禁用当前线程,并最多等待指定的等待时间。
static void parkNanos(Object blocker, long nanos)
// 为了线程调度,在指定的时限前禁用当前线程,除非许可可用。
static void parkUntil(long deadline)
// 为了线程调度,在指定的时限前禁用当前线程,除非许可可用。
static void parkUntil(Object blocker, long deadline)
// 如果给定线程的许可尚不可用,则使其可用。
static void unpark(Thread thread)

ReentrantLock类

private final Sync sync;
abstract static class Sync extends AbstractQueuedSynchronizer 定义了内部抽象静态类Sync
static final class NonfairSync extends Sync 非公平锁
static final class FairSync extends Sync 公平锁

new ReentrantLock() 定义的是非公平锁, 公平锁要比不公平锁的吞吐率更低
public ReentrantLock(true) 定义的是公平锁
void lock()
非公平锁立即占用锁或者一直竞争锁资源
公平锁进入队列排队等待获取锁资源,开销很大
void lockInterruptibly()
类似lock()方法,但当其他线程调用了该线程的interrupt()方法会抛出异常。
boolean tryLock()
锁资源没有被其他线程持有则持有锁资源并返回true,否则返回false。
boolean tryLock(long timeout, TimeUnit unit)
单元时间内获得锁资源立即返回true,否则超时返回false.
void unlock()
释放持有的锁资源
Condition newCondition()
创建Condition对象
boolean isHeldByCurrentThread()
是否当前线程持有锁资源,监控使用
boolean isLocked()
资源是否被某个线程持有,监控使用
boolean isFair()
是否是公平锁
Thread getOwner()
获取正持有锁资源的线程
boolean hasQueuedThreads()
队列里面是否有线程等待获取锁资源
boolean hasQueuedThread(Thread thread)
thread是否在队列中等待获取资源
int getQueueLength()
返回队列长度
Collection getQueuedThreads()
返回队列中所有线程的集合
boolean hasWaiters(Condition condition)
condition队列中是否有等待被唤醒的线程
getWaitQueueLength(Condition condition)
返回condition队列中所有等待被唤醒(waitState=-2)线程的个数
Collection getWaitingThreads(Condition condition)
返回condition队列中所有等待被唤醒(waitState=-2)线程的集合

ReentrantLock与synchronize的区别
synchronize
受保护的代码抛出异常,JVM 将确保锁会获得自动释放
它无法中断一个正在等候获得锁的线程,也无法通过投票得到锁,如果不想等下去,也就没法得到锁
ReentrantLock:
ReentrantLock 类实现了 Lock ,它拥有与 synchronized 相同的并发性和内存语义,但是添加了类似锁投票、定时锁等候和可中断锁等候的一些特性
激烈争用情况下更佳的性能(当许多线程都想访问共享资源时,JVM 可以花更少的时候来调度线程,把更多时间用在执行线程上)
lock 必须在 finally 块中释放,受保护的代码抛出异常,不会释放锁资源
Lock包含了Condition对象,每个condition都有自己的队列,所以通过不同的condition唤醒特定的线程。运行condition之前必须先持有锁资源。

吞吐率:Lock非公平锁 > synchronize > Lock公平锁

使用锁,如果一个线程没有获取到锁资源,那么它是不是一直在竞争锁资源,

每个condition都包含了一个condition队列

有2个队列,一个是waitStatus=-2的条件队列,另一个是waitStatus!=-2的sync队列

m<

public abstract class AbstractQueuedSynchronizer    extends AbstractOwnableSynchronizer    implements java.io.Serializable {    private static final long serialVersionUID = 7373984972572414691L;    protected AbstractQueuedSynchronizer() { }    static final class Node {        /**标记Node处于共享模式 */        static final Node SHARED = new Node();        /** 标记Node处于独占模式 */        static final Node EXCLUSIVE = null;        /** 因为超时或者中断,Node被设置为取消状态,被取消的Node不应该去竞争锁,只能保持取消状态不变,不能转换为其他状态,处于这种状态的Node会被踢出队列,被GC回收 */        static final int CANCELLED =  1;        /** 表示当前节点的后继节点包含的线程需要运行,也就是unpark */        static final int SIGNAL    = -1;        /** 表示当前节点在等待condition,也就是在condition队列中  */        static final int CONDITION = -2;        /**         * 表示当前场景下后续的acquireShared能够得以执行;         */        static final int PROPAGATE = -3;        /**         * 下列值中的一个:         *   SIGNAL:     继任者处于阻塞状态, 所以当前节点被释放或者取消后应该唤醒继任者节点线程, acquire 方法必须首先指定为signal,         *               然后重试原子获取锁。该状态节点在队列中等待获取锁资源         *   CANCELLED:  因为超时或者interrupt处于该状态.该节点状态永远不会被改变,一直到被移除.         *   CONDITION:  该节点处于 condition队列中.当被唤醒后置为0进入同步队列         *   PROPAGATE:  A releaseShared should be propagated to other         *               nodes. This is set (for head node only) in         *               doReleaseShared to ensure propagation         *               continues, even if other operations have         *               since intervened.         *   0:          其他,初始化值         */        volatile int waitStatus;        volatile Node prev;        volatile Node next;         // 入队列时的当前线程        volatile Thread thread;         // 存储condition队列中的后继节点,或者特殊的共享节点        Node nextWaiter;        /**         * Returns true if node is waiting in shared mode.         */        final boolean isShared() {            return nextWaiter == SHARED;        }        /**         * 返回前驱节点         */        final Node predecessor() throws NullPointerException {            Node p = prev;            if (p == null)                throw new NullPointerException();            else                return p;        }        Node() {    // Used to establish initial head or SHARED marker        }        Node(Thread thread, Node mode) {     // Used by addWaiter            this.nextWaiter = mode;            this.thread = thread;        }        Node(Thread thread, int waitStatus) { // Used by Condition            this.waitStatus = waitStatus;            this.thread = thread;        }    }    //头结点    private transient volatile Node head;    //尾节点    private transient volatile Node tail;    //锁状态    private volatile int state;    protected final int getState() {        return state;    }    protected final void setState(int newState) {        state = newState;    }    /**     * CAS原子操作修改状态值     */    protected final boolean compareAndSetState(int expect, int update) {        // See below for intrinsics setup to support this        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);    }    /**     * 在park线程之前,先自旋spinForTimeoutThreshold的时间,一个粗略的估计足以在非常短的超时中提高响应能力     */    static final long spinForTimeoutThreshold = 1000L;    /**     * 入队列     */    private Node enq(final Node node) {        for (;;) {            Node t = tail;            //为空初始化队列            if (t == null) { // Must initialize                if (compareAndSetHead(new Node()))                    tail = head;            } else {                node.prev = t;                if (compareAndSetTail(t, node)) {                    t.next = node;                    return t;                }            }        }    }    /**     * 为当前线程给定模式并创建和成为队列尾节点。     */    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;    }    /**     * 设置头结点     */    private void setHead(Node node) {        head = node;        node.thread = null;        node.prev = null;    }    //唤醒继承者节点线程    private void unparkSuccessor(Node node) {        int ws = node.waitStatus;        if (ws < 0)            compareAndSetWaitStatus(node, ws, 0);        /*         * 唤醒继承者节点线程,如果next节点为null或者为取消状态,则从尾节点依次往前查找继任者节点         */        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);    }    /**     * 为共享模式释放操作——通知继任者,并确保传播。(注意:对于独占模式,如果需要信号的话,释放就相当于调用unparkSuccessor需要通知的头节点。)     */    private void doReleaseShared() {        for (;;) {            Node h = head;            if (h != null && h != tail) {                int ws = h.waitStatus;                if (ws == Node.SIGNAL) {                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))                        continue;            // loop to recheck cases                    unparkSuccessor(h);                }                else if (ws == 0 &&                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))                    continue;                // loop on failed CAS            }            if (h == head)                   // loop if head changed                break;        }    }    private void setHeadAndPropagate(Node node, int propagate) {        Node h = head; // Record old head for check below        setHead(node);        if (propagate > 0 || h == null || h.waitStatus < 0 ||            (h = head) == null || h.waitStatus < 0) {            Node s = node.next;            if (s == null || s.isShared())                doReleaseShared();        }    }    /**     * 将当期节点状态设置为取消状态,并从队列中移除当前节点     */    private void cancelAcquire(Node node) {        // Ignore if node doesn't exist        if (node == null)            return;        node.thread = null;        // Skip cancelled predecessors        Node pred = node.prev;        while (pred.waitStatus > 0)            node.prev = pred = pred.prev;        Node predNext = pred.next;        node.waitStatus = Node.CANCELLED;        if (node == tail && compareAndSetTail(node, pred)) {            compareAndSetNext(pred, predNext, null);        } else {            int ws;            if (pred != head &&                ((ws = pred.waitStatus) == Node.SIGNAL ||                 (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&                pred.thread != null) {                Node next = node.next;                if (next != null && next.waitStatus <= 0)                    compareAndSetNext(pred, predNext, next);            } else {                unparkSuccessor(node);            }            node.next = node; // help GC        }    }    /**     * 检查并更新状态     */    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {        int ws = pred.waitStatus;        if (ws == Node.SIGNAL)            return true;        if (ws > 0) {            /*             * 前驱为取消状态,则找到非取消状态的前驱者,并重试获取锁             */            do {                node.prev = pred = pred.prev;            } while (pred.waitStatus > 0);            pred.next = node;        } else {            /*             * 状态为0或PROPAGATE,表示当前节点需要运行,重试获取锁             */            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);        }        return false;    }    /**     * Convenience method to interrupt current thread.     */    static void selfInterrupt() {        Thread.currentThread().interrupt();    }    /**     * 停止当前线程运行,线程被中断返回true     */    private final boolean parkAndCheckInterrupt() {        LockSupport.park(this);        return Thread.interrupted();    }    /**     * 自旋判断是否该自己运行,直到获得锁成功     */    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 in exclusive interruptible mode.     * @param arg the acquire argument     */    private void doAcquireInterruptibly(int arg)        throws InterruptedException {        final Node node = addWaiter(Node.EXCLUSIVE);        boolean failed = true;        try {            for (;;) {                final Node p = node.predecessor();                if (p == head && tryAcquire(arg)) {                    setHead(node);                    p.next = null; // help GC                    failed = false;                    return;                }                if (shouldParkAfterFailedAcquire(p, node) &&                    parkAndCheckInterrupt())                    throw new InterruptedException();            }        } finally {            if (failed)                cancelAcquire(node);        }    }    /**     * Acquires in exclusive timed mode.     *     * @param arg the acquire argument     * @param nanosTimeout max wait time     * @return {@code true} if acquired     */    private boolean doAcquireNanos(int arg, long nanosTimeout)            throws InterruptedException {        if (nanosTimeout <= 0L)            return false;        final long deadline = System.nanoTime() + nanosTimeout;        final Node node = addWaiter(Node.EXCLUSIVE);        boolean failed = true;        try {            for (;;) {                final Node p = node.predecessor();                if (p == head && tryAcquire(arg)) {                    setHead(node);                    p.next = null; // help GC                    failed = false;                    return true;                }                nanosTimeout = deadline - System.nanoTime();                if (nanosTimeout <= 0L)                    return false;                if (shouldParkAfterFailedAcquire(p, node) &&                    nanosTimeout > spinForTimeoutThreshold)                    LockSupport.parkNanos(this, nanosTimeout);                if (Thread.interrupted())                    throw new InterruptedException();            }        } finally {            if (failed)                cancelAcquire(node);        }    }    /**     * Acquires in shared uninterruptible mode.     * @param arg the acquire argument     */    private void doAcquireShared(int arg) {        //在获取共享状态失败后,当前时刻有可能是独占锁被其他线程所把持,那么将当前线程构造成为节点(共享模式)加入到sync队列中        final Node node = addWaiter(Node.SHARED);        boolean failed = true;        try {            boolean interrupted = false;            for (;;) {                final Node p = node.predecessor();                //判断后继节点是否是共享模式,如果是共享模式,那么就直接对其进行唤醒操作,也就是同时激发多个线程并发的运行。                if (p == head) {                    int r = tryAcquireShared(arg);                    if (r >= 0) {                        //判断后继节点是否是共享模式,如果是共享模式,那么就直接对其进行唤醒操作,也就是同时激发多个线程并发的运行。                        setHeadAndPropagate(node, r);                        p.next = null; // help GC                        if (interrupted)                            selfInterrupt();                        failed = false;                        return;                    }                }                //通过使用LockSupport将当前线程从线程调度器上摘下,进入休眠状态                if (shouldParkAfterFailedAcquire(p, node) &&                    parkAndCheckInterrupt())                    interrupted = true;            }        } finally {            if (failed)                cancelAcquire(node);        }    }    /**     * Acquires in shared interruptible mode.     * @param arg the acquire argument     */    private void doAcquireSharedInterruptibly(int arg)        throws InterruptedException {        final Node node = addWaiter(Node.SHARED);        boolean failed = true;        try {            for (;;) {                final Node p = node.predecessor();                if (p == head) {                    int r = tryAcquireShared(arg);                    if (r >= 0) {                        setHeadAndPropagate(node, r);                        p.next = null; // help GC                        failed = false;                        return;                    }                }                if (shouldParkAfterFailedAcquire(p, node) &&                    parkAndCheckInterrupt())                    throw new InterruptedException();            }        } finally {            if (failed)                cancelAcquire(node);        }    }    /**     * Acquires in shared timed mode.     *     * @param arg the acquire argument     * @param nanosTimeout max wait time     * @return {@code true} if acquired     */    private boolean doAcquireSharedNanos(int arg, long nanosTimeout)            throws InterruptedException {        if (nanosTimeout <= 0L)            return false;        final long deadline = System.nanoTime() + nanosTimeout;        final Node node = addWaiter(Node.SHARED);        boolean failed = true;        try {            for (;;) {                final Node p = node.predecessor();                if (p == head) {                    int r = tryAcquireShared(arg);                    if (r >= 0) {                        setHeadAndPropagate(node, r);                        p.next = null; // help GC                        failed = false;                        return true;                    }                }                nanosTimeout = deadline - System.nanoTime();                if (nanosTimeout <= 0L)                    return false;                if (shouldParkAfterFailedAcquire(p, node) &&                    nanosTimeout > spinForTimeoutThreshold)                    LockSupport.parkNanos(this, nanosTimeout);                if (Thread.interrupted())                    throw new InterruptedException();            }        } finally {            if (failed)                cancelAcquire(node);        }    }    // Main exported methods    /**     * 由继承类实现     */    protected boolean tryAcquire(int arg) {        throw new UnsupportedOperationException();    }    /**     * 由继承类实现     */    protected boolean tryRelease(int arg) {        throw new UnsupportedOperationException();    }    /**     * 子类实现,获取共享锁,如共享读锁     */    protected int tryAcquireShared(int arg) {        throw new UnsupportedOperationException();    }    /**     * 子类实现,释放共享锁     */    protected boolean tryReleaseShared(int arg) {        throw new UnsupportedOperationException();    }    /**     * 子类实现,判断是否为独占锁     */    protected boolean isHeldExclusively() {        throw new UnsupportedOperationException();    }    /**     * 获取独占模式锁     */    public final void acquire(int arg) {        //尝试获取(调用tryAcquire更改状态,需要保证原子性)        //如果获取不到,将当前线程构造成节点Node并加入sync队列;        if (!tryAcquire(arg) &&            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))            selfInterrupt();    }    /**     * 同acquire()方法,但当Thread.interrupt()时抛出异常,并取消当前线程的运行     */    public final void acquireInterruptibly(int arg)            throws InterruptedException {        if (Thread.interrupted())            throw new InterruptedException();        if (!tryAcquire(arg))            doAcquireInterruptibly(arg);    }    /**     * 1 单位时间内获得锁成功则返回true,     * 2 超时返回false     * 3 中断抛出异常     */    public final boolean tryAcquireNanos(int arg, long nanosTimeout)            throws InterruptedException {        if (Thread.interrupted())            throw new InterruptedException();        return tryAcquire(arg) ||            doAcquireNanos(arg, nanosTimeout);    }    /**     * 释放独占锁     */    public final boolean release(int arg) {        if (tryRelease(arg)) {            Node h = head;            if (h != null && h.waitStatus != 0)                unparkSuccessor(h);            return true;        }        return false;    }    /**     * ReentrantReadWriteLock中的读锁会调用     * 当tryAcquireShared()方法小于0时,那么会执行doAcquireShared方法将该线程加入到等待队列中     */    public final void acquireShared(int arg) {        if (tryAcquireShared(arg) < 0)            doAcquireShared(arg);    }    public final void acquireSharedInterruptibly(int arg)            throws InterruptedException {        if (Thread.interrupted())            throw new InterruptedException();        if (tryAcquireShared(arg) < 0)            doAcquireSharedInterruptibly(arg);    }    /**     * 参考acquireShared     */    public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)            throws InterruptedException {        if (Thread.interrupted())            throw new InterruptedException();        return tryAcquireShared(arg) >= 0 ||            doAcquireSharedNanos(arg, nanosTimeout);    }    /**     * 释放一个共享锁     */    public final boolean releaseShared(int arg) {        if (tryReleaseShared(arg)) {            doReleaseShared();            return true;        }        return false;    }    /**     * 判断当前节点是否在Sysn队列中     * 1 waitStatus=CONDITION在 condition队列中,返回false     * 2 node.prev == null返回false     * 3 node.next != null返回true     * 4 从队列尾节点一直找到头结点,找到当前节点返回true     */    final boolean isOnSyncQueue(Node node) {        if (node.waitStatus == Node.CONDITION || node.prev == null)            return false;        if (node.next != null) // If has successor, it must be on queue            return true;        return findNodeFromTail(node);    }    /**     * 从队列尾节点一直找到头结点,找到当前节点返回true     */    private boolean findNodeFromTail(Node node) {        Node t = tail;        for (;;) {            if (t == node)                return true;            if (t == null)                return false;            t = t.prev;        }    }    /**     * 将节点从condition队列转移到sync队列     */    final boolean transferForSignal(Node node) {        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))            return false;        Node p = enq(node);        int ws = p.waitStatus;        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))            LockSupport.unpark(node.thread);        return true;    }    final boolean transferAfterCancelledWait(Node node) {        if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {            enq(node);            return true;        }        while (!isOnSyncQueue(node))            Thread.yield();        return false;    }    /**     * 释放当前状态的锁     */    final int fullyRelease(Node node) {        boolean failed = true;        try {            int savedState = getState();            if (release(savedState)) {                failed = false;                return savedState;            } else {                throw new IllegalMonitorStateException();            }        } finally {            if (failed)                node.waitStatus = Node.CANCELLED;        }    }    /**     * 条件实体,包含自己的队列     */    public class ConditionObject implements Condition, java.io.Serializable {        private static final long serialVersionUID = 1173984872572414699L;        /** First node of condition queue. */        private transient Node firstWaiter;        /** Last node of condition queue. */        private transient Node lastWaiter;        public ConditionObject() { }        /**         * 将当前线程加入该condition队列         */        private Node addConditionWaiter() {            Node t = lastWaiter;            // If lastWaiter is cancelled, clean out.            if (t != null && t.waitStatus != Node.CONDITION) {                unlinkCancelledWaiters();                t = lastWaiter;            }            Node node = new Node(Thread.currentThread(), Node.CONDITION);            if (t == null)                firstWaiter = node;            else                t.nextWaiter = node;            lastWaiter = node;            return node;        }        /**         * Removes and transfers nodes until hit non-cancelled one or         * null. Split out from signal in part to encourage compilers         * to inline the case of no waiters.         * @param first (non-null) the first node on condition queue         */        private void doSignal(Node first) {            do {                if ( (firstWaiter = first.nextWaiter) == null)                    lastWaiter = null;                first.nextWaiter = null;            } while (!transferForSignal(first) &&                     (first = firstWaiter) != null);        }        /**         * Removes and transfers all nodes.         * @param first (non-null) the first node on condition queue         */        private void doSignalAll(Node first) {            lastWaiter = firstWaiter = null;            do {                Node next = first.nextWaiter;                first.nextWaiter = null;                transferForSignal(first);                first = next;            } while (first != null);        }        /**         * 移除condition队列中被唤醒的节点         */        private void unlinkCancelledWaiters() {            Node t = firstWaiter;            Node trail = null;            while (t != null) {                Node next = t.nextWaiter;                if (t.waitStatus != Node.CONDITION) {                    t.nextWaiter = null;                    if (trail == null)                        firstWaiter = next;                    else                        trail.nextWaiter = next;                    if (next == null)                        lastWaiter = trail;                }                else                    trail = t;                t = next;            }        }        // public methods        /**         * Moves the longest-waiting thread, if one exists, from the         * wait queue for this condition to the wait queue for the         * owning lock.         *         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}         *         returns {@code false}         */        public final void signal() {            if (!isHeldExclusively())                throw new IllegalMonitorStateException();            Node first = firstWaiter;            if (first != null)                doSignal(first);        }        /**         * Moves all threads from the wait queue for this condition to         * the wait queue for the owning lock.         *         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}         *         returns {@code false}         */        public final void signalAll() {            if (!isHeldExclusively())                throw new IllegalMonitorStateException();            Node first = firstWaiter;            if (first != null)                doSignalAll(first);        }        /**         * Implements uninterruptible condition wait.         * <ol>         * <li> Save lock state returned by {@link #getState}.         * <li> Invoke {@link #release} with saved state as argument,         *      throwing IllegalMonitorStateException if it fails.         * <li> Block until signalled.         * <li> Reacquire by invoking specialized version of         *      {@link #acquire} with saved state as argument.         * </ol>         */        public final void awaitUninterruptibly() {            Node node = addConditionWaiter();            int savedState = fullyRelease(node);            boolean interrupted = false;            while (!isOnSyncQueue(node)) {                LockSupport.park(this);                if (Thread.interrupted())                    interrupted = true;            }            if (acquireQueued(node, savedState) || interrupted)                selfInterrupt();        }        /*         * For interruptible waits, we need to track whether to throw         * InterruptedException, if interrupted while blocked on         * condition, versus reinterrupt current thread, if         * interrupted while blocked waiting to re-acquire.         */        /** Mode meaning to reinterrupt on exit from wait */        private static final int REINTERRUPT =  1;        /** Mode meaning to throw InterruptedException on exit from wait */        private static final int THROW_IE    = -1;        /**         * Checks for interrupt, returning THROW_IE if interrupted         * before signalled, REINTERRUPT if after signalled, or         * 0 if not interrupted.         */        private int checkInterruptWhileWaiting(Node node) {            return Thread.interrupted() ?                (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :                0;        }        /**         * Throws InterruptedException, reinterrupts current thread, or         * does nothing, depending on mode.         */        private void reportInterruptAfterWait(int interruptMode)            throws InterruptedException {            if (interruptMode == THROW_IE)                throw new InterruptedException();            else if (interruptMode == REINTERRUPT)                selfInterrupt();        }        /**         * Implements interruptible condition wait.         * <ol>         * <li> If current thread is interrupted, throw InterruptedException.         * <li> Save lock state returned by {@link #getState}.         * <li> Invoke {@link #release} with saved state as argument,         *      throwing IllegalMonitorStateException if it fails.         * <li> Block until signalled or interrupted.         * <li> Reacquire by invoking specialized version of         *      {@link #acquire} with saved state as argument.         * <li> If interrupted while blocked in step 4, throw InterruptedException.         * </ol>         */        public final void await() throws InterruptedException {            if (Thread.interrupted())                throw new InterruptedException();            Node node = addConditionWaiter();            int savedState = fullyRelease(node);            int interruptMode = 0;            while (!isOnSyncQueue(node)) {                LockSupport.park(this);                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)                    break;            }            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)                interruptMode = REINTERRUPT;            if (node.nextWaiter != null) // clean up if cancelled                unlinkCancelledWaiters();            if (interruptMode != 0)                reportInterruptAfterWait(interruptMode);        }        /**         * Implements timed condition wait.         * <ol>         * <li> If current thread is interrupted, throw InterruptedException.         * <li> Save lock state returned by {@link #getState}.         * <li> Invoke {@link #release} with saved state as argument,         *      throwing IllegalMonitorStateException if it fails.         * <li> Block until signalled, interrupted, or timed out.         * <li> Reacquire by invoking specialized version of         *      {@link #acquire} with saved state as argument.         * <li> If interrupted while blocked in step 4, throw InterruptedException.         * </ol>         */        public final long awaitNanos(long nanosTimeout)                throws InterruptedException {            if (Thread.interrupted())                throw new InterruptedException();            Node node = addConditionWaiter();            int savedState = fullyRelease(node);            final long deadline = System.nanoTime() + nanosTimeout;            int interruptMode = 0;            while (!isOnSyncQueue(node)) {                if (nanosTimeout <= 0L) {                    transferAfterCancelledWait(node);                    break;                }                if (nanosTimeout >= spinForTimeoutThreshold)                    LockSupport.parkNanos(this, nanosTimeout);                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)                    break;                nanosTimeout = deadline - System.nanoTime();            }            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)                interruptMode = REINTERRUPT;            if (node.nextWaiter != null)                unlinkCancelledWaiters();            if (interruptMode != 0)                reportInterruptAfterWait(interruptMode);            return deadline - System.nanoTime();        }        /**         * Implements absolute timed condition wait.         * <ol>         * <li> If current thread is interrupted, throw InterruptedException.         * <li> Save lock state returned by {@link #getState}.         * <li> Invoke {@link #release} with saved state as argument,         *      throwing IllegalMonitorStateException if it fails.         * <li> Block until signalled, interrupted, or timed out.         * <li> Reacquire by invoking specialized version of         *      {@link #acquire} with saved state as argument.         * <li> If interrupted while blocked in step 4, throw InterruptedException.         * <li> If timed out while blocked in step 4, return false, else true.         * </ol>         */        public final boolean awaitUntil(Date deadline)                throws InterruptedException {            long abstime = deadline.getTime();            if (Thread.interrupted())                throw new InterruptedException();            Node node = addConditionWaiter();            int savedState = fullyRelease(node);            boolean timedout = false;            int interruptMode = 0;            while (!isOnSyncQueue(node)) {                if (System.currentTimeMillis() > abstime) {                    timedout = transferAfterCancelledWait(node);                    break;                }                LockSupport.parkUntil(this, abstime);                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)                    break;            }            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)                interruptMode = REINTERRUPT;            if (node.nextWaiter != null)                unlinkCancelledWaiters();            if (interruptMode != 0)                reportInterruptAfterWait(interruptMode);            return !timedout;        }        /**         * Implements timed condition wait.         * <ol>         * <li> If current thread is interrupted, throw InterruptedException.         * <li> Save lock state returned by {@link #getState}.         * <li> Invoke {@link #release} with saved state as argument,         *      throwing IllegalMonitorStateException if it fails.         * <li> Block until signalled, interrupted, or timed out.         * <li> Reacquire by invoking specialized version of         *      {@link #acquire} with saved state as argument.         * <li> If interrupted while blocked in step 4, throw InterruptedException.         * <li> If timed out while blocked in step 4, return false, else true.         * </ol>         */        public final boolean await(long time, TimeUnit unit)                throws InterruptedException {            long nanosTimeout = unit.toNanos(time);            if (Thread.interrupted())                throw new InterruptedException();            Node node = addConditionWaiter();            int savedState = fullyRelease(node);            final long deadline = System.nanoTime() + nanosTimeout;            boolean timedout = false;            int interruptMode = 0;            while (!isOnSyncQueue(node)) {                if (nanosTimeout <= 0L) {                    timedout = transferAfterCancelledWait(node);                    break;                }                if (nanosTimeout >= spinForTimeoutThreshold)                    LockSupport.parkNanos(this, nanosTimeout);                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)                    break;                nanosTimeout = deadline - System.nanoTime();            }            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)                interruptMode = REINTERRUPT;            if (node.nextWaiter != null)                unlinkCancelledWaiters();            if (interruptMode != 0)                reportInterruptAfterWait(interruptMode);            return !timedout;        }    }    private static final Unsafe unsafe = Unsafe.getUnsafe();    private static final long stateOffset;    private static final long headOffset;    private static final long tailOffset;    private static final long waitStatusOffset;    private static final long nextOffset;    static {        try {            stateOffset = unsafe.objectFieldOffset                (AbstractQueuedSynchronizer.class.getDeclaredField("state"));            headOffset = unsafe.objectFieldOffset                (AbstractQueuedSynchronizer.class.getDeclaredField("head"));            tailOffset = unsafe.objectFieldOffset                (AbstractQueuedSynchronizer.class.getDeclaredField("tail"));            waitStatusOffset = unsafe.objectFieldOffset                (Node.class.getDeclaredField("waitStatus"));            nextOffset = unsafe.objectFieldOffset                (Node.class.getDeclaredField("next"));        } catch (Exception ex) { throw new Error(ex); }    }    /**     * CAS head field. Used only by enq.     */    private final boolean compareAndSetHead(Node update) {        return unsafe.compareAndSwapObject(this, headOffset, null, update);    }    /**     * CAS tail field. Used only by enq.     */    private final boolean compareAndSetTail(Node expect, Node update) {        return unsafe.compareAndSwapObject(this, tailOffset, expect, update);    }    /**     * CAS waitStatus field of a node.     */    private static final boolean compareAndSetWaitStatus(Node node,                                                         int expect,                                                         int update) {        return unsafe.compareAndSwapInt(node, waitStatusOffset,                                        expect, update);    }    /**     * CAS next field of a node.     */    private static final boolean compareAndSetNext(Node node,                                                   Node expect,                                                   Node update) {        return unsafe.compareAndSwapObject(node, nextOffset, expect, update);    }}
阅读全文
0 0
原创粉丝点击