阻塞队列—ArrayBlockingQueue源码分析

开发 前端
ArrayBlockingQueue是一个阻塞队列,内部由ReentrantLock来实现线程安全,由Condition的await和signal来实现等待唤醒的功能。它的数据结构是数组,准确地说是一个循环数组(可以类比一个圆环),所有的下标在到达最大长度时自动从0继续开始。

 前言


ArrayBlockingQueue 由数组支持的有界阻塞队列,队列基于数组实现,容量大小在创建 ArrayBlockingQueue 对象时已经定义好。 此队列按照先进先出(FIFO)的原则对元素进行排序。支持公平锁和非公平锁,默认采用非公平锁。其数据结构如下图:

阻塞队列—ArrayBlockingQueue源码分析

 

  • 注:每一个线程在获取锁的时候可能都会排队等待,如果在等待时间上,先获取锁的线程和请求一定先被满足,那么这个锁就是公平的。反之,这个锁就是不公平的。公平的获取锁,也就是当前等待时间最长的线程先获取锁

队列创建

  1. BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(5); 

应用场景

在线程池中有比较多的应用,生产者消费者场景。

  • 先进先出队列(队列头的是最先进队的元素;队列尾的是最后进队的元素)
  • 有界队列(即初始化时指定的容量,就是队列最大的容量,不会出现扩容,容量满,则阻塞进队操作;容量空,则阻塞出队操作)
  • 队列不支持空元素
  • 公平性 (fairness)可以在构造函数中指定。

此类支持对等待的生产者线程和使用者线程进行排序的可选公平策略。默认情况下,不保证是这种排序。然而,通过在构造函数将公平性 (fairness) 设置为 true 而构造的队列允许按照 FIFO 顺序访问线程。公平性通常会降低吞吐量,但也减少了可变性和避免了“不平衡性”。

工作原理

ArrayBlockingQueue是对BlockingQueue的一个数组实现,它使用一把全局的锁并行对queue的读写操作,同时使用两个Condition阻塞容量为空时的取操作和容量满时的写操作。

基于 ReentrantLock 保证线程安全,根据 Condition 实现队列满时的阻塞。

  1. final ReentrantLock lock; 
  2.  
  3. private final Condition notEmpty; 
  4.  
  5. private final Condition notFull; 

 Lock的作用是提供独占锁机制,来保护竞争资源;而Condition是为了更加精细地对锁进行控制,它依赖于Lock,通过某个条件对多线程进行控制。

notEmpty表示“锁的非空条件”。当某线程想从队列中取数据时,而此时又没有数据,则该线程通过notEmpty.await()进行等待;当其它线程向队列中插入了元素之后,就调用notEmpty.signal()唤醒“之前通过notEmpty.await()进入等待状态的线程”。 同理,notFull表示“锁的满条件”。当某线程想向队列中插入元素,而此时队列已满时,该线程等待;当其它线程从队列中取出元素之后,就唤醒该等待的线程。

  • 试图向已满队列中放入元素会导致放入操作受阻塞,直到BlockingQueue里有新的唤空间才会被醒继续操作; 试图从空队列中检索元素将导致类似阻塞,直到BlocingkQueue进了新货才会被唤醒。

源码分析

以下源码分析基于JDK1.8

定义

ArrayBlockingQueue的类继承关系如下:

  其包含的方法定义如下:

阻塞队列—ArrayBlockingQueue源码分析

 成员属性

  1. /** 真正存入数据的数组 */ 
  2.    final Object[] items; 
  3.  
  4.    /** take,poll,peek or remove 的下一个索引 */ 
  5.    int takeIndex; 
  6.  
  7.    /** put,offer,or add 下一个索引 */ 
  8.    int putIndex; 
  9.  
  10.    /** 队列中元素个数 */ 
  11.    int count
  12.  
  13.    /** 可重入锁 */ 
  14.    final ReentrantLock lock; 
  15.  
  16.    /** 如果数组是空的,在该Condition上等待 */ 
  17.    private final Condition notEmpty; 
  18.  
  19.    /** 如果数组是满的,在该Condition上等待 */ 
  20.    private final Condition notFull; 
  21.  
  22.    /** 遍历器实现 */ 
  23.    transient Itrs itrs = null

 构造函数 

  1. /** 
  2.     * 构造函数,设置队列的初始容量 
  3.     */ 
  4.    public ArrayBlockingQueue(int capacity) { 
  5.        this(capacity, false); 
  6.    } 
  7.  
  8.    /** 
  9.     * 构造函数, 
  10.     * capacity and the specified access policy. 
  11.     * 
  12.     * @param capacity 设置数组大小 
  13.     * @param fair  设置是否为公平锁 
  14.     * @throws IllegalArgumentException if {@code capacity < 1} 
  15.     */ 
  16.    public ArrayBlockingQueue(int capacity, boolean fair) { 
  17.        if (capacity <= 0) 
  18.            throw new IllegalArgumentException(); 
  19.        this.items = new Object[capacity]; 
  20.        // 是否为公平锁,如果是的话,那么先到的线程先获得锁对象 
  21.        // 否则,由操作系统调度由哪个线程获得锁,一般为false,性能会比较高 
  22.        lock = new ReentrantLock(fair);  
  23.        notEmpty = lock.newCondition(); 
  24.        notFull =  lock.newCondition(); 
  25.    } 
  26.  
  27.    /** 
  28.     * 构造函数,带有初始内容的队列 
  29.     */ 
  30.    public ArrayBlockingQueue(int capacity, boolean fair, 
  31.                              Collection<? extends E> c) { 
  32.        this(capacity, fair); 
  33.  
  34.        final ReentrantLock lock = this.lock; 
  35.        //加锁的目的是为了其他CPU能够立即看到修改 
  36.        //加锁和解锁底层都是CAS,会强制修改写回主存,对其他CPU可见 
  37.        lock.lock(); // 要给数组设置内容,先上锁 
  38.        try { 
  39.            int i = 0; 
  40.            try { 
  41.                for (E e : c) { 
  42.                    checkNotNull(e); 
  43.                    items[i++] = e; // 依次拷贝内容 
  44.                } 
  45.            } catch (ArrayIndexOutOfBoundsException ex) { 
  46.                throw new IllegalArgumentException(); 
  47.            } 
  48.            count = i; 
  49.            putIndex = (i == capacity) ? 0 : i; // 如果 putIndex大于数组大小,那么从0重写开始 
  50.        } finally { 
  51.            lock.unlock(); // 最后一定要释放锁 
  52.        } 
  53.    } 

 入队方法

add / offer / put,这三个方法都是往队列中添加元素,说明如下:

  • add方法依赖于offer方法,如果队列满了则抛出异常,否则添加成功返回true;
  • offer方法有两个重载版本,只有一个参数的版本,如果队列满了就返回false,否则加入到队列中,返回true,add方法就是调用此版本的offer方法;另一个带时间参数的版本,如果队列满了则等待,可指定等待的时间,如果这期间中断了则抛出异常,如果等待超时了则返回false,否则加入到队列中返回true;
  • put方法跟带时间参数的offer方法逻辑一样,不过没有等待的时间限制,会一直等待直到队列有空余位置了,再插入到队列中,返回true
  1. /** 
  2.      * 添加一个元素,其实super.add里面调用了offer方法 
  3.      */ 
  4.     public boolean add(E e) { 
  5.         return super.add(e); 
  6.     } 
  7.  
  8.     /** 
  9.      * 加入成功返回 true,否则返回 false 
  10.      */ 
  11.     public boolean offer(E e) { 
  12.      // 创建插入的元素是否为null,是的话抛出NullPointerException异常 
  13.         checkNotNull(e); 
  14.         // 获取“该阻塞队列的独占锁” 
  15.         final ReentrantLock lock = this.lock; 
  16.         lock.lock(); // 上锁 
  17.         try { 
  18.          // 如果队列已满,则返回false。 
  19.             if (count == items.length) // 超过数组的容量 
  20.                 return false
  21.             else { 
  22.              // 如果队列未满,则插入e,并返回true。 
  23.                 enqueue(e);  
  24.                 return true
  25.             } 
  26.         } finally { 
  27.          // 释放锁 
  28.             lock.unlock(); 
  29.         } 
  30.     } 
  31.  
  32.     /** 
  33.      * 如果队列已满的话,就会等待 
  34.      */ 
  35.     public void put(E e) throws InterruptedException { 
  36.         checkNotNull(e); 
  37.         final ReentrantLock lock = this.lock; 
  38.         lock.lockInterruptibly(); //和lock方法的区别是让它在阻塞时可以抛出异常跳出 
  39.         try { 
  40.             while (count == items.length) 
  41.                 notFull.await(); // 这里就是阻塞了,要注意:如果运行到这里,那么它会释放上面的锁,一直等到 notify 
  42.             enqueue(e); 
  43.         } finally { 
  44.             lock.unlock(); 
  45.         } 
  46.     } 
  47.  
  48.     /** 
  49.      * 带有超时事件的插入方法,unit 表示是按秒、分、时哪一种 
  50.      */ 
  51.     public boolean offer(E e, long timeout, TimeUnit unit) 
  52.         throws InterruptedException { 
  53.  
  54.         checkNotNull(e); 
  55.         long nanos = unit.toNanos(timeout); 
  56.         final ReentrantLock lock = this.lock; 
  57.         lock.lockInterruptibly(); 
  58.         try { 
  59.             while (count == items.length) { 
  60.                 if (nanos <= 0) 
  61.                     return false
  62.                 nanos = notFull.awaitNanos(nanos); // 带有超时等待的阻塞方法 
  63.             } 
  64.             enqueue(e); // 入队 
  65.             return true
  66.         } finally { 
  67.             lock.unlock(); 
  68.         } 
  69.     } 

 出队方法

poll / take / peek,这几个方法都是获取队列顶的元素,具体说明如下:

  • poll方法有两个重载版本,第一个版本,如果队列是空的,返回null,否则移除并返回队列头部元素;另一个带时间参数的版本,如果栈为空则等待,可以指定等待的时间,如果等待超时了则返回null,如果被中断了则抛出异常,否则移除并返回栈顶元素
  • take方法同带时间参数的poll方法,但是不能指定等待时间,会一直等待直到队列中有元素为止,然后移除并返回栈顶元素
  • peek方法只是返回队列头部元素,不移除
  1. // 实现的方法,如果当前队列为空,返回null 
  2.    public E poll() { 
  3.        final ReentrantLock lock = this.lock; 
  4.        lock.lock(); 
  5.        try { 
  6.            return (count == 0) ? null : dequeue(); 
  7.        } finally { 
  8.            lock.unlock(); 
  9.        } 
  10.    } 
  11. // 实现的方法,如果当前队列为空,一直阻塞 
  12.    public E take() throws InterruptedException { 
  13.        final ReentrantLock lock = this.lock; 
  14.        lock.lockInterruptibly(); 
  15.        try { 
  16.            while (count == 0) 
  17.                notEmpty.await(); // 队列为空,阻塞方法 
  18.            return dequeue(); 
  19.        } finally { 
  20.            lock.unlock(); 
  21.        } 
  22.    } 
  23. // 带有超时事件的取元素方法,否则返回null 
  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 = notEmpty.awaitNanos(nanos); // 超时等待 
  33.            } 
  34.            return dequeue(); // 取得元素 
  35.        } finally { 
  36.            lock.unlock(); 
  37.        } 
  38.    } 
  39.  
  40.    // 只是看一个队列最前面的元素,取出是不擅长队列中原来的元素,队列为空时返回null 
  41.    public E peek() { 
  42.        final ReentrantLock lock = this.lock; 
  43.        lock.lock(); 
  44.        try { 
  45.            return itemAt(takeIndex); // 队列为空时返回null 
  46.        } finally { 
  47.            lock.unlock(); 
  48.        } 
  49.    } 

 删除元素方法

remove / clear /drainT,这三个方法用于从队列中移除元素,具体说明如下:

  • remove方法用于移除某个元素,如果栈为空或者没有找到该元素则返回false,否则从栈中移除该元素;移除时,如果该元素位于栈顶则直接移除,如果位于栈中间,则需要将该元素后面的其他元素往前面挪动,移除后需要唤醒因为栈满了而阻塞的线程
  • clear方法用于整个栈,同时将takeIndex置为putIndex,保证栈中的元素先进先出;最后会唤醒最多count个线程,因为正常一个线程插入一个元素,如果唤醒超过count个线程,可能导致部分线程因为栈满了又再次被阻塞
  • drainTo方法有两个重载版本,一个是不带个数,将所有的元素都移除并拷贝到指定的集合中;一个带个数,将指定个数的元素移除并拷贝到指定的集合中,两者的底层实现都是同一个方法。移除后需要重置takeIndex和count,并唤醒最多移除个数的因为栈满而阻塞的线程。
  1. /** 
  2.     * 从队列中删除一个元素的方法。删除成功返回true,否则返回false 
  3.     */ 
  4.    public boolean remove(Object o) { 
  5.        if (o == nullreturn false
  6.        final Object[] items = this.items; 
  7.        final ReentrantLock lock = this.lock; 
  8.        lock.lock(); 
  9.        try { 
  10.            if (count > 0) { 
  11.                final int putIndex = this.putIndex; 
  12.                int i = takeIndex; 
  13.                //从takeIndex开始往后遍历直到等于putIndex 
  14.                do { 
  15.                    if (o.equals(items[i])) { 
  16.                        removeAt(i); // 真正删除的方法 
  17.                        return true
  18.                    } 
  19.                    //走到数组末尾了又从头开始,put时也按照这个规则来 
  20.                    if (++i == items.length) 
  21.                        i = 0; 
  22.                } while (i != putIndex); // 一直不断的循环取出来做判断 
  23.            } 
  24.            //如果数组为空,返回false 
  25.            return false
  26.        } finally { 
  27.            lock.unlock(); 
  28.        } 
  29.    } 
  30.  
  31. /** 
  32.     * 指定删除索引上的元素. 
  33.     */ 
  34.    void removeAt(final int removeIndex) { 
  35.        // assert lock.getHoldCount() == 1; 
  36.        // assert items[removeIndex] != null
  37.        // assert removeIndex >= 0 && removeIndex < items.length; 
  38.        final Object[] items = this.items; 
  39.        if (removeIndex == takeIndex) { 
  40.            //如果移除的就是栈顶的元素 
  41.            items[takeIndex] = null
  42.            if (++takeIndex == items.length) 
  43.                takeIndex = 0; 
  44.            //元素个数减1 
  45.            count--; 
  46.            if (itrs != null
  47.                itrs.elementDequeued(); 
  48.        } else { 
  49.            // an "interior" remove 
  50.  
  51.            // 如果移除的是栈中间的某个元素,需要将该元素后面的元素往前挪动 
  52.            final int putIndex = this.putIndex; 
  53.            for (int i = removeIndex;;) { 
  54.                int next = i + 1; 
  55.                //到数组末尾了,从头开始 
  56.                if (next == items.length) 
  57.                    next = 0; 
  58.                if (next != putIndex) { 
  59.                 //将后面一个元素复制到前面来 
  60.                    items[i] = items[next]; 
  61.                    i = next
  62.                } else { 
  63.                 //如果下一个元素的索引等于putIndex,说明i就是栈中最后一个元素了,直接将该元素置为null 
  64.                    items[i] = null
  65.                    //重置putIndex为i 
  66.                    this.putIndex = i; 
  67.                    break; 
  68.                } 
  69.            } 
  70.            count--; 
  71.            if (itrs != null
  72.             //通知itrs节点移除了 
  73.                itrs.removedAt(removeIndex); 
  74.        } 
  75.        //唤醒因为栈满了而等待的线程 
  76.        notFull.signal(); // 有一个元素删除成功,那肯定队列不满 
  77.    } 
  78.  
  79. /** 
  80.     * 清空队列 
  81.     */ 
  82.    public void clear() { 
  83.        final Object[] items = this.items; 
  84.        final ReentrantLock lock = this.lock; 
  85.        lock.lock(); 
  86.        try { 
  87.            int k = count
  88.            if (k > 0) { 
  89.                final int putIndex = this.putIndex; 
  90.                int i = takeIndex; 
  91.                //从takeIndex开始遍历直到i等于putIndex,将数组元素置为null 
  92.                do { 
  93.                    items[i] = null
  94.                    if (++i == items.length) 
  95.                        i = 0; 
  96.                } while (i != putIndex); 
  97.                //注意此处没有将这两个index置为0,只是让他们相等,因为只要相等就可以实现栈先进先出了 
  98.                takeIndex = putIndex; 
  99.                count = 0; 
  100.                if (itrs != null
  101.                    itrs.queueIsEmpty(); 
  102.                //如果有因为栈满了而等待的线程,则将其唤醒 
  103.                //注意这里没有使用signalAll而是通过for循环来signal多次,单纯从唤醒线程来看是可以使用signalAll的,效果跟这里的for循环是一样的 
  104.                //如果有等待的线程,说明count就是当前线程的最大容量了,这里清空了,最多只能put count次,一个线程只能put 1次,只唤醒最多count个线程就避免了 
  105.                //线程被唤醒后再次因为栈满了而阻塞 
  106.                for (; k > 0 && lock.hasWaiters(notFull); k--) 
  107.                    notFull.signal(); 
  108.            } 
  109.        } finally { 
  110.            lock.unlock(); 
  111.        } 
  112.    } 
  113.  
  114.    /** 
  115.     * 取出所有元素到集合 
  116.     */ 
  117.    public int drainTo(Collection<? super E> c) { 
  118.        return drainTo(c, Integer.MAX_VALUE); 
  119.    } 
  120.  
  121.    /** 
  122.     * 取出所有元素到集合 
  123.     */ 
  124.    public int drainTo(Collection<? super E> c, int maxElements) { 
  125.        //校验参数合法 
  126.        checkNotNull(c); 
  127.        if (c == this) 
  128.            throw new IllegalArgumentException(); 
  129.        if (maxElements <= 0) 
  130.            return 0; 
  131.        final Object[] items = this.items; 
  132.        final ReentrantLock lock = this.lock; 
  133.        lock.lock(); 
  134.        try { 
  135.         //取两者之间的最小值 
  136.            int n = Math.min(maxElements, count); 
  137.            int take = takeIndex; 
  138.            int i = 0; 
  139.            try { 
  140.             //从takeIndex开始遍历,取出元素然后添加到c中,直到满足个数要求为止 
  141.                while (i < n) { 
  142.                    @SuppressWarnings("unchecked"
  143.                    E x = (E) items[take]; 
  144.                    c.add(x); 
  145.                    items[take] = null
  146.                    if (++take == items.length) 
  147.                        take = 0; 
  148.                    i++; 
  149.                } 
  150.                return n; 
  151.            } finally { 
  152.                // Restore invariants even if c.add() threw 
  153.                if (i > 0) { 
  154.                 //取完了,修改count减去i 
  155.                    count -= i; 
  156.                    takeIndex = take; 
  157.                    if (itrs != null) { 
  158.                        if (count == 0) 
  159.                         //通知itrs 栈空了 
  160.                            itrs.queueIsEmpty(); 
  161.                        else if (i > take) 
  162.                         //说明take中间变成0了,通知itrs 
  163.                            itrs.takeIndexWrapped(); 
  164.                    } 
  165.                    //唤醒在因为栈满而等待的线程,最多唤醒i个,同上避免线程被唤醒了因为栈又满了而阻塞 
  166.                    for (; i > 0 && lock.hasWaiters(notFull); i--) 
  167.                        notFull.signal(); 
  168.                } 
  169.            } 
  170.        } finally { 
  171.            lock.unlock(); 
  172.        } 
  173.    } 

 iterator / Itr / Itrs

Itr和Itrs都是ArrayBlockingQueue的两个内部类,如下:

阻塞队列—ArrayBlockingQueue源码分析

 iterator方法返回一个迭代器实例,用于实现for循环遍历和部分Collection接口,该方法的实现如下: 

  1. public Iterator<E> iterator() { 
  2.  return new Itr(); 
  3.  
  4. Itr() { 
  5.  // assert lock.getHoldCount() == 0; 
  6.  lastRet = NONE; 
  7.  final ReentrantLock lock = ArrayBlockingQueue.this.lock; 
  8.     lock.lock(); 
  9.     try { 
  10.      if (count == 0) { 
  11.          //NONE和DETACHED都是常量 
  12.             cursor = NONE; 
  13.             nextIndex = NONE; 
  14.             prevTakeIndex = DETACHED; 
  15.         } else { 
  16.          //初始化各属性 
  17.             final int takeIndex = ArrayBlockingQueue.this.takeIndex; 
  18.             prevTakeIndex = takeIndex; 
  19.             nextItem = itemAt(nextIndex = takeIndex); 
  20.             cursor = incCursor(takeIndex); 
  21.             if (itrs == null) { 
  22.              itrs = new Itrs(this); 
  23.             } else { 
  24.              //初始化Itrs,将当前线程注册到Itrs 
  25.                 itrs.register(this); // in this order 
  26.                 itrs.doSomeSweeping(false); 
  27.             } 
  28.             prevCycles = itrs.cycles; 
  29.             // assert takeIndex >= 0; 
  30.             // assert prevTakeIndex == takeIndex; 
  31.             // assert nextIndex >= 0; 
  32.             // assert nextItem != null
  33.      } 
  34.  } finally { 
  35.     lock.unlock(); 
  36.     } 
  37.  
  38. Itrs(Itr initial) { 
  39.  register(initial); 
  40.  
  41. //根据index计算cursor 
  42. private int incCursor(int index) { 
  43.  // assert lock.getHoldCount() == 1; 
  44.  if (++index == items.length) 
  45.   index = 0; 
  46.  if (index == putIndex) 
  47.   index = NONE; 
  48.  return index
  49.  
  50. /** 
  51. * 创建一个新的Itr实例时,会调用此方法将该实例添加到Node链表中 
  52. */ 
  53. void register(Itr itr) { 
  54.  //创建一个新节点将其插入到head节点的前面 
  55.  head = new Node(itr, head); 

 小结

ArrayBlockingQueue是一个阻塞队列,内部由ReentrantLock来实现线程安全,由Condition的await和signal来实现等待唤醒的功能。它的数据结构是数组,准确地说是一个循环数组(可以类比一个圆环),所有的下标在到达最大长度时自动从0继续开始。

PS:以上代码提交在 Github :

https://github.com/Niuh-Study/niuh-juc-final.git

 

责任编辑:姜华 来源: 今日头条
相关推荐

2020-11-24 09:04:55

PriorityBlo

2020-11-20 06:22:02

LinkedBlock

2020-11-25 14:28:56

DelayedWork

2023-12-28 07:49:11

线程池源码应用场景

2017-04-12 10:02:21

Java阻塞队列原理分析

2012-06-14 10:34:40

Java阻塞搜索实例

2023-12-15 09:45:21

阻塞接口

2022-06-30 08:14:05

Java阻塞队列

2021-05-17 07:36:54

ArrayBlocki面试集合

2021-06-04 14:15:10

鸿蒙HarmonyOS应用

2024-02-20 08:16:10

阻塞队列源码

2022-09-26 00:48:14

线程池阻塞数据

2021-09-22 14:36:32

鸿蒙HarmonyOS应用

2023-12-05 13:46:09

解密协程线程队列

2011-03-15 11:33:18

iptables

2021-01-09 13:57:05

阻塞队列并发

2020-11-27 09:16:21

BlockingQue

2014-08-26 11:11:57

AsyncHttpCl源码分析

2021-05-12 09:45:20

鸿蒙HarmonyOS应用

2022-06-30 14:31:57

Java阻塞队列
点赞
收藏

51CTO技术栈公众号