线程在JDK中是非常重要的一块内容,所有的应用服务都离不开线程的相关操作,对于大量线程的使用都是推荐使用线程池来进行操作和管理,JDK本身提供的线程池在服务中经常被使用到,以往经常使用Executors来创建,但是阿里规范中也指出了其存在的隐患,从源码来看,内部大量使用了队列相关的类,所以在深入线程部分之前,我们需要了解队列相关的内容,本文就以ArrayBlockingQueue开始对JDK中的常用的队列进行说明

前言

首先我们需要明白其结构特点:ArrayBlockingQueue是数组实现的线程安全的有界的阻塞队列

  • 内部是通过数组来实现的,从源码部分也能看出来
  • 线程安全说明的是ArrayBlockingQueue内部通过ReentrantLock保护竞争资源,实现了多线程对竞争资源的互斥访问
  • 有界,ArrayBlockingQueue对应的数组是有界限的
  • 阻塞队列,是指多线程访问竞争资源时,当竞争资源已被某线程获取时,其它要获取该资源的线程需要阻塞等待;而且,ArrayBlockingQueue是按 FIFO(先进先出)原则对元素进行排序,元素都是从尾部插入到队列,从头部开始返回。

从上边的结构特点我们基本上能够理解了其主要的实现,下面来稍微具体描述下其内部实现:

  1. ArrayBlockingQueue继承于AbstractQueue,并且它实现了BlockingQueue接口
  2. ArrayBlockingQueue内部是通过Object[]数组保存数据的,印证上边通过数组实现的特点。ArrayBlockingQueue的大小,即数组的容量是创建ArrayBlockingQueue时需要指定的
  3. ArrayBlockingQueue中包含一个ReentrantLock对象(lock)。ReentrantLock是可重入的互斥锁,ArrayBlockingQueue就是根据该互斥锁实现“多线程对竞争资源的互斥访问”。而且,ReentrantLock分为公平锁和非公平锁,关于具体使用公平锁还是非公平锁,在创建ArrayBlockingQueue时可以指定;而且,ArrayBlockingQueue默认会使用非公平锁。
  4. ArrayBlockingQueue中包含两个Condition对象(notEmpty和notFull)。Condition又依赖于ArrayBlockingQueue而存在,通过Condition可以实现对ArrayBlockingQueue的更精确的访问。例如,若线程A要取数据时,数组正好为空,则该线程会执行notEmpty.await()进行等待;当其它某个线程(线程B)向数组中插入了数据之后,会调用notEmpty.signal()唤醒“notEmpty上的等待线程”。此时,线程A会被唤醒从而得以继续运行。若线程C要插入数据时,数组已满,则该线程会它执行notFull.await()进行等待;当其它某个线程(线程D)取出数据之后,会调用notFull.signal()唤醒“notFull上的等待线程”。此时,线程C就会被唤醒从而得以继续运行。

ArrayBlockingQueue中入队出队操作如上例子相对比较简单也比较好理解,复杂部分在于迭代器部分,下面通过源码来一步一步说明

类定义

  1. public class ArrayBlockingQueue<E> extends AbstractQueue<E>
  2. implements BlockingQueue<E>, java.io.Serializable

常量/变量

  1. /** The queued items */
  2. // 队列内部实现使用数组
  3. final Object[] items;
  4. /** items index for next take, poll, peek or remove */
  5. // 下一次从队列中获取的队列元素索引
  6. int takeIndex;
  7. /** items index for next put, offer, or add */
  8. // 下一次插入队列的队列元素索引
  9. int putIndex;
  10. /** Number of elements in the queue */
  11. // 队列长度
  12. int count;
  13. /*
  14. * Concurrency control uses the classic two-condition algorithm
  15. * found in any textbook.
  16. */
  17. /** Main lock guarding all access */
  18. // 互斥锁
  19. final ReentrantLock lock;
  20. /** Condition for waiting takes */
  21. // 非空信号量
  22. private final Condition notEmpty;
  23. /** Condition for waiting puts */
  24. // 非满信号量
  25. private final Condition notFull;
  26. /**
  27. * Shared state for currently active iterators, or null if there
  28. * are known not to be any. Allows queue operations to update
  29. * iterator state.
  30. */
  31. // 迭代器维护列表,每次队列更新操作需要更新迭代器保证正确性
  32. // 第二部分迭代器部分单独说明,这里先简单理解就好
  33. transient Itrs itrs = null;

构造方法

默认使用非公平锁,创建一个互斥锁和两个Condition来帮助完成整个队列的操作,从构造方法上也可以看到,队列容量是必须要传的

  1. public ArrayBlockingQueue(int capacity) {
  2. this(capacity, false);
  3. }
  4. public ArrayBlockingQueue(int capacity, boolean fair) {
  5. if (capacity <= 0)
  6. throw new IllegalArgumentException();
  7. this.items = new Object[capacity];
  8. lock = new ReentrantLock(fair);
  9. notEmpty = lock.newCondition();
  10. notFull = lock.newCondition();
  11. }
  12. public ArrayBlockingQueue(int capacity, boolean fair,
  13. Collection<? extends E> c) {
  14. this(capacity, fair);
  15. final ReentrantLock lock = this.lock;
  16. // 使用锁操作确保可见性,因为item这里本身并不保证可见性,防止并发操作下线程内存中数组不一致的情况出现
  17. lock.lock(); // Lock only for visibility, not mutual exclusion
  18. try {
  19. int i = 0;
  20. try {
  21. for (E e : c) {
  22. checkNotNull(e);
  23. items[i++] = e;
  24. }
  25. } catch (ArrayIndexOutOfBoundsException ex) {
  26. throw new IllegalArgumentException();
  27. }
  28. count = i;
  29. // 队列被占满 putIndex置0,从这里也能看出来这个数组是循环利用的,达到最大值,置成0,类似环状数组
  30. putIndex = (i == capacity) ? 0 : i;
  31. } finally {
  32. lock.unlock();
  33. }
  34. }

