1.首先看下aqs的继承关系,可以帮助我们更好的了解源码

  1. public abstract class AbstractQueuedSynchronizer
  2. extends AbstractOwnableSynchronizer
  3. implements java.io.Serializable

接口“Serializable”不用多说了吧,序列化作用。那么我们重点讲讲“abstractOwnableSynchronizer”中有啥方法。

1.1.abstractOwnableSynchronizer

  1. /**
  2. * The current owner of exclusive mode synchronization.
  3. */
  4. private transient Thread exclusiveOwnerThread;
  5. /**
  6. * Sets the thread that currently owns exclusive access.
  7. * A {@code null} argument indicates that no thread owns access.
  8. * This method does not otherwise impose any synchronization or
  9. * {@code volatile} field accesses.
  10. * @param thread the owner thread
  11. */
  12. protected final void setExclusiveOwnerThread(Thread thread) {
  13. exclusiveOwnerThread = thread;
  14. }
  15. /**
  16. * Returns the thread last set by {@code setExclusiveOwnerThread},
  17. * or {@code null} if never set. This method does not otherwise
  18. * impose any synchronization or {@code volatile} field accesses.
  19. * @return the owner thread
  20. */
  21. protected final Thread getExclusiveOwnerThread() {
  22. return exclusiveOwnerThread;
  23. }

其实注释上已经讲得很清楚了,定义了一个属性,是一个线程,该线程是:在独占模式下同步锁的拥有者,并有两个和他有关的方法,get,set。
看到这里提到一个名字:独占模式,难不成还有别的模式,那么别的模式叫什么,有哪些实例?这个问题我会在下一篇文章讲到。

2.源码分析

2.1.内部静态类:node

  1. static final class Node {
  2. /** Marker to indicate a node is waiting in shared mode */
  3. static final Node SHARED = new Node();
  4. /** Marker to indicate a node is waiting in exclusive mode */
  5. static final Node EXCLUSIVE = null;
  6. /** waitStatus value to indicate thread has cancelled */
  7. static final int CANCELLED = 1;
  8. /** waitStatus value to indicate successor's thread needs unparking */
  9. static final int SIGNAL = -1;
  10. /** waitStatus value to indicate thread is waiting on condition */
  11. static final int CONDITION = -2;
  12. /**
  13. * waitStatus value to indicate the next acquireShared should
  14. * unconditionally propagate
  15. */
  16. static final int PROPAGATE = -3;
  17. /**
  18. * Status field, taking on only the values:
  19. * SIGNAL: The successor of this node is (or will soon be)
  20. * blocked (via park), so the current node must
  21. * unpark its successor when it releases or
  22. * cancels. To avoid races, acquire methods must
  23. * first indicate they need a signal,
  24. * then retry the atomic acquire, and then,
  25. * on failure, block.
  26. * CANCELLED: This node is cancelled due to timeout or interrupt.
  27. * Nodes never leave this state. In particular,
  28. * a thread with cancelled node never again blocks.
  29. * CONDITION: This node is currently on a condition queue.
  30. * It will not be used as a sync queue node
  31. * until transferred, at which time the status
  32. * will be set to 0. (Use of this value here has
  33. * nothing to do with the other uses of the
  34. * field, but simplifies mechanics.)
  35. * PROPAGATE: A releaseShared should be propagated to other
  36. * nodes. This is set (for head node only) in
  37. * doReleaseShared to ensure propagation
  38. * continues, even if other operations have
  39. * since intervened.
  40. * 0: None of the above
  41. *
  42. * The values are arranged numerically to simplify use.
  43. * Non-negative values mean that a node doesn't need to
  44. * signal. So, most code doesn't need to check for particular
  45. * values, just for sign.
  46. *
  47. * The field is initialized to 0 for normal sync nodes, and
  48. * CONDITION for condition nodes. It is modified using CAS
  49. * (or when possible, unconditional volatile writes).
  50. */
  51. volatile int waitStatus;
  52. /**
  53. * Link to predecessor node that current node/thread relies on
  54. * for checking waitStatus. Assigned during enqueuing, and nulled
  55. * out (for sake of GC) only upon dequeuing. Also, upon
  56. * cancellation of a predecessor, we short-circuit while
  57. * finding a non-cancelled one, which will always exist
  58. * because the head node is never cancelled: A node becomes
  59. * head only as a result of successful acquire. A
  60. * cancelled thread never succeeds in acquiring, and a thread only
  61. * cancels itself, not any other node.
  62. */
  63. volatile Node prev;
  64. /**
  65. * Link to the successor node that the current node/thread
  66. * unparks upon release. Assigned during enqueuing, adjusted
  67. * when bypassing cancelled predecessors, and nulled out (for
  68. * sake of GC) when dequeued. The enq operation does not
  69. * assign next field of a predecessor until after attachment,
  70. * so seeing a null next field does not necessarily mean that
  71. * node is at end of queue. However, if a next field appears
  72. * to be null, we can scan prev's from the tail to
  73. * double-check. The next field of cancelled nodes is set to
  74. * point to the node itself instead of null, to make life
  75. * easier for isOnSyncQueue.
  76. */
  77. volatile Node next;
  78. /**
  79. * The thread that enqueued this node. Initialized on
  80. * construction and nulled out after use.
  81. */
  82. volatile Thread thread;
  83. /**
  84. * Link to next node waiting on condition, or the special
  85. * value SHARED. Because condition queues are accessed only
  86. * when holding in exclusive mode, we just need a simple
  87. * linked queue to hold nodes while they are waiting on
  88. * conditions. They are then transferred to the queue to
  89. * re-acquire. And because conditions can only be exclusive,
  90. * we save a field by using special value to indicate shared
  91. * mode.
  92. */
  93. Node nextWaiter;
  94. /**
  95. * Returns true if node is waiting in shared mode.
  96. */
  97. final boolean isShared() {
  98. return nextWaiter == SHARED;
  99. }
  100. /**
  101. * Returns previous node, or throws NullPointerException if null.
  102. * Use when predecessor cannot be null. The null check could
  103. * be elided, but is present to help the VM.
  104. *
  105. * @return the predecessor of this node
  106. */
  107. final Node predecessor() throws NullPointerException {
  108. Node p = prev;
  109. if (p == null)
  110. throw new NullPointerException();
  111. else
  112. return p;
  113. }
  114. Node() { // Used to establish initial head or SHARED marker
  115. }
  116. Node(Thread thread, Node mode) { // Used by addWaiter
  117. this.nextWaiter = mode;
  118. this.thread = thread;
  119. }
  120. Node(Thread thread, int waitStatus) { // Used by Condition
  121. this.waitStatus = waitStatus;
  122. this.thread = thread;
  123. }
  124. }

