经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
死磕 java集合之ArrayBlockingQueue源码分析
来源:cnblogs  作者:彤哥读源码  时间:2019/4/22 9:23:35  对本文有异议

问题

(1)ArrayBlockingQueue的实现方式?

(2)ArrayBlockingQueue是否需要扩容?

(3)ArrayBlockingQueue有什么缺点?

简介

ArrayBlockingQueue是java并发包下一个以数组实现的阻塞队列,它是线程安全的,至于是否需要扩容,请看下面的分析。

队列

队列,是一种线性表,它的特点是先进先出,又叫FIFO,就像我们平常排队一样,先到先得,即先进入队列的人先出队。

源码分析

主要属性

  1. // 使用数组存储元素
  2. final Object[] items;
  3. // 取元素的指针
  4. int takeIndex;
  5. // 放元素的指针
  6. int putIndex;
  7. // 元素数量
  8. int count;
  9. // 保证并发访问的锁
  10. final ReentrantLock lock;
  11. // 非空条件
  12. private final Condition notEmpty;
  13. // 非满条件
  14. private final Condition notFull;

通过属性我们可以得出以下几个重要信息:

(1)利用数组存储元素;

(2)通过放指针和取指针来标记下一次操作的位置;

(3)利用重入锁来保证并发安全;

主要构造方法

  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. // 初始化数组
  8. this.items = new Object[capacity];
  9. // 创建重入锁及两个条件
  10. lock = new ReentrantLock(fair);
  11. notEmpty = lock.newCondition();
  12. notFull = lock.newCondition();
  13. }

通过构造方法我们可以得出以下两个结论:

(1)ArrayBlockingQueue初始化时必须传入容量,也就是数组的大小;

(2)可以通过构造方法控制重入锁的类型是公平锁还是非公平锁;

入队

入队有四个方法,它们分别是add(E e)、offer(E e)、put(E e)、offer(E e, long timeout, TimeUnit unit),它们有什么区别呢?

  1. public boolean add(E e) {
  2. // 调用父类的add(e)方法
  3. return super.add(e);
  4. }
  5. // super.add(e)
  6. public boolean add(E e) {
  7. // 调用offer(e)如果成功返回true,如果失败抛出异常
  8. if (offer(e))
  9. return true;
  10. else
  11. throw new IllegalStateException("Queue full");
  12. }
  13. public boolean offer(E e) {
  14. // 元素不可为空
  15. checkNotNull(e);
  16. final ReentrantLock lock = this.lock;
  17. // 加锁
  18. lock.lock();
  19. try {
  20. if (count == items.length)
  21. // 如果数组满了就返回false
  22. return false;
  23. else {
  24. // 如果数组没满就调用入队方法并返回true
  25. enqueue(e);
  26. return true;
  27. }
  28. } finally {
  29. // 解锁
  30. lock.unlock();
  31. }
  32. }
  33. public void put(E e) throws InterruptedException {
  34. checkNotNull(e);
  35. final ReentrantLock lock = this.lock;
  36. // 加锁,如果线程中断了抛出异常
  37. lock.lockInterruptibly();
  38. try {
  39. // 如果数组满了,使用notFull等待
  40. // notFull等待的意思是说现在队列满了
  41. // 只有取走一个元素后,队列才不满
  42. // 然后唤醒notFull,然后继续现在的逻辑
  43. // 这里之所以使用while而不是if
  44. // 是因为有可能多个线程阻塞在lock上
  45. // 即使唤醒了可能其它线程先一步修改了队列又变成满的了
  46. // 这时候需要再次等待
  47. while (count == items.length)
  48. notFull.await();
  49. // 入队
  50. enqueue(e);
  51. } finally {
  52. // 解锁
  53. lock.unlock();
  54. }
  55. }
  56. public boolean offer(E e, long timeout, TimeUnit unit)
  57. throws InterruptedException {
  58. checkNotNull(e);
  59. long nanos = unit.toNanos(timeout);
  60. final ReentrantLock lock = this.lock;
  61. // 加锁
  62. lock.lockInterruptibly();
  63. try {
  64. // 如果数组满了,就阻塞nanos纳秒
  65. // 如果唤醒这个线程时依然没有空间且时间到了就返回false
  66. while (count == items.length) {
  67. if (nanos <= 0)
  68. return false;
  69. nanos = notFull.awaitNanos(nanos);
  70. }
  71. // 入队
  72. enqueue(e);
  73. return true;
  74. } finally {
  75. // 解锁
  76. lock.unlock();
  77. }
  78. }
  79. private void enqueue(E x) {
  80. final Object[] items = this.items;
  81. // 把元素直接放在放指针的位置上
  82. items[putIndex] = x;
  83. // 如果放指针到数组尽头了,就返回头部
  84. if (++putIndex == items.length)
  85. putIndex = 0;
  86. // 数量加1
  87. count++;
  88. // 唤醒notEmpty,因为入队了一个元素,所以肯定不为空了
  89. notEmpty.signal();
  90. }

(1)add(e)时如果队列满了则抛出异常;

(2)offer(e)时如果队列满了则返回false;

(3)put(e)时如果队列满了则使用notFull等待;

(4)offer(e, timeout, unit)时如果队列满了则等待一段时间后如果队列依然满就返回false;

(5)利用放指针循环使用数组来存储元素;

出队

出队有四个方法,它们分别是remove()、poll()、take()、poll(long timeout, TimeUnit unit),它们有什么区别呢?

  1. public E remove() {
  2. // 调用poll()方法出队
  3. E x = poll();
  4. if (x != null)
  5. // 如果有元素出队就返回这个元素
  6. return x;
  7. else
  8. // 如果没有元素出队就抛出异常
  9. throw new NoSuchElementException();
  10. }
  11. public E poll() {
  12. final ReentrantLock lock = this.lock;
  13. // 加锁
  14. lock.lock();
  15. try {
  16. // 如果队列没有元素则返回null,否则出队
  17. return (count == 0) ? null : dequeue();
  18. } finally {
  19. lock.unlock();
  20. }
  21. }
  22. public E take() throws InterruptedException {
  23. final ReentrantLock lock = this.lock;
  24. // 加锁
  25. lock.lockInterruptibly();
  26. try {
  27. // 如果队列无元素,则阻塞等待在条件notEmpty上
  28. while (count == 0)
  29. notEmpty.await();
  30. // 有元素了再出队
  31. return dequeue();
  32. } finally {
  33. // 解锁
  34. lock.unlock();
  35. }
  36. }
  37. public E poll(long timeout, TimeUnit unit) throws InterruptedException {
  38. long nanos = unit.toNanos(timeout);
  39. final ReentrantLock lock = this.lock;
  40. // 加锁
  41. lock.lockInterruptibly();
  42. try {
  43. // 如果队列无元素,则阻塞等待nanos纳秒
  44. // 如果下一次这个线程获得了锁但队列依然无元素且已超时就返回null
  45. while (count == 0) {
  46. if (nanos <= 0)
  47. return null;
  48. nanos = notEmpty.awaitNanos(nanos);
  49. }
  50. return dequeue();
  51. } finally {
  52. lock.unlock();
  53. }
  54. }
  55. private E dequeue() {
  56. final Object[] items = this.items;
  57. @SuppressWarnings("unchecked")
  58. // 取取指针位置的元素
  59. E x = (E) items[takeIndex];
  60. // 把取指针位置设为null
  61. items[takeIndex] = null;
  62. // 取指针前移,如果数组到头了就返回数组前端循环利用
  63. if (++takeIndex == items.length)
  64. takeIndex = 0;
  65. // 元素数量减1
  66. count--;
  67. if (itrs != null)
  68. itrs.elementDequeued();
  69. // 唤醒notFull条件
  70. notFull.signal();
  71. return x;
  72. }

(1)remove()时如果队列为空则抛出异常;

(2)poll()时如果队列为空则返回null;

(3)take()时如果队列为空则阻塞等待在条件notEmpty上;

(4)poll(timeout, unit)时如果队列为空则阻塞等待一段时间后如果还为空就返回null;

(5)利用取指针循环从数组中取元素;

总结

(1)ArrayBlockingQueue不需要扩容,因为是初始化时指定容量,并循环利用数组;

(2)ArrayBlockingQueue利用takeIndex和putIndex循环利用数组;

(3)入队和出队各定义了四组方法为满足不同的用途;

(4)利用重入锁和两个条件保证并发安全;

彩蛋

(1)论BlockingQueue中的那些方法?

BlockingQueue是所有阻塞队列的顶级接口,它里面定义了一批方法,它们有什么区别呢?

操作 抛出异常 返回特定值 阻塞 超时
入队 add(e) offer(e)——false put(e) offer(e, timeout, unit)
出队 remove() poll()——null take() poll(timeout, unit)
检查 element() peek()——null - -

(2)ArrayBlockingQueue有哪些缺点呢?

a)队列长度固定且必须在初始化时指定,所以使用之前一定要慎重考虑好容量;

b)如果消费速度跟不上入队速度,则会导致提供者线程一直阻塞,且越阻塞越多,非常危险;

c)只使用了一个锁来控制入队出队,效率较低,那是不是可以借助分段的思想把入队出队分裂成两个锁呢?且听下回分解。


欢迎关注我的公众号“彤哥读源码”,查看更多源码系列文章, 与彤哥一起畅游源码的海洋。

qrcode

原文链接:http://www.cnblogs.com/tong-yuan/p/ArrayBlockingQueue.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号