重要方法

enqueue

入队操作,添加元素到队列中,当且仅当持有lock的时候。每次添加完毕后通过notEmpty.signal()唤醒之前通过notEmpty.await()进入等待状态的线程

  1. /**
  2. * Inserts element at current put position, advances, and signals.
  3. * Call only when holding lock.
  4. */
  5. private void enqueue(E x) {
  6. // assert lock.getHoldCount() == 1;
  7. // assert items[putIndex] == null;
  8. final Object[] items = this.items;
  9. items[putIndex] = x;
  10. // 达到数组最大索引时,putIndex指向数组为0的位置
  11. if (++putIndex == items.length)
  12. putIndex = 0;
  13. // 队列长度加1
  14. count++;
  15. notEmpty.signal();
  16. }

dequeue

出队操作,获取队列元素,当且仅当持有lock的时候。每次获取完毕后通过notFull.signal()唤醒之前通过notFull.await()进入等待状态的线程

  1. /**
  2. * Extracts element at current take position, advances, and signals.
  3. * Call only when holding lock.
  4. */
  5. private E dequeue() {
  6. // assert lock.getHoldCount() == 1;
  7. // assert items[takeIndex] != null;
  8. final Object[] items = this.items;
  9. @SuppressWarnings("unchecked")
  10. E x = (E) items[takeIndex];
  11. // 指向置空,删除队列中的这个元素
  12. items[takeIndex] = null;
  13. // takeIndex同putIndex,达到数组最大索引时,指向数组为0的位置
  14. if (++takeIndex == items.length)
  15. takeIndex = 0;
  16. // 队列长度减1
  17. count--;
  18. // 更新迭代器中的元素数据,保证在并发操作中迭代的正确性
  19. // 后边迭代器说明时可以回来看下
  20. if (itrs != null)
  21. itrs.elementDequeued();
  22. notFull.signal();
  23. return x;
  24. }

add/offer/put

入队操作有以下几个方法,同时各个方法有些许不同

  1. public boolean add(E e) {
  2. // 调用offer获取结果 不成功则抛错
  3. return super.add(e);
  4. }
  5. public boolean add(E e) {
  6. if (offer(e))
  7. return true;
  8. else
  9. throw new IllegalStateException("Queue full");
  10. }
  11. public boolean offer(E e) {
  12. // 检查元素是否为空
  13. checkNotNull(e);
  14. final ReentrantLock lock = this.lock;
  15. lock.lock();
  16. try {
  17. // 队列已满则返回false
  18. if (count == items.length)
  19. return false;
  20. else {
  21. // 入队
  22. enqueue(e);
  23. return true;
  24. }
  25. } finally {
  26. lock.unlock();
  27. }
  28. }
  29. public boolean offer(E e, long timeout, TimeUnit unit)
  30. throws InterruptedException {
  31. checkNotNull(e);
  32. // 阻塞等待时间 纳秒
  33. long nanos = unit.toNanos(timeout);
  34. final ReentrantLock lock = this.lock;
  35. // lockInterruptibly方法可被中断
  36. lock.lockInterruptibly();
  37. try {
  38. while (count == items.length) {
  39. if (nanos <= 0)
  40. // 超时返回
  41. return false;
  42. // 队列已满则阻塞等待nanos纳秒
  43. nanos = notFull.awaitNanos(nanos);
  44. }
  45. // 入队
  46. enqueue(e);
  47. return true;
  48. } finally {
  49. lock.unlock();
  50. }
  51. }
  52. public void put(E e) throws InterruptedException {
  53. checkNotNull(e);
  54. final ReentrantLock lock = this.lock;
  55. lock.lockInterruptibly();
  56. try {
  57. while (count == items.length)
  58. // 队列已满阻塞等待
  59. notFull.await();
  60. // 入队
  61. enqueue(e);
  62. } finally {
  63. lock.unlock();
  64. }
  65. }

向队列中添加元素主要包含上述3个方法,不同之处如下:

方法名(含参数) 说明
add(E e) 实际调用offer,元素入队操作,成功则返回true,失败则抛错IllegalStateException
offer(E e) 元素入队操作,成功返回true,失败返回false
put(E e) 可中断,元素入队操作,队列已满则阻塞等待直到被通知可入队
offer(E e, long timeout, TimeUnit unit) 可中断,元素入队操作,设置阻塞等待超时时间,超时则返回false,成功入队则返回true

以上操作其实已经在BlockingQueue接口中定义,需根据接口自行实现

poll/take/peek/remove

出队方法同入队方法,也稍有不同,如下

  1. public E poll() {
  2. final ReentrantLock lock = this.lock;
  3. lock.lock();
  4. try {
  5. // 队列无元素返回null,有元素则出队列操作
  6. return (count == 0) ? null : dequeue();
  7. } finally {
  8. lock.unlock();
  9. }
  10. }
  11. public E take() throws InterruptedException {
  12. final ReentrantLock lock = this.lock;
  13. // 可中断
  14. lock.lockInterruptibly();
  15. try {
  16. while (count == 0)
  17. // 队列为空则阻塞等待直到被唤醒
  18. notEmpty.await();
  19. return dequeue();
  20. } finally {
  21. lock.unlock();
  22. }
  23. }
  24. public E poll(long timeout, TimeUnit unit) throws InterruptedException {
  25. long nanos = unit.toNanos(timeout);
  26. final ReentrantLock lock = this.lock;
  27. lock.lockInterruptibly();
  28. try {
  29. while (count == 0) {
  30. if (nanos <= 0)
  31. return null;
  32. // 阻塞等待超时nanos纳秒
  33. nanos = notEmpty.awaitNanos(nanos);
  34. }
  35. return dequeue();
  36. } finally {
  37. lock.unlock();
  38. }
  39. }
  40. public E peek() {
  41. final ReentrantLock lock = this.lock;
  42. lock.lock();
  43. try {
  44. // 返回队列takeIndex索引处的值,不进行出队列操作,元素不会被删除
  45. return itemAt(takeIndex); // null when queue is empty
  46. } finally {
  47. lock.unlock();
  48. }
  49. }
  50. public boolean remove(Object o) {
  51. if (o == null) return false;
  52. final Object[] items = this.items;
  53. final ReentrantLock lock = this.lock;
  54. lock.lock();
  55. try {
  56. if (count > 0) {
  57. final int putIndex = this.putIndex;
  58. int i = takeIndex;
  59. do {
  60. if (o.equals(items[i])) {
  61. // 移除i处的元素,同时队列进行整理,移除元素后的元素依次向前移动进行填补空缺
  62. removeAt(i);
  63. return true;
  64. }
  65. // 循环到数组长度,从0继续
  66. if (++i == items.length)
  67. i = 0;
  68. } while (i != putIndex);
  69. }
  70. return false;
  71. } finally {
  72. lock.unlock();
  73. }
  74. }

从队列中获取元素主要包含上述4个方法,除peek不执行出队操作外,remove是删除之外,其余均需执行出队操作,不同之处如下:

方法名(含参数) 说明
poll() 出队操作,队列为空返回null,不为空则返回对应元素
take() 可中断,出队操作,队列为空则阻塞等待直到被通知获取值返回
poll(long timeout, TimeUnit unit) 可中断,出队操作,设置阻塞等待超时时间,超时则返回null,成功则返回对应元素
peek() 仅仅返回队列元素的值,但是不执行出队操作
remove(Object o) 删除队列中的对应元素(可处于队列任何位置),队列需进行整理

removeAt

移除指定位置的队列元素并调整队列

  1. /**
  2. * Deletes item at array index removeIndex.
  3. * Utility for remove(Object) and iterator.remove.
  4. * Call only when holding lock.
  5. */
  6. void removeAt(final int removeIndex) {
  7. // assert lock.getHoldCount() == 1;
  8. // assert items[removeIndex] != null;
  9. // assert removeIndex >= 0 && removeIndex < items.length;
  10. final Object[] items = this.items;
  11. // 移除队列元素索引是队列出队索引时,参考出队操作即可
  12. if (removeIndex == takeIndex) {
  13. // removing front item; just advance
  14. // 移除队列元素置空
  15. items[takeIndex] = null;
  16. // 调整队列出队索引
  17. if (++takeIndex == items.length)
  18. takeIndex = 0;
  19. // 队列长度减1
  20. count--;
  21. // 如果有迭代器则需要更新,这部分后边说
  22. if (itrs != null)
  23. itrs.elementDequeued();
  24. } else {
  25. // 到这里表明删除的元素非队列出队索引,删除元素在队列中间
  26. // an "interior" remove
  27. // slide over all others up through putIndex.
  28. final int putIndex = this.putIndex;
  29. // 调整队列元素,队列删除元素后的所有元素向前移动一位
  30. for (int i = removeIndex;;) {
  31. int next = i + 1;
  32. if (next == items.length)
  33. next = 0;
  34. if (next != putIndex) {
  35. items[i] = items[next];
  36. i = next;
  37. } else {
  38. // next = putIndex 说明是putIndex前一个元素,则置空更新putIndex即可结束
  39. items[i] = null;
  40. this.putIndex = i;
  41. break;
  42. }
  43. }
  44. count--;
  45. // 同步迭代器操作,后面进行说明
  46. if (itrs != null)
  47. itrs.removedAt(removeIndex);
  48. }
  49. // 唤醒入队线程
  50. notFull.signal();
  51. }

源码在方法中多次将操作的类成员变量赋予方法内部的局部变量,例如这里的 ReentrantLock lock = this.lock,其实是为了加快程序运行效率,每次都直接引用类成员,比如this.lock这样的读取操作相对于在方法内部直接操作方法栈的局部变量效率相对要低一点,涉及到了JVM部分,不详细说明,有兴趣可以自行查找相关资料

迭代器说明

以上源码部分为队列操作部分,整体上来看算是很好理解了,下面说明最复杂的迭代器部分

  1. public Iterator<E> iterator() {
  2. return new Itr();
  3. }

对于外部调用方来说,需要先获取对应的迭代器,源码如上,从这个地方我们能明白一件事,迭代器是调用这个方法那个时间的队列的类似于快照的保存,保存了那个时刻的队列状态,在下面的内部类源码中我们也能看到保存了哪些属性,这里没有保存队列内部具体元素,所以会造成一个比较大的问题,就是在多线程频繁的入队出队操作如何保证迭代器取值的正确性?当然,如果我们把队列元素也保存一份,本身也是不正确的。迭代器的复杂部分就在于此,保证迭代器正确性导致了迭代器源码的复杂性

这里先给出结论:

  1. 创建的迭代器Itr会保存当时队列的状态(不保存队列元素值)
  2. 创建的迭代器会放入Itrs(迭代器维护列表)中进行统一的维护和管理
  3. 在每次next()操作时会更新迭代器状态查看是都用完或失效,通过Itrs的doSomeSweeping进行清理无效迭代器
  4. 出队操作时会通过itrs.elementDequeued()更新迭代器维护列表Itrs
  5. 首次创建迭代器时会保存下一次调用next方法的值,故在调用hasNext时为true,在next()调用前队列空了,再调用next()依旧会返回值,算是一种保护
  6. 在创建了迭代器之后,队列中的元素被两次循环替代后,则判定此迭代器无效

迭代器相关内部类

内部类主要在迭代时使用,从iterator方法可以看出,每次调用时都会重新创建一个Itr对象,那么如何保证增删改时迭代器的正确性?看下内部实现

  1. private class Itr implements Iterator<E> {
  2. /** Index to look for new nextItem; NONE at end */
  3. // 指向下一个迭代元素的游标,结束时为NONE(-1)
  4. private int cursor;
  5. /** Element to be returned by next call to next(); null if none */
  6. // 下次调用next()返回的元素,无则返回null,这里即对应结论上的5
  7. private E nextItem;
  8. /** Index of nextItem; NONE if none, REMOVED if removed elsewhere */
  9. // 下一个元素nextItem的索引值,空的话返回NONE(-1),如果被移除了则返回REMOVED(-2)
  10. private int nextIndex;
  11. /** Last element returned; null if none or not detached. */
  12. // 上一次调用next()返回的元素,无则返回null
  13. private E lastItem;
  14. /** Index of lastItem, NONE if none, REMOVED if removed elsewhere */
  15. // 上一个元素的索引值,空的话返回NONE,如果被移除了则返回REMOVED
  16. private int lastRet;
  17. /** Previous value of takeIndex, or DETACHED when detached */
  18. // 上一个takeIndex对应的值,当处于无效状态时为DETACHED(-3),以这个变量标识迭代器DETACHED状态
  19. private int prevTakeIndex;
  20. /** Previous value of iters.cycles */
  21. // 上一个cycles的值
  22. private int prevCycles;
  23. /** Special index value indicating "not available" or "undefined" */
  24. // 标识不可用值或未定义值
  25. private static final int NONE = -1;
  26. /**
  27. * Special index value indicating "removed elsewhere", that is,
  28. * removed by some operation other than a call to this.remove().
  29. */
  30. // 标识元素被移除
  31. private static final int REMOVED = -2;
  32. /** Special value for prevTakeIndex indicating "detached mode" */
  33. // 标识prevTakeIndex为无效状态
  34. private static final int DETACHED = -3;
  35. Itr() {
  36. // assert lock.getHoldCount() == 0;
  37. // 构造时上一个元素索引为空
  38. lastRet = NONE;
  39. // 使用互斥锁
  40. final ReentrantLock lock = ArrayBlockingQueue.this.lock;
  41. lock.lock();
  42. try {
  43. // 队列为空,初始化变量
  44. if (count == 0) {
  45. // assert itrs == null;
  46. cursor = NONE;
  47. nextIndex = NONE;
  48. // 无效状态的迭代器
  49. prevTakeIndex = DETACHED;
  50. } else {
  51. // 此时队列不为空
  52. // 记录出队的takeIndex
  53. final int takeIndex = ArrayBlockingQueue.this.takeIndex;
  54. prevTakeIndex = takeIndex;
  55. // 下一次使用迭代返回的值,这里就已经保存好了调用next的返回值
  56. nextItem = itemAt(nextIndex = takeIndex);
  57. // 游标指向takeIndex+1
  58. cursor = incCursor(takeIndex);
  59. // 使用Itrs来维护所有的迭代器
  60. if (itrs == null) {
  61. // 空则创建
  62. itrs = new Itrs(this);
  63. } else {
  64. // 非空将次迭代器注册
  65. itrs.register(this); // in this order
  66. // 清理迭代器,每次创建新迭代器时都会进行一次简单的清理操作
  67. itrs.doSomeSweeping(false);
  68. }
  69. // 保存队列循环的次数,cycles在itrs进行解释
  70. prevCycles = itrs.cycles;
  71. // assert takeIndex >= 0;
  72. // assert prevTakeIndex == takeIndex;
  73. // assert nextIndex >= 0;
  74. // assert nextItem != null;
  75. }
  76. } finally {
  77. lock.unlock();
  78. }
  79. }
  80. // 判断迭代器是否已经无效,通过prevTakeIndex来判断
  81. boolean isDetached() {
  82. // assert lock.getHoldCount() == 1;
  83. return prevTakeIndex < 0;
  84. }
  85. // 游标值+1
  86. private int incCursor(int index) {
  87. // assert lock.getHoldCount() == 1;
  88. // 达到最大值从0开始
  89. if (++index == items.length)
  90. index = 0;
  91. // 与下一个入队元素位置相同,则表示队列已无元素,置NONE
  92. if (index == putIndex)
  93. index = NONE;
  94. return index;
  95. }
  96. /**
  97. * Returns true if index is invalidated by the given number of
  98. * dequeues, starting from prevTakeIndex.
  99. */
  100. // 从prevTakeIndex开始,队列索引index无效则返回true
  101. // 在incorporateDequeues中使用,比较index,prevTakeIndex的距离与实际距离
  102. private boolean invalidated(int index, int prevTakeIndex,
  103. long dequeues, int length) {
  104. // 初始化时设置小于0
  105. if (index < 0)
  106. return false;
  107. // 当前index与prevTakeIndex的距离
  108. int distance = index - prevTakeIndex;
  109. // 发生循环操作,很好理解,加上数组length,即为正确的距离
  110. if (distance < 0)
  111. distance += length;
  112. // 如果distance小于实际距离,则无效返回true
  113. return dequeues > distance;
  114. }
  115. /**
  116. * Adjusts indices to incorporate all dequeues since the last
  117. * operation on this iterator. Call only from iterating thread.
  118. */
  119. // 迭代操作后元素出队调整索引
  120. private void incorporateDequeues() {
  121. // assert lock.getHoldCount() == 1;
  122. // assert itrs != null;
  123. // assert !isDetached();
  124. // assert count > 0;
  125. // 获取当前变量
  126. final int cycles = itrs.cycles;
  127. final int takeIndex = ArrayBlockingQueue.this.takeIndex;
  128. final int prevCycles = this.prevCycles;
  129. final int prevTakeIndex = this.prevTakeIndex;
  130. // cycles != prevCycles 表示队列已经被循环使用过,相当于循环到0重新入队出队
  131. // takeIndex != prevTakeIndex 表示队列元素有出队,需重新排序
  132. if (cycles != prevCycles || takeIndex != prevTakeIndex) {
  133. final int len = items.length;
  134. // how far takeIndex has advanced since the previous
  135. // operation of this iterator
  136. // 队列实际移动的长度
  137. long dequeues = (cycles - prevCycles) * len
  138. + (takeIndex - prevTakeIndex);
  139. // Check indices for invalidation
  140. // lastRet处元素被移除了
  141. if (invalidated(lastRet, prevTakeIndex, dequeues, len))
  142. lastRet = REMOVED;
  143. // nextIndex处元素被移除了
  144. if (invalidated(nextIndex, prevTakeIndex, dequeues, len))
  145. nextIndex = REMOVED;
  146. // 游标索引无效置为当前队列takeIndex
  147. if (invalidated(cursor, prevTakeIndex, dequeues, len))
  148. cursor = takeIndex;
  149. // 迭代器无效进行清理操作
  150. if (cursor < 0 && nextIndex < 0 && lastRet < 0)
  151. detach();
  152. else {
  153. // 更新索引
  154. this.prevCycles = cycles;
  155. this.prevTakeIndex = takeIndex;
  156. }
  157. }
  158. }
  159. /**
  160. * Called when itrs should stop tracking this iterator, either
  161. * because there are no more indices to update (cursor < 0 &&
  162. * nextIndex < 0 && lastRet < 0) or as a special exception, when
  163. * lastRet >= 0, because hasNext() is about to return false for the
  164. * first time. Call only from iterating thread.
  165. */
  166. //
  167. private void detach() {
  168. // Switch to detached mode
  169. // assert lock.getHoldCount() == 1;
  170. // assert cursor == NONE;
  171. // assert nextIndex < 0;
  172. // assert lastRet < 0 || nextItem == null;
  173. // assert lastRet < 0 ^ lastItem != null;
  174. if (prevTakeIndex >= 0) {
  175. // assert itrs != null;
  176. // 设置迭代器DETACHED状态,无效状态
  177. prevTakeIndex = DETACHED;
  178. // try to unlink from itrs (but not too hard)
  179. // 所有的迭代器进行一次清理
  180. itrs.doSomeSweeping(true);
  181. }
  182. }
  183. /**
  184. * For performance reasons, we would like not to acquire a lock in
  185. * hasNext in the common case. To allow for this, we only access
  186. * fields (i.e. nextItem) that are not modified by update operations
  187. * triggered by queue modifications.
  188. */
  189. // 出于对性能的考虑,这里不会进行加锁
  190. public boolean hasNext() {
  191. // assert lock.getHoldCount() == 0;
  192. // 直接判断nextItem,故首次初始化时后续清空队列这里nextItem不为空,会返回第一个队列值
  193. if (nextItem != null)
  194. return true;
  195. // nextItem为空时才会进入noNext
  196. noNext();
  197. return false;
  198. }
  199. // 无元素,清理
  200. private void noNext() {
  201. final ReentrantLock lock = ArrayBlockingQueue.this.lock;
  202. lock.lock();
  203. try {
  204. // assert cursor == NONE;
  205. // assert nextIndex == NONE;
  206. // prevTakeIndex >= 0,需要进行处理
  207. if (!isDetached()) {
  208. // assert lastRet >= 0;
  209. incorporateDequeues(); // might update lastRet
  210. if (lastRet >= 0) {
  211. // 保存lastItem值,remove方法中需要用到
  212. lastItem = itemAt(lastRet);
  213. // assert lastItem != null;
  214. detach();
  215. }
  216. }
  217. // assert isDetached();
  218. // assert lastRet < 0 ^ lastItem != null;
  219. } finally {
  220. lock.unlock();
  221. }
  222. }
  223. public E next() {
  224. // assert lock.getHoldCount() == 0;
  225. // 迭代返回值,每次调用next前已经确定了nextItem值
  226. final E x = nextItem;
  227. if (x == null)
  228. throw new NoSuchElementException();
  229. final ReentrantLock lock = ArrayBlockingQueue.this.lock;
  230. lock.lock();
  231. try {
  232. if (!isDetached())
  233. incorporateDequeues();
  234. // assert nextIndex != NONE;
  235. // assert lastItem == null;
  236. // next调用之后调用remove删除元素的时候使用
  237. lastRet = nextIndex;
  238. final int cursor = this.cursor;
  239. if (cursor >= 0) {
  240. // 下一次迭代返回值
  241. nextItem = itemAt(nextIndex = cursor);
  242. // assert nextItem != null;
  243. // 游标加1
  244. this.cursor = incCursor(cursor);
  245. } else {
  246. // 无下一个迭代元素
  247. nextIndex = NONE;
  248. nextItem = null;
  249. }
  250. } finally {
  251. lock.unlock();
  252. }
  253. return x;
  254. }
  255. public void remove() {
  256. // assert lock.getHoldCount() == 0;
  257. final ReentrantLock lock = ArrayBlockingQueue.this.lock;
  258. lock.lock();
  259. try {
  260. if (!isDetached())
  261. incorporateDequeues(); // might update lastRet or detach
  262. final int lastRet = this.lastRet;
  263. this.lastRet = NONE;
  264. // 删除时需要用到lastRet
  265. if (lastRet >= 0) {
  266. if (!isDetached())
  267. removeAt(lastRet);
  268. else {
  269. // 处理在hasNext()返回false之后调用iterator .remove()的特殊情况
  270. final E lastItem = this.lastItem;
  271. // assert lastItem != null;
  272. this.lastItem = null;
  273. // 和预期元素一致才进行删除
  274. if (itemAt(lastRet) == lastItem)
  275. removeAt(lastRet);
  276. }
  277. } else if (lastRet == NONE)
  278. // lastRet为NONE时会抛错
  279. throw new IllegalStateException();
  280. // else lastRet == REMOVED and the last returned element was
  281. // previously asynchronously removed via an operation other
  282. // than this.remove(), so nothing to do.
  283. if (cursor < 0 && nextIndex < 0)
  284. detach();
  285. } finally {
  286. lock.unlock();
  287. // assert lastRet == NONE;
  288. // assert lastItem == null;
  289. }
  290. }
  291. /**
  292. * Called to notify the iterator that the queue is empty, or that it
  293. * has fallen hopelessly behind, so that it should abandon any
  294. * further iteration, except possibly to return one more element
  295. * from next(), as promised by returning true from hasNext().
  296. */
  297. // 队列为空或者无效时应清理掉,更新内部变量值
  298. void shutdown() {
  299. // assert lock.getHoldCount() == 1;
  300. cursor = NONE;
  301. if (nextIndex >= 0)
  302. nextIndex = REMOVED;
  303. if (lastRet >= 0) {
  304. lastRet = REMOVED;
  305. lastItem = null;
  306. }
  307. prevTakeIndex = DETACHED;
  308. // nextItem不置空是因为有可能调用的next方法需要用到
  309. // Don't set nextItem to null because we must continue to be
  310. // able to return it on next().
  311. //
  312. // Caller will unlink from itrs when convenient.
  313. }
  314. // 计算index与prevTakeIndex的距离
  315. private int distance(int index, int prevTakeIndex, int length) {
  316. int distance = index - prevTakeIndex;
  317. if (distance < 0)
  318. distance += length;
  319. return distance;
  320. }
  321. /**
  322. * Called whenever an interior remove (not at takeIndex) occurred.
  323. *
  324. * @return true if this iterator should be unlinked from itrs
  325. */
  326. // 队列内部元素被删除时调用,保证迭代器的正确性
  327. boolean removedAt(int removedIndex) {
  328. // assert lock.getHoldCount() == 1;
  329. // 当前迭代器无效时直接返回true
  330. if (isDetached())
  331. return true;
  332. final int cycles = itrs.cycles;
  333. final int takeIndex = ArrayBlockingQueue.this.takeIndex;
  334. final int prevCycles = this.prevCycles;
  335. final int prevTakeIndex = this.prevTakeIndex;
  336. final int len = items.length;
  337. int cycleDiff = cycles - prevCycles;
  338. // 删除的索引位置小于takeIndex,循环次数+1
  339. if (removedIndex < takeIndex)
  340. cycleDiff++;
  341. // 删除元素的实际距离
  342. final int removedDistance =
  343. (cycleDiff * len) + (removedIndex - prevTakeIndex);
  344. // assert removedDistance >= 0;
  345. int cursor = this.cursor;
  346. if (cursor >= 0) {
  347. int x = distance(cursor, prevTakeIndex, len);
  348. // 游标指向被删除的元素位置
  349. if (x == removedDistance) {
  350. // 已经没有元素了,置NONE
  351. if (cursor == putIndex)
  352. this.cursor = cursor = NONE;
  353. }
  354. // 游标已经超过removedDistance,索引游标需-1,因为删除元素算在了游标内,
  355. // 需减1才能保证队列删除元素之后整体元素位置调整之后迭代器这里的正确性
  356. else if (x > removedDistance) {
  357. // assert cursor != prevTakeIndex;
  358. this.cursor = cursor = dec(cursor);
  359. }
  360. }
  361. int lastRet = this.lastRet;
  362. // lastRet同上
  363. if (lastRet >= 0) {
  364. int x = distance(lastRet, prevTakeIndex, len);
  365. if (x == removedDistance)
  366. this.lastRet = lastRet = REMOVED;
  367. else if (x > removedDistance)
  368. this.lastRet = lastRet = dec(lastRet);
  369. }
  370. // nextIndex同上
  371. int nextIndex = this.nextIndex;
  372. if (nextIndex >= 0) {
  373. int x = distance(nextIndex, prevTakeIndex, len);
  374. if (x == removedDistance)
  375. this.nextIndex = nextIndex = REMOVED;
  376. else if (x > removedDistance)
  377. this.nextIndex = nextIndex = dec(nextIndex);
  378. }
  379. // 迭代器无效状态
  380. else if (cursor < 0 && nextIndex < 0 && lastRet < 0) {
  381. this.prevTakeIndex = DETACHED;
  382. return true;
  383. }
  384. return false;
  385. }
  386. /**
  387. * Called whenever takeIndex wraps around to zero.
  388. *
  389. * @return true if this iterator should be unlinked from itrs
  390. */
  391. // 每当takeIndex循环到0时调用
  392. boolean takeIndexWrapped() {
  393. // assert lock.getHoldCount() == 1;
  394. if (isDetached())
  395. return true;
  396. if (itrs.cycles - prevCycles > 1) {
  397. // All the elements that existed at the time of the last
  398. // operation are gone, so abandon further iteration.
  399. // 迭代器所有元素都已经在入队出队中不存在了,需置迭代器无效,这里也能看到相差2的时候已经无效了
  400. shutdown();
  401. return true;
  402. }
  403. return false;
  404. }
  405. }

提一句,下面的Itrs中的Node使用了弱引用,这可以在迭代器实例被使用完时(例如将其置为null)被GC及时的回收掉,同样涉及到JVM,自行查找相关资料吧

  1. class Itrs {
  2. /**
  3. * Node in a linked list of weak iterator references.
  4. */
  5. // 继承WeakReference实现Node的弱引用,这里也能看出来是链表
  6. private class Node extends WeakReference<Itr> {
  7. Node next;
  8. Node(Itr iterator, Node next) {
  9. super(iterator);
  10. this.next = next;
  11. }
  12. }
  13. /** Incremented whenever takeIndex wraps around to 0 */
  14. // takeIndex循环到0时加1,记录循环次数
  15. int cycles = 0;
  16. /** Linked list of weak iterator references */
  17. // 头节点
  18. private Node head;
  19. /** Used to expunge stale iterators */
  20. // 记录上次清理到的节点,方便下次使用
  21. private Node sweeper = null;
  22. // 每次迭代器清理操作时有两种模式,一种查找次数少,一种查找次数多
  23. private static final int SHORT_SWEEP_PROBES = 4;
  24. private static final int LONG_SWEEP_PROBES = 16;
  25. Itrs(Itr initial) {
  26. register(initial);
  27. }
  28. /**
  29. * Sweeps itrs, looking for and expunging stale iterators.
  30. * If at least one was found, tries harder to find more.
  31. * Called only from iterating thread.
  32. *
  33. * @param tryHarder whether to start in try-harder mode, because
  34. * there is known to be at least one iterator to collect
  35. */
  36. // 清理操作,通过tryHarder判断使用哪种清理模式
  37. void doSomeSweeping(boolean tryHarder) {
  38. // assert lock.getHoldCount() == 1;
  39. // assert head != null;
  40. int probes = tryHarder ? LONG_SWEEP_PROBES : SHORT_SWEEP_PROBES;
  41. Node o, p;
  42. final Node sweeper = this.sweeper;
  43. boolean passedGo; // to limit search to one full sweep
  44. if (sweeper == null) {
  45. // 无上次记录,则从头开始
  46. o = null;
  47. p = head;
  48. passedGo = true;
  49. } else {
  50. // 上次记录继续清理
  51. o = sweeper;
  52. p = o.next;
  53. passedGo = false;
  54. }
  55. for (; probes > 0; probes--) {
  56. if (p == null) {
  57. if (passedGo)
  58. break;
  59. o = null;
  60. p = head;
  61. passedGo = true;
  62. }
  63. final Itr it = p.get();
  64. final Node next = p.next;
  65. // 迭代器无效处理
  66. if (it == null || it.isDetached()) {
  67. // found a discarded/exhausted iterator
  68. // 发现一个迭代器无效则转换成try harder模式
  69. probes = LONG_SWEEP_PROBES; // "try harder"
  70. // unlink p
  71. p.clear();
  72. p.next = null;
  73. if (o == null) {
  74. head = next;
  75. if (next == null) {
  76. // We've run out of iterators to track; retire
  77. itrs = null;
  78. return;
  79. }
  80. }
  81. else
  82. o.next = next;
  83. } else {
  84. o = p;
  85. }
  86. p = next;
  87. }
  88. // 记录下次清理需要使用的节点数据
  89. this.sweeper = (p == null) ? null : o;
  90. }
  91. /**
  92. * Adds a new iterator to the linked list of tracked iterators.
  93. */
  94. // 将迭代器添加到迭代管理列表中,从头部添加
  95. void register(Itr itr) {
  96. // assert lock.getHoldCount() == 1;
  97. head = new Node(itr, head);
  98. }
  99. /**
  100. * Called whenever takeIndex wraps around to 0.
  101. *
  102. * Notifies all iterators, and expunges any that are now stale.
  103. */
  104. // 队列takeIndex循环到0时调用
  105. void takeIndexWrapped() {
  106. // assert lock.getHoldCount() == 1;
  107. // cycles加1记录循环次数
  108. cycles++;
  109. // 调用每个迭代器的takeIndexWrapped更新,同时清理无效迭代器
  110. for (Node o = null, p = head; p != null;) {
  111. final Itr it = p.get();
  112. final Node next = p.next;
  113. if (it == null || it.takeIndexWrapped()) {
  114. // unlink p
  115. // assert it == null || it.isDetached();
  116. p.clear();
  117. p.next = null;
  118. if (o == null)
  119. head = next;
  120. else
  121. o.next = next;
  122. } else {
  123. o = p;
  124. }
  125. p = next;
  126. }
  127. // 迭代管理列表空,无迭代器了
  128. if (head == null) // no more iterators to track
  129. itrs = null;
  130. }
  131. /**
  132. * Called whenever an interior remove (not at takeIndex) occurred.
  133. *
  134. * Notifies all iterators, and expunges any that are now stale.
  135. */
  136. // 队列删除元素时调用迭代管理列表的removedAt
  137. void removedAt(int removedIndex) {
  138. for (Node o = null, p = head; p != null;) {
  139. final Itr it = p.get();
  140. final Node next = p.next;
  141. // 迭代管理列表itrs调用每个迭代器的removedAt完成更新
  142. // 同时进行无效迭代器的清理
  143. if (it == null || it.removedAt(removedIndex)) {
  144. // unlink p
  145. // assert it == null || it.isDetached();
  146. p.clear();
  147. p.next = null;
  148. if (o == null)
  149. head = next;
  150. else
  151. o.next = next;
  152. } else {
  153. o = p;
  154. }
  155. p = next;
  156. }
  157. if (head == null) // no more iterators to track
  158. itrs = null;
  159. }
  160. /**
  161. * Called whenever the queue becomes empty.
  162. *
  163. * Notifies all active iterators that the queue is empty,
  164. * clears all weak refs, and unlinks the itrs datastructure.
  165. */
  166. // 队列为空时调用,迭代管理器将清理所有迭代器
  167. void queueIsEmpty() {
  168. // assert lock.getHoldCount() == 1;
  169. for (Node p = head; p != null; p = p.next) {
  170. Itr it = p.get();
  171. if (it != null) {
  172. p.clear();
  173. it.shutdown();
  174. }
  175. }
  176. head = null;
  177. itrs = null;
  178. }
  179. /**
  180. * Called whenever an element has been dequeued (at takeIndex).
  181. */
  182. // 队列出队时调用判断队列是否为空和队列循环次数
  183. void elementDequeued() {
  184. // assert lock.getHoldCount() == 1;
  185. if (count == 0)
  186. queueIsEmpty();
  187. else if (takeIndex == 0)
  188. takeIndexWrapped();
  189. }
  190. }

上边两个内部类实现了迭代器的相关操作,还是比较复杂的,通过一个中间类Itrs来完成对所有的迭代器的管理和更新操作,在队列操作时也要对迭代器的相关变量进行更新来保证迭代的正确性

总结

整体来说,ArrayBlockingQueue本身在队列操作这块并不是很复杂,基本的阻塞队列操作能理解就已经ok了。其中涉及到锁的部分先简单理解为好,毕竟涉及到了AQS,后续再进行介绍,在迭代器部分还是比较复杂的,不过最终都是为了保证迭代时数据的正确性,这个方面还是比较好理解的

以上的源码分析中,我们也能看出一些问题,ArrayBlockingQueue内部的大部分操作方法都需要先获取同一个ReentrantLock独占锁才能继续执行,这极大的降低了吞吐量,几乎每个操作都会阻塞其它操作,最主要是入队操作和出队操作之间互斥。所以ArrayBlockingQueue不适用于需要高吞吐量的高效率数据生成与消费场景。在常用的线程池中也没有用到ArrayBlockingQueue

以上内容如有问题欢迎指出,笔者验证后将及时修正,谢谢

JDK源码那些事儿之ArrayBlockingQueue的更多相关文章

  1. JDK源码那些事儿之并发ConcurrentHashMap上篇

    前面已经说明了HashMap以及红黑树的一些基本知识,对JDK8的HashMap也有了一定的了解,本篇就开始看看并发包下的ConcurrentHashMap,说实话,还是比较复杂的,笔者在这里也不会过 ...

  2. JDK源码那些事儿之红黑树基础下篇

    说到HashMap,就一定要说到红黑树,红黑树作为一种自平衡二叉查找树,是一种用途较广的数据结构,在jdk1.8中使用红黑树提升HashMap的性能,今天就来说一说红黑树,上一讲已经给出插入平衡的调整 ...

  3. JDK源码那些事儿之浅析Thread上篇

    JAVA中多线程的操作对于初学者而言是比较难理解的,其实联想到底层操作系统时我们可能会稍微明白些,对于程序而言最终都是硬件上运行二进制指令,然而,这些又太过底层,今天来看一下JAVA中的线程,浅析JD ...

  4. JDK源码那些事儿之LinkedBlockingQueue

    今天继续讲解阻塞队列,涉及到了常用线程池的其中一个队列LinkedBlockingQueue,从类命名部分我们就可以看出其用意,队列中很多方法名是通用的,只是每个队列内部实现不同,毕竟实现的都是同一个 ...

  5. JDK源码那些事儿之ConcurrentLinkedDeque

    非阻塞队列ConcurrentLinkedQueue我们已经了解过了,既然是Queue,那么是否有其双端队列实现呢?答案是肯定的,今天就继续说一说非阻塞双端队列实现ConcurrentLinkedDe ...

  6. JDK源码那些事儿之ConcurrentLinkedQueue

    阻塞队列的实现前面已经讲解完毕,今天我们继续了解源码中非阻塞队列的实现,接下来就看一看ConcurrentLinkedQueue非阻塞队列是怎么完成操作的 前言 JDK版本号:1.8.0_171 Co ...

  7. JDK源码那些事儿之LinkedBlockingDeque

    阻塞队列中目前还剩下一个比较特殊的队列实现,相比较前面讲解过的队列,本文中要讲的LinkedBlockingDeque比较容易理解了,但是与之前讲解过的阻塞队列又有些不同,从命名上你应该能看出一些端倪 ...

  8. JDK源码那些事儿之LinkedTransferQueue

    在JDK8的阻塞队列实现中还有两个未进行说明,今天继续对其中的一个阻塞队列LinkedTransferQueue进行源码分析,如果之前的队列分析已经让你对阻塞队列有了一定的了解,相信本文要讲解的Lin ...

  9. JDK源码那些事儿之DelayQueue

    作为阻塞队列的一员,DelayQueue(延迟队列)由于其特殊含义而使用在特定的场景之中,主要在于Delay这个词上,那么其内部是如何实现的呢?今天一起通过DelayQueue的源码来看一看其是如何完 ...