我原封不动的把源码给copy下来了,包括注解。现在就分析下AQS核心这个内部静态类,干了什么?
从注解中我们发现,其有两种模式:共享模式、独占模式。
并且其中也有两个链表,链表中有“next”和“pre”属性,毫无疑问是一个双向链表:一个共享模式的链表、一个独占模式的链表。
所以看源码其实就三个东西:一个叫数据结构、一个叫算法、一个叫设计模式,加上网络基础知识,计算机基础知识,一般的源码肯定水到渠成的。

我们先看一个属性:waitStatus。等待状态,而且还被volatile修饰了,再看下它有几种状态:
·SIGNAL=-1:一个需要成功线程唤醒的状态 注:大家可以了解下park与wait、unpark与notify的用法的区别?可能对大家再并发线程或者一些特殊情况处理会有帮助。
·CANCELLED=1:当前线程已经被取消了,不难理解
·CONDITION=-2:表明当前线程还处于等待队列中
·PROPAGATE=-3:下一次的请求无条件传播
·0:以上都不是

next:表示下一个节点,prev:表示上一个节点,thread:表示该节点的线程,nextWaiter:只有共享模式下,这个值才会有值,是一种特殊的值,只会在共享模式下。所以是否是共享模式,就是通过该值确定的

在AQS中有头结点与尾结点,state:表示一个同步的状态,当前有没有现成获得锁就是通过它进行判断的。所以在aqs中除了用到了volatile,还用到了CAS,两者保证了其是线程安全的。

2.2.内部类:ConditionObject

2.2.1.继承关系:condition,主要两个方法:一个await与signal,是不是感觉和object中的方法wait与notify很相似。
2.2.2.内部解析
其实这个类就是AQS当中的等待队列,队列当中有两个节点,一个是头结点,一个尾结点。

3.独占锁之ReentrantLock

3.1.继承关系:lock

lock:堵塞获得锁
lockInterruptibly:堵塞获得锁,除非当前线程被中断
tryLock:尝试获得锁,成功返回true,失败返回fasle
unlock:释放锁
codition:创建一个等待队列

3.2.解读源码

3.2.1.抽象类Sync,继承了aqs,所以该类属于其基类,所以在他基础上,实现了公平锁与非公平锁
lock:抽象方法,子类实现

        /**
         * Performs {@link Lock#lock}. The main reason for subclassing
         * is to allow fast path for nonfair version.
         */
        abstract void lock();

nonfairTryAccuire:该方法中有一个int型的参数,所以表明该锁是可以重入的。

        /**
         * Performs non-fair tryLock.  tryAcquire is implemented in
         * subclasses, but both need nonfair try for trylock method.
         */
        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;
        }

先拿到当前线程,在获得是否有线程获得了该锁,如果没有线程获得该锁,则cas其state值,如果cas成功,说明当前线程获得锁成功,则将当前线程赋值给独占模式下所拥有的的线程,并返回true;
如果有线程获得了锁,则判断获得锁的线程是否就是当前线程,如果是,则state加上重入次数,返回true,否则fasle

tryRelease:尝试释放锁,参数也有个int参数,表示尝试释放重入的次数。

        protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }

这个代码没啥可以解释的吧,应该都能看得懂

isHeldExclusively:主要就是判断当前线程是否拿到了独占锁

        protected final boolean isHeldExclusively() {
            // While we must in general read state before owner,
            // we don't need to do so to check if current thread is owner
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

newCondition:创建一个等待队列

        final ConditionObject newCondition() {
            return new ConditionObject();
        }

getOwner:获取拥有锁的线程

        final ConditionObject newCondition() {
            return new ConditionObject();
        }

getHoldCount:获取当前线程获取锁的次数

        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }

isLocked:是否有线程获取了锁

        final boolean isLocked() {
            return getState() != 0;
        }

readObject:从流中获取一个实例,并将锁的状态设置为0

         /**
         * Reconstitutes the instance from a stream (that is, deserializes it).
         */
        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0); // reset to unlocked state
        }

3.2.2.NonFairSync—非公平锁

    /**
     * Sync object for non-fair locks
     */
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        /**
         * Performs lock.  Try immediate barge, backing up to normal
         * acquire on failure.
         */
        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

其实代码很简单,实现抽象类的lock:cas设置state锁的状态,如果成功,则将当前线程赋值给拥有锁线程属性;如果失败,则调用aqs的acquire(1)方法

    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

很简单,就是先尝试获取,如果失败,则将其加到等待队列中,并且等待唤醒争抢锁,除非线程中断,有兴趣的同学可以看看里面的代码,怎么进行争抢的。里面其实就是一个死循环,跳出循环只有两种可能,一种是成功,一种是线程中断,如果线程中断则取消请求

tryAcquire:其实调用的就是父类的nonfairTryAcquire

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }

3.2.3.FairSync—公平锁

    /**
     * Sync object for fair locks
     */
    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

        final void lock() {
            acquire(1);
        }

        /**
         * Fair version of tryAcquire.  Don't grant access unless
         * recursive call or no waiters or is first.
         */
        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;
        }
    }

lock:发现了与非公平锁有不一样的地方了吧。为啥是公平的,就是因为他不会一上来就去抢锁,而是先尝试(尝试自己有自己的实现逻辑),不行直接加到队列中去,看出他是公平的地方了吧。

tryAcquire:重点来了,公平锁在这个地方也有体现。首先会先判断是否有线程获得了锁,如果没有线程获得锁,则判断等待队列中是否只有一个线程等待,并且头结点的下一个节点线程是否是当前线程,如果是说明下一个可以争抢的节点就是他,所以直接cas锁的状态state,成功说明增强成功,设置占用线程,返回true;
如果有线程获得了锁,则判断获得锁的线程与当前线程是否一样,一样则增加重入次数。

注:有个地方希望大家注意一点,可能大家不仔细看的话,没有注意到这一点

    /**
     * Wakes up node's successor, if one exists.
     *
     * @param node the node
     */
    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);
    }

唤醒线程的时候,一般情况下,是直接唤醒成功获得锁线程节点的下一个节点,但是如果很巧的是,下一个节点被取消或者为null的情况,aqs会从队列底部去唤醒一个线程。

4.共享锁—CountDownLatch

同样,内部也有一个类Sync继承了aqs

    /**
     * Synchronization control For CountDownLatch.
     * Uses AQS state to represent count.
     */
    private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            setState(count);
        }

        int getCount() {
            return getState();
        }

        protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }

        protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    }

构造函数中的count,就是CountDownLatch中构造函数的参数。其实原理超级简单,所谓的CountDownLatch中共享模式其实就是把我们获取锁的时候反过来,我们刚开始锁的状态state是0,但是在该类中就必须是一个大于0的值,我们获得锁了,然后state在加,而该类则类似释放一样,在减,减到0了,说明锁释放了。

    /**
     * Constructs a {@code CountDownLatch} initialized with the given count.
     *
     * @param count the number of times {@link #countDown} must be invoked
     *        before threads can pass through {@link #await}
     * @throws IllegalArgumentException if {@code count} is negative
     */
    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }

构造函数,很清晰,其实就是new了一个aqs的实现类

看一下方法countDown

    /**
     * Decrements the count of the latch, releasing all waiting threads if
     * the count reaches zero.
     *
     * <p>If the current count is greater than zero then it is decremented.
     * If the new count is zero then all waiting threads are re-enabled for
     * thread scheduling purposes.
     *
     * <p>If the current count equals zero then nothing happens.
     */
    public void countDown() {
        sync.releaseShared(1);
    }

    /**
     * Returns the current count.
     *
     * <p>This method is typically used for debugging and testing purposes.
     *
     * @return the current count
     */
    public long getCount() {
        return sync.getCount();
    }

如果默认不传参数,则默认state-1

下面就是共享模式的代码

    /**
     * Acquires in shared uninterruptible mode.
     * @param arg the acquire argument
     */
    private void doAcquireShared(int arg) {
        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;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }