1 BlockingQueue 接口及其实现类
BlocingQueue接口定义如下,仅列举几个常用方法:
- put(E) 在队列尾部放入元素,若队列满则等待;
- take() 取队列头部元素返回,若队列空则等待;
- offer(E) 在队列尾部放入元素,若成功则返回true, 否则false;不阻塞;
- poll() 取队列头部元素返回,若有元素则返回元素,否则null;不阻塞;
实现BlockingQueue的常用接口:
- ArrayBlockingQueue: 使用循环数组实现队列,由一把锁控制put 和 take, 同一把锁上实现了两个等待队列(Condition);
- LinkedBlockingQueue: 使用链表实现队列,由两把锁分别控制put 和 take,两个等待队列分别在两把锁上;
- PriorityBlockingQueue: 使用小顶堆实现优先级队列,取出元素顺序有Comparable, Comparator决定,多线程安全;
2 ArrayBlockingQueue 源码解读
ArrayBlockingQueue创建的时候需要指定容量capacity(可以存储的最大的元素个数,因为它不会自动扩容)。其中一个构造方法为:
- public ArrayBlockingQueue(int capacity, boolean fair) {
- if (capacity <= 0)
- throw new IllegalArgumentException();
- this.items = (E[]) new Object[capacity];
- lock = new ReentrantLock(fair);
- notEmpty = lock.newCondition();
- notFull = lock.newCondition();
- }
ArrayBlockingQueue类中定义的变量有:
- /** The queued items */
- private final E[] items;
- /** items index for next take, poll or remove */
- private int takeIndex;
- /** items index for next put, offer, or add. */
- private int putIndex;
- /** Number of items in the queue */
- private int count;
- /*
- * Concurrency control uses the classic two-condition algorithm
- * found in any textbook.
- */
- /** Main lock guarding all access */
- private final ReentrantLock lock;
- /** Condition for waiting takes */
- private final Condition notEmpty;
- /** Condition for waiting puts */
- private final Condition notFull;
put(E e)方法的源码如下。进行put操作之前,必须获得锁并进行加锁操作,以保证线程安全性。加锁后,若发现队列已满,则调用notFull.await()方法,如当前线程陷入等待。直到其他线程take走某个元素后,会调用notFull.signal()方法来激活该线程。激活之后,继续下面的插入操作。
- /**
- * Inserts the specified element at the tail of this queue, waiting
- * for space to become available if the queue is full.
- *
- */
- public void put(E e) throws InterruptedException {
- //不能存放 null 元素
- if (e == null) throw new NullPointerException();
- final E[] items = this.items; //数组队列
- final ReentrantLock lock = this.lock;
- //加锁
- lock.lockInterruptibly();
- try {
- try {
- //当队列满时,调用notFull.await()方法,使该线程阻塞。
- //直到take掉某个元素后,调用notFull.signal()方法激活该线程。
- while (count == items.length)
- notFull.await();
- } catch (InterruptedException ie) {
- notFull.signal(); // propagate to non-interrupted thread
- throw ie;
- }
- //把元素 e 插入到队尾
- insert(e);
- } finally {
- //解锁
- lock.unlock();
- }
- }
- /**
- * Inserts element at current put position, advances, and signals.
- * Call only when holding lock.
- */
- private void insert(E x) {
- items[putIndex] = x;
- //下标加1或者等于0
- putIndex = inc(putIndex);
- ++count; //计数加1
- //若有take()线程陷入阻塞,则该操作激活take()线程,继续进行取元素操作。
- //若没有take()线程陷入阻塞,则该操作无意义。
- notEmpty.signal();
- }
- **
- * Circularly increment i.
- */
- final int inc(int i) {
- //此处可以看到使用了循环队列
- return (++i == items.length)? 0 : i;
- }
- public E take() throws InterruptedException {
- final ReentrantLock lock = this.lock;
- lock.lockInterruptibly(); //加锁
- try {
- try {
- //当队列空时,调用notEmpty.await()方法,使该线程阻塞。
- //直到take掉某个元素后,调用notEmpty.signal()方法激活该线程。
- while (count == 0)
- notEmpty.await();
- } catch (InterruptedException ie) {
- notEmpty.signal(); // propagate to non-interrupted thread
- throw ie;
- }
- //取出队头元素
- E x = extract();
- return x;
- } finally {
- lock.unlock(); //解锁
- }
- }
- /**
- * Extracts element at current take position, advances, and signals.
- * Call only when holding lock.
- */
- private E extract() {
- final E[] items = this.items;
- E x = items[takeIndex];
- items[takeIndex] = null;
- takeIndex = inc(takeIndex);
- --count;
- notFull.signal();
- return x;
- }
3 LinkedBlockingQueue 源码解读
基于链表的阻塞队列,同ArrayListBlockingQueue类似,其内部也维持着一个数据缓冲队列(该队列由一个链表构成),当生产者往队列中放入一个数据时,队列会从生产者手中获取数据,并缓存在队列内部,而生产者立即返回;只有当队列缓冲区达到最大值缓存容量时(LinkedBlockingQueue可以通过构造函数指定该值),才会阻塞生产者队列,直到消费者从队列中消费掉一份数据,生产者线程会被唤醒,反之对于消费者这端的处理也基于同样的原理。而LinkedBlockingQueue之所以能够高效的处理并发数据,还因为其对于生产者端和消费者端分别采用了独立的锁来控制数据同步,这也意味着在高并发的情况下生产者和消费者可以并行地操作队列中的数据,以此来提高整个队列的并发性能。
作为开发者,我们需要注意的是,如果构造一个LinkedBlockingQueue对象,而没有指定其容量大小,LinkedBlockingQueue会默认一个类似无限大小的容量(Integer.MAX_VALUE),这样的话,如果生产者的速度一旦大于消费者的速度,也许还没有等到队列满阻塞产生,系统内存就有可能已被消耗殆尽了。
LinkedBlockingQueue 类中定义的变量有:
- /** The capacity bound, or Integer.MAX_VALUE if none */
- private final int capacity;
- /** Current number of elements */
- private final AtomicInteger count = new AtomicInteger(0);
- /** Head of linked list */
- private transient Node<E> head;
- /** Tail of linked list */
- private transient Node<E> last;
- /** Lock held by take, poll, etc */
- private final ReentrantLock takeLock = new ReentrantLock();
- /** Wait queue for waiting takes */
- private final Condition notEmpty = takeLock.newCondition();
- /** Lock held by put, offer, etc */
- private final ReentrantLock putLock = new ReentrantLock();
- /** Wait queue for waiting puts */
- private final Condition notFull = putLock.newCondition();
- /**
- * Inserts the specified element at the tail of this queue, waiting if
- * necessary for space to become available.
- */
- public void put(E e) throws InterruptedException {
- if (e == null) throw new NullPointerException();
- // Note: convention in all put/take/etc is to preset local var
- // holding count negative to indicate failure unless set.
- int c = -1;
- final ReentrantLock putLock = this.putLock;
- final AtomicInteger count = this.count;
- putLock.lockInterruptibly(); //加 putLock 锁
- try {
- /*
- * Note that count is used in wait guard even though it is
- * not protected by lock. This works because count can
- * only decrease at this point (all other puts are shut
- * out by lock), and we (or some other waiting put) are
- * signalled if it ever changes from
- * capacity. Similarly for all other uses of count in
- * other wait guards.
- */
- //当队列满时,调用notFull.await()方法释放锁,陷入等待状态。
- //有两种情况会激活该线程
- //第一、 某个put线程添加元素后,发现队列有空余,就调用notFull.signal()方法激活阻塞线程
- //第二、 take线程取元素时,发现队列已满。则其取出元素后,也会调用notFull.signal()方法激活阻塞线程
- while (count.get() == capacity) {
- notFull.await();
- }
- // 把元素 e 添加到队列中(队尾)
- enqueue(e);
- c = count.getAndIncrement();
- //发现队列未满,调用notFull.signal()激活阻塞的put线程(可能存在)
- if (c + 1 < capacity)
- notFull.signal();
- } finally {
- putLock.unlock();
- }
- if (c == 0)
- //队列空,说明已经有take线程陷入阻塞,故调用signalNotEmpty激活阻塞的take线程
- signalNotEmpty();
- }
- /**
- * Creates a node and links it at end of queue.
- * @param x the item
- */
- private void enqueue(E x) {
- // assert putLock.isHeldByCurrentThread();
- last = last.next = new Node<E>(x);
- }
- public E take() throws InterruptedException {
- E x;
- int c = -1;
- final AtomicInteger count = this.count;
- final ReentrantLock takeLock = this.takeLock;
- takeLock.lockInterruptibly();
- try {
- while (count.get() == 0) {
- notEmpty.await();
- }
- x = dequeue();
- c = count.getAndDecrement();
- if (c > 1)
- notEmpty.signal();
- } finally {
- takeLock.unlock();
- }
- if (c == capacity)
- signalNotFull();
- return x;
- }
- /**
- * Removes a node from head of queue.
- * @return the node
- */
- private E dequeue() {
- // assert takeLock.isHeldByCurrentThread();
- Node<E> h = head;
- Node<E> first = h.next;
- h.next = h; // help GC
- head = first;
- E x = first.item;
- first.item = null;
- return x;
- }
小结:take和put操作各有一把锁,可并行读取。
4 SynchronousQueue, ArrayBlockingQueue 和 LinkedBlockingQueue 性能对比
-
线程多(>20),Queue长度长(>30),使用LinkedBlockingQueue
-
线程少 (<20) ,Queue长度短 (<30) , 使用SynchronousQueue
当然,使用SynchronousQueue的时候不要忘记应用的扩展,如果将来需要进行扩展还是选择LinkedBlockingQueue好,尽量把SynchronousQueue限制在特殊场景中使用。
-
少用ArrayBlcokingQueue,似乎没找到它的好处,高手给给建议吧!
参考文章:
1 JDK源码分析—— ArrayBlockingQueue 和 LinkedBlockingQueue
2 SynchronousQueue、LinkedBlockingQueue、ArrayBlockingQueue性能测试