随机推荐

  1. Asp.Net Core中完成拒绝访问功能

    很多时候如果用户没有某个菜单的操作权限的话在页面是不应该显示出来的. @if (SignInManager.IsSignedIn(User) && User.IsInRole(&quo ...

  2. Java中的IO流之输出流|乐字节

    大家好,乐字节小乐又来了.上一篇给大家带来的是:Java中的IO流之输入流|乐字节,本文将继续讲述IO流之输出流.   一.输出流 1.抽象类:OutputStream 和 Writer Output ...

  3. Java program to find the largest element in array

    Java program to find the largest element in array Given an array of numbers, write a java program to ...

  4. 关于epoll,select,poll的理解

    select: 轮询+fd_set 1.采用fd_set存储fd(fd_set通过数组位图实现) 2.每次调用select,都需要把fd集合从用户态拷贝到内核态,fd越多开销越大 3.每次调用sele ...

  5. 【转帖】DevOps和SRE的区别

    DevOps和SRE的区别 https://zhuanlan.zhihu.com/p/87598465 DevOps 和 SRE 最近有一位朋友和我聊职业发展方向问题,聊了不少 DevOps 和 SR ...

  6. java当中JDBC当中的transaction例子

    [学习笔记] 7.jdbc的transaction例子: import java.sql.*; public class MySQlTransaction1 { public static void ...

  7. Python06之分支和循环1(三目运算符)

    Python 为了使得程序更加简洁而新引入过来的一个三目操作符,顾名思义就是有三个参数. 格式: x if 条件表达式 else y 先判断条件表达式真假,真则取 x 的值,否则取 y 的值. 例如: ...

  8. python 之 前端开发(盒子模型、页面布局、浮动、定位、z-index、overflow溢出)

    11.312 盒子模型 HTML文档中的每个元素都被比喻成矩形盒子, 盒子模型通过四个边界来描述:margin(外边距),border(边框),padding(内填充),content(内容区域),如 ...

  9. pod宿主机挂载pv存储过程

    1处的控制循环Control Loop应该是:VolumeManagerReconciler ----------------------------------------------------- ...

  10. 基本数据类型和string的转换