源码基于open jdk 11

ArrayBlockingQueue源码分析 - 图1

ArrayBlockingQueue是通过有界数组方式实现的阻塞队列 , 通过ReentrantLock实现线程安全,阻塞通过Condition实现,出队和入队使用同一把锁。

有两个内部类Itr 和 Itrs,Itrs内部又实现了Node类,像LinkedBlockingQueue和ConcurrentLinkedQueue都有Node类,但两个类有不同,该类的Node类定义在Itrs的内部类中

先来看下该类哪些属性

属性

  1. /** The queued items */
  2. final Object[] items;
  3. /** items index for next take, poll, peek or remove */
  4. int takeIndex;
  5. /** items index for next put, offer, or add */
  6. int putIndex;
  7. /** Number of elements in the queue */
  8. int count;
  9. /*
  10. * Concurrency control uses the classic two-condition algorithm
  11. * found in any textbook.
  12. */
  13. /** Main lock guarding all access */
  14. final ReentrantLock lock;
  15. /** Condition for waiting takes */
  16. private final Condition notEmpty;
  17. /** Condition for waiting puts */
  18. private final Condition notFull;
  19. /**
  20. * Shared state for currently active iterators, or null if there
  21. * are known not to be any. Allows queue operations to update
  22. * iterator state.
  23. */
  24. transient Itrs itrs;

内部类

Itr

  1. private class Itr implements Iterator<E> {
  2. /** Index to look for new nextItem; NONE at end */
  3. private int cursor;
  4. /** Element to be returned by next call to next(); null if none */
  5. private E nextItem;
  6. /** Index of nextItem; NONE if none, REMOVED if removed elsewhere */
  7. private int nextIndex;
  8. /** Last element returned; null if none or not detached. */
  9. private E lastItem;
  10. /** Index of lastItem, NONE if none, REMOVED if removed elsewhere */
  11. private int lastRet;
  12. /** Previous value of takeIndex, or DETACHED when detached */
  13. private int prevTakeIndex;
  14. /** Previous value of iters.cycles */
  15. private int prevCycles;
  16. /** Special index value indicating "not available" or "undefined" */
  17. private static final int NONE = -1;
  18. /**
  19. * Special index value indicating "removed elsewhere", that is,
  20. * removed by some operation other than a call to this.remove().
  21. */
  22. private static final int REMOVED = -2;
  23. /** Special value for prevTakeIndex indicating "detached mode" */
  24. private static final int DETACHED = -3;
  25. Itr() {
  26. lastRet = NONE;
  27. final ReentrantLock lock = ArrayBlockingQueue.this.lock;
  28. lock.lock();
  29. try {
  30. if (count == 0) {
  31. // assert itrs == null;
  32. cursor = NONE;
  33. nextIndex = NONE;
  34. prevTakeIndex = DETACHED;
  35. } else {
  36. final int takeIndex = ArrayBlockingQueue.this.takeIndex;
  37. prevTakeIndex = takeIndex;
  38. nextItem = itemAt(nextIndex = takeIndex);
  39. cursor = incCursor(takeIndex);
  40. if (itrs == null) {
  41. itrs = new Itrs(this);
  42. } else {
  43. itrs.register(this); // in this order
  44. itrs.doSomeSweeping(false);
  45. }
  46. prevCycles = itrs.cycles;
  47. // assert takeIndex >= 0;
  48. // assert prevTakeIndex == takeIndex;
  49. // assert nextIndex >= 0;
  50. // assert nextItem != null;
  51. }
  52. } finally {
  53. lock.unlock();
  54. }
  55. }
  56. boolean isDetached() {
  57. // assert lock.isHeldByCurrentThread();
  58. return prevTakeIndex < 0;
  59. }
  60. private int incCursor(int index) {
  61. // assert lock.isHeldByCurrentThread();
  62. if (++index == items.length) index = 0;
  63. if (index == putIndex) index = NONE;
  64. return index;
  65. }
  66. /**
  67. * Returns true if index is invalidated by the given number of
  68. * dequeues, starting from prevTakeIndex.
  69. */
  70. private boolean invalidated(int index, int prevTakeIndex,
  71. long dequeues, int length) {
  72. if (index < 0)
  73. return false;
  74. int distance = index - prevTakeIndex;
  75. if (distance < 0)
  76. distance += length;
  77. return dequeues > distance;
  78. }
  79. /**
  80. * Adjusts indices to incorporate all dequeues since the last
  81. * operation on this iterator. Call only from iterating thread.
  82. */
  83. private void incorporateDequeues() {
  84. // assert lock.isHeldByCurrentThread();
  85. // assert itrs != null;
  86. // assert !isDetached();
  87. // assert count > 0;
  88. final int cycles = itrs.cycles;
  89. final int takeIndex = ArrayBlockingQueue.this.takeIndex;
  90. final int prevCycles = this.prevCycles;
  91. final int prevTakeIndex = this.prevTakeIndex;
  92. if (cycles != prevCycles || takeIndex != prevTakeIndex) {
  93. final int len = items.length;
  94. // how far takeIndex has advanced since the previous
  95. // operation of this iterator
  96. long dequeues = (long) (cycles - prevCycles) * len
  97. + (takeIndex - prevTakeIndex);
  98. // Check indices for invalidation
  99. if (invalidated(lastRet, prevTakeIndex, dequeues, len))
  100. lastRet = REMOVED;
  101. if (invalidated(nextIndex, prevTakeIndex, dequeues, len))
  102. nextIndex = REMOVED;
  103. if (invalidated(cursor, prevTakeIndex, dequeues, len))
  104. cursor = takeIndex;
  105. if (cursor < 0 && nextIndex < 0 && lastRet < 0)
  106. detach();
  107. else {
  108. this.prevCycles = cycles;
  109. this.prevTakeIndex = takeIndex;
  110. }
  111. }
  112. }
  113. /**
  114. * Called when itrs should stop tracking this iterator, either
  115. * because there are no more indices to update (cursor < 0 &&
  116. * nextIndex < 0 && lastRet < 0) or as a special exception, when
  117. * lastRet >= 0, because hasNext() is about to return false for the
  118. * first time. Call only from iterating thread.
  119. */
  120. private void detach() {
  121. // Switch to detached mode
  122. // assert lock.isHeldByCurrentThread();
  123. // assert cursor == NONE;
  124. // assert nextIndex < 0;
  125. // assert lastRet < 0 || nextItem == null;
  126. // assert lastRet < 0 ^ lastItem != null;
  127. if (prevTakeIndex >= 0) {
  128. // assert itrs != null;
  129. prevTakeIndex = DETACHED;
  130. // try to unlink from itrs (but not too hard)
  131. itrs.doSomeSweeping(true);
  132. }
  133. }
  134. /**
  135. * For performance reasons, we would like not to acquire a lock in
  136. * hasNext in the common case. To allow for this, we only access
  137. * fields (i.e. nextItem) that are not modified by update operations
  138. * triggered by queue modifications.
  139. */
  140. public boolean hasNext() {
  141. if (nextItem != null)
  142. return true;
  143. noNext();
  144. return false;
  145. }
  146. private void noNext() {
  147. final ReentrantLock lock = ArrayBlockingQueue.this.lock;
  148. lock.lock();
  149. try {
  150. // assert cursor == NONE;
  151. // assert nextIndex == NONE;
  152. if (!isDetached()) {
  153. // assert lastRet >= 0;
  154. incorporateDequeues(); // might update lastRet
  155. if (lastRet >= 0) {
  156. lastItem = itemAt(lastRet);
  157. // assert lastItem != null;
  158. detach();
  159. }
  160. }
  161. // assert isDetached();
  162. // assert lastRet < 0 ^ lastItem != null;
  163. } finally {
  164. lock.unlock();
  165. }
  166. }
  167. public E next() {
  168. final E e = nextItem;
  169. if (e == null)
  170. throw new NoSuchElementException();
  171. final ReentrantLock lock = ArrayBlockingQueue.this.lock;
  172. lock.lock();
  173. try {
  174. if (!isDetached())
  175. incorporateDequeues();
  176. // assert nextIndex != NONE;
  177. // assert lastItem == null;
  178. lastRet = nextIndex;
  179. final int cursor = this.cursor;
  180. if (cursor >= 0) {
  181. nextItem = itemAt(nextIndex = cursor);
  182. // assert nextItem != null;
  183. this.cursor = incCursor(cursor);
  184. } else {
  185. nextIndex = NONE;
  186. nextItem = null;
  187. if (lastRet == REMOVED) detach();
  188. }
  189. } finally {
  190. lock.unlock();
  191. }
  192. return e;
  193. }
  194. public void forEachRemaining(Consumer<? super E> action) {
  195. Objects.requireNonNull(action);
  196. final ReentrantLock lock = ArrayBlockingQueue.this.lock;
  197. lock.lock();
  198. try {
  199. final E e = nextItem;
  200. if (e == null) return;
  201. if (!isDetached())
  202. incorporateDequeues();
  203. action.accept(e);
  204. if (isDetached() || cursor < 0) return;
  205. final Object[] items = ArrayBlockingQueue.this.items;
  206. for (int i = cursor, end = putIndex,
  207. to = (i < end) ? end : items.length;
  208. ; i = 0, to = end) {
  209. for (; i < to; i++)
  210. action.accept(itemAt(items, i));
  211. if (to == end) break;
  212. }
  213. } finally {
  214. // Calling forEachRemaining is a strong hint that this
  215. // iteration is surely over; supporting remove() after
  216. // forEachRemaining() is more trouble than it's worth
  217. cursor = nextIndex = lastRet = NONE;
  218. nextItem = lastItem = null;
  219. detach();
  220. lock.unlock();
  221. }
  222. }
  223. public void remove() {
  224. final ReentrantLock lock = ArrayBlockingQueue.this.lock;
  225. lock.lock();
  226. // assert lock.getHoldCount() == 1;
  227. try {
  228. if (!isDetached())
  229. incorporateDequeues(); // might update lastRet or detach
  230. final int lastRet = this.lastRet;
  231. this.lastRet = NONE;
  232. if (lastRet >= 0) {
  233. if (!isDetached())
  234. removeAt(lastRet);
  235. else {
  236. final E lastItem = this.lastItem;
  237. // assert lastItem != null;
  238. this.lastItem = null;
  239. if (itemAt(lastRet) == lastItem)
  240. removeAt(lastRet);
  241. }
  242. } else if (lastRet == NONE)
  243. throw new IllegalStateException();
  244. // else lastRet == REMOVED and the last returned element was
  245. // previously asynchronously removed via an operation other
  246. // than this.remove(), so nothing to do.
  247. if (cursor < 0 && nextIndex < 0)
  248. detach();
  249. } finally {
  250. lock.unlock();
  251. // assert lastRet == NONE;
  252. // assert lastItem == null;
  253. }
  254. }
  255. /**
  256. * Called to notify the iterator that the queue is empty, or that it
  257. * has fallen hopelessly behind, so that it should abandon any
  258. * further iteration, except possibly to return one more element
  259. * from next(), as promised by returning true from hasNext().
  260. */
  261. void shutdown() {
  262. // assert lock.isHeldByCurrentThread();
  263. cursor = NONE;
  264. if (nextIndex >= 0)
  265. nextIndex = REMOVED;
  266. if (lastRet >= 0) {
  267. lastRet = REMOVED;
  268. lastItem = null;
  269. }
  270. prevTakeIndex = DETACHED;
  271. // Don't set nextItem to null because we must continue to be
  272. // able to return it on next().
  273. //
  274. // Caller will unlink from itrs when convenient.
  275. }
  276. private int distance(int index, int prevTakeIndex, int length) {
  277. int distance = index - prevTakeIndex;
  278. if (distance < 0)
  279. distance += length;
  280. return distance;
  281. }
  282. /**
  283. * Called whenever an interior remove (not at takeIndex) occurred.
  284. *
  285. * @return true if this iterator should be unlinked from itrs
  286. */
  287. boolean removedAt(int removedIndex) {
  288. // assert lock.isHeldByCurrentThread();
  289. if (isDetached())
  290. return true;
  291. final int takeIndex = ArrayBlockingQueue.this.takeIndex;
  292. final int prevTakeIndex = this.prevTakeIndex;
  293. final int len = items.length;
  294. // distance from prevTakeIndex to removedIndex
  295. final int removedDistance =
  296. len * (itrs.cycles - this.prevCycles
  297. + ((removedIndex < takeIndex) ? 1 : 0))
  298. + (removedIndex - prevTakeIndex);
  299. // assert itrs.cycles - this.prevCycles >= 0;
  300. // assert itrs.cycles - this.prevCycles <= 1;
  301. // assert removedDistance > 0;
  302. // assert removedIndex != takeIndex;
  303. int cursor = this.cursor;
  304. if (cursor >= 0) {
  305. int x = distance(cursor, prevTakeIndex, len);
  306. if (x == removedDistance) {
  307. if (cursor == putIndex)
  308. this.cursor = cursor = NONE;
  309. }
  310. else if (x > removedDistance) {
  311. // assert cursor != prevTakeIndex;
  312. this.cursor = cursor = dec(cursor, len);
  313. }
  314. }
  315. int lastRet = this.lastRet;
  316. if (lastRet >= 0) {
  317. int x = distance(lastRet, prevTakeIndex, len);
  318. if (x == removedDistance)
  319. this.lastRet = lastRet = REMOVED;
  320. else if (x > removedDistance)
  321. this.lastRet = lastRet = dec(lastRet, len);
  322. }
  323. int nextIndex = this.nextIndex;
  324. if (nextIndex >= 0) {
  325. int x = distance(nextIndex, prevTakeIndex, len);
  326. if (x == removedDistance)
  327. this.nextIndex = nextIndex = REMOVED;
  328. else if (x > removedDistance)
  329. this.nextIndex = nextIndex = dec(nextIndex, len);
  330. }
  331. if (cursor < 0 && nextIndex < 0 && lastRet < 0) {
  332. this.prevTakeIndex = DETACHED;
  333. return true;
  334. }
  335. return false;
  336. }
  337. /**
  338. * Called whenever takeIndex wraps around to zero.
  339. *
  340. * @return true if this iterator should be unlinked from itrs
  341. */
  342. boolean takeIndexWrapped() {
  343. // assert lock.isHeldByCurrentThread();
  344. if (isDetached())
  345. return true;
  346. if (itrs.cycles - prevCycles > 1) {
  347. // All the elements that existed at the time of the last
  348. // operation are gone, so abandon further iteration.
  349. shutdown();
  350. return true;
  351. }
  352. return false;
  353. }
  354. // /** Uncomment for debugging. */
  355. // public String toString() {
  356. // return ("cursor=" + cursor + " " +
  357. // "nextIndex=" + nextIndex + " " +
  358. // "lastRet=" + lastRet + " " +
  359. // "nextItem=" + nextItem + " " +
  360. // "lastItem=" + lastItem + " " +
  361. // "prevCycles=" + prevCycles + " " +
  362. // "prevTakeIndex=" + prevTakeIndex + " " +
  363. // "size()=" + size() + " " +
  364. // "remainingCapacity()=" + remainingCapacity());
  365. // }
  366. }

Itrs

class Itrs {

    /**
     * Node in a linked list of weak iterator references.
     */
    private class Node extends WeakReference<Itr> {
        Node next;

        Node(Itr iterator, Node next) {
            super(iterator);
            this.next = next;
        }
    }

    /** Incremented whenever takeIndex wraps around to 0 */
    int cycles;

    /** Linked list of weak iterator references */
    private Node head;

    /** Used to expunge stale iterators */
    private Node sweeper;

    private static final int SHORT_SWEEP_PROBES = 4;
    private static final int LONG_SWEEP_PROBES = 16;

    Itrs(Itr initial) {
        register(initial);
    }

    /**
     * Sweeps itrs, looking for and expunging stale iterators.
     * If at least one was found, tries harder to find more.
     * Called only from iterating thread.
     *
     * @param tryHarder whether to start in try-harder mode, because
     * there is known to be at least one iterator to collect
     */
    void doSomeSweeping(boolean tryHarder) {
        // assert lock.isHeldByCurrentThread();
        // assert head != null;
        int probes = tryHarder ? LONG_SWEEP_PROBES : SHORT_SWEEP_PROBES;
        Node o, p;
        final Node sweeper = this.sweeper;
        boolean passedGo;   // to limit search to one full sweep

        if (sweeper == null) {
            o = null;
            p = head;
            passedGo = true;
        } else {
            o = sweeper;
            p = o.next;
            passedGo = false;
        }

        for (; probes > 0; probes--) {
            if (p == null) {
                if (passedGo)
                    break;
                o = null;
                p = head;
                passedGo = true;
            }
            final Itr it = p.get();
            final Node next = p.next;
            if (it == null || it.isDetached()) {
                // found a discarded/exhausted iterator
                probes = LONG_SWEEP_PROBES; // "try harder"
                // unlink p
                p.clear();
                p.next = null;
                if (o == null) {
                    head = next;
                    if (next == null) {
                        // We've run out of iterators to track; retire
                        itrs = null;
                        return;
                    }
                }
                else
                    o.next = next;
            } else {
                o = p;
            }
            p = next;
        }

        this.sweeper = (p == null) ? null : o;
    }

    /**
     * Adds a new iterator to the linked list of tracked iterators.
     */
    void register(Itr itr) {
        // assert lock.isHeldByCurrentThread();
        head = new Node(itr, head);
    }

    /**
     * Called whenever takeIndex wraps around to 0.
     *
     * Notifies all iterators, and expunges any that are now stale.
     */
    void takeIndexWrapped() {
        // assert lock.isHeldByCurrentThread();
        cycles++;
        for (Node o = null, p = head; p != null;) {
            final Itr it = p.get();
            final Node next = p.next;
            if (it == null || it.takeIndexWrapped()) {
                // unlink p
                // assert it == null || it.isDetached();
                p.clear();
                p.next = null;
                if (o == null)
                    head = next;
                else
                    o.next = next;
            } else {
                o = p;
            }
            p = next;
        }
        if (head == null)   // no more iterators to track
            itrs = null;
    }

    /**
     * Called whenever an interior remove (not at takeIndex) occurred.
     *
     * Notifies all iterators, and expunges any that are now stale.
     */
    void removedAt(int removedIndex) {
        for (Node o = null, p = head; p != null;) {
            final Itr it = p.get();
            final Node next = p.next;
            if (it == null || it.removedAt(removedIndex)) {
                // unlink p
                // assert it == null || it.isDetached();
                p.clear();
                p.next = null;
                if (o == null)
                    head = next;
                else
                    o.next = next;
            } else {
                o = p;
            }
            p = next;
        }
        if (head == null)   // no more iterators to track
            itrs = null;
    }

    /**
     * Called whenever the queue becomes empty.
     *
     * Notifies all active iterators that the queue is empty,
     * clears all weak refs, and unlinks the itrs datastructure.
     */
    void queueIsEmpty() {
        // assert lock.isHeldByCurrentThread();
        for (Node p = head; p != null; p = p.next) {
            Itr it = p.get();
            if (it != null) {
                p.clear();
                it.shutdown();
            }
        }
        head = null;
        itrs = null;
    }

    /**
     * Called whenever an element has been dequeued (at takeIndex).
     */
    void elementDequeued() {
        // assert lock.isHeldByCurrentThread();
        if (count == 0)
            queueIsEmpty();
        else if (takeIndex == 0)
            takeIndexWrapped();
    }
}

瓦雀