烂大街的阻塞队列你真的学会了吗——ArrayBlockingQueue

1,344 阅读4分钟

这是我参与11月更文挑战的第3天,活动详情查看:2021最后一次更文挑战

BlockingQueue简介

在讲ArrayBlockingQueue之前先讲一下阻塞队列,阻塞队列支持阻塞的插入和移除。即当队列满了的情况下,队列会阻塞插入元素的线程,直到队列不满;当队列为空的情况下,队列会阻塞获取元素的线程,直到队列非空。

BlockingQueue的核心方法

offer(anObject):表示如果可能的话,将anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则返回false。本方法不阻塞当前执行方法的线程

offer(E o, long timeout, TimeUnit unit):可以设定等待的时间,如果在指定的时间内,还不能往队列中加入BlockingQueue,则返回失败。

put(anObject):把anObject加到BlockingQueue里,如果BlockingQueue没有空间,则调用此方法的线程被阻断,直到BlockingQueue里面有空间再继续。

poll(time):取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,取不到时返回null。

poll(long timeout, TimeUnit unit):从BlockingQueue取出一个队首的对象,如果在指定时间内,队列一旦有数据可取,则立即返回队列中的数据。否则知道时间超时还没有数据可取,返回失败。

take():取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到BlockingQueue有新的数据被加入。

drainTo():一次性从BlockingQueue获取所有可用的数据对象(还可以指定获取数据的个数), 通过该方法,可以提升获取数据效率;不需要多次分批加锁或释放锁。

需要注意的是BlockingQueue不接受null值的插入,相应的方法在碰到null的插入时会抛出NullPointerException 异常。null值用于作为特殊值返回,代表poll失败。

常见的BlockingQueue: 1094831408-4dac22f5a10a2e85_fix732.png

ArrayBlockingQueue

ArrayBlockingQueue是一个用数组实现的有界阻塞队列。按照先进先出(FIFO)的原则对元素进行排序。有界是指它不能够存储无限多数量的元素,在创建ArrayBlockingQueue时,必须要给它指定一个队列的大小。阻塞指在添加/取走元素时,当队列没有空间/为空的时候会阻塞,知道队列有空间/有新的元素加入时再继续。因为采用的是循环数组的形式表达队列,所以队列的容量一旦在构造时指定,后续不能改变,对于数组的长度来说,根据初始化的参数为标准,类中没有默认的数组长度。

源码分析

重要属性

ArrayBlockingQueue的底层组包括:数组,一个重入锁,两个条件队列

//队列中元素保存的地方
final Object[] items;

//items index for next take, poll, peek or remove(下一个待删除位置的索引: take, poll, peek, remove方法使用)
int takeIndex;

// items index for next put, offer, or add(下一个待插入位置的索引: put, offer, add方法使用)
int putIndex;

//队列中元素个数
int count;

//全局锁
final ReentrantLock lock;

//非空条件队列:当队列空时,线程在该队列等待获取
private final Condition notEmpty;

//非满条件队列:当队列满时,线程在该队列等待插入
private final Condition notFull;

构造方法


//队列初始容量和公平/非公平锁的构造器.

public ArrayBlockingQueue(int capacity, boolean fair) {
    if (capacity <= 0)
        throw new IllegalArgumentException();

    this.items = new Object[capacity];
    lock = new ReentrantLock(fair);     // 独占锁
    notEmpty = lock.newCondition();  //队列为空时,线程在该队列等待获取
    notFull = lock.newCondition();  // 队列满时,线程在该队列等待插入
}

重要方法

添加元素

add()方法:此方法,实际上调用了offer(e)方法。

public boolean add(E e) {
    // 调用父类的add(e)方法
    return super.add(e);
}
public boolean add(E e) {
    // 调用offer(e)如果成功返回true,如果失败抛出异常
    if (offer(e))
        return true;
    else
        throw new IllegalStateException("Queue full");
}

offer(e)方法入队入参e为null,会抛空指针异常。

offer(E e)方法:将元素添加到 BlockingQueue 里,如果可以容纳返回 true 否则返回 false

public boolean offer(E e) {
    checkNotNull(e); // 检查元素是否为 null
    final ReentrantLock lock = this.lock;
    lock.lock(); // 加锁
    try {
        if (count == items.length) // 如果队列已经满了返回 false
            return false;
        else { // 队列还没有满,则添加到队列中
            enqueue(e); // 进队
            return true;
        }
    } finally {
        lock.unlock(); // 释放锁
    }
}

put(e)方法:将元素添加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程被阻塞,直到有空间

public void put(E e) throws InterruptedException {
    checkNotNull(e); // 检查元素是否为 null
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly(); // 加锁
    try {
        while (count == items.length)
            notFull.await(); //如果队列已经满了,就阻塞(添加到 notFull 条件队列中等待唤醒)
        enqueue(e); // 如果队列没有满直接添加
    } finally {
        lock.unlock(); // 释放锁
    }
}

enqueue(E x)入队,利用放指针循环使用数组来存储元素。

private void enqueue(E x) {
    // 获取当前数组
    final Object[] items = this.items;
    // 通过索引赋值
    items[putIndex] = x;
    // 如果当前添加对象的位置 +1 等于 数组的长度,也就是当前对象的位置在数组的最后一个
    // 那么下一个应该从数组的第一个添加
    if (++putIndex == items.length)
        putIndex = 0;
    count++;
    // 唤醒正在等待获取对象的线程
    notEmpty.signal();
}

获取元素

poll()方法,取队头(首个)元素并删除,没有则返回null。

public E poll() {        
    final ReentrantLock lock = this.lock;        
    lock.lock();        
    try {
        //如果队列里没有数据就直接返回null
        //否则从队列头部出队
        return (count == 0) ? null : dequeue();        
    } finally {            
        lock.unlock();       
    }   
}

take()方法,如果队列中有元素,则获取并删除,如果没有元素,则阻塞等待

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    //加锁,如果线程中断了抛出异常
    lock.lockInterruptibly();        
    try {
        //队列中不存元素
        while (count == 0){  
            /*
             * 一直等待条件notEmpty,即被其他线程唤醒
             * (唤醒其实就是,有线程将一个元素入队了,然后调用notEmpty.signal()
             * 唤醒其他等待这个条件的线程,同时队列也不空了)
             */
            notEmpty.await();
        }
        //否则出队
        return dequeue();        
    } finally {            
        lock.unlock();        
    }    
}

dequeue()方法。

private E dequeue() {
    final Object[] items = this.items;
    @SuppressWarnings("unchecked")
    // 根据索引获取对象
    E x = (E) items[takeIndex];
    // 当前位置的对象被取走,位置就腾出来了
    items[takeIndex] = null;
    // 如果被取走的是数组的最后一个,那下一个要从第一个取
    if (++takeIndex == items.length)
        takeIndex = 0;
    count--;
    if (itrs != null)
        itrs.elementDequeued();
    // 唤醒正在等待添加对象的线程
    notFull.signal();
    return x;
}

peek()方法,只取不删,当队列中没有元素时会返回null。

public E peek() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return itemAt(takeIndex);
    } finally {
        lock.unlock();
    }
}

删除元素

remove(o)方法,如果队列为空或者没有找到该元素返回false,否则删除元素并且返回true。

public boolean remove(Object o) {
    if (o == null) return false;
    final Object[] items = this.items;
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        if (count > 0) {
            final int putIndex = this.putIndex;
            int i = takeIndex; // 从取得位置开始,到添加的位置
            do {
                if (o.equals(items[i])) {
                    removeAt(i);
                    return true;
                }
                if (++i == items.length) // 若果判断的位置到了队列最末尾,那下一个从第一个判断
                    i = 0;
            } while (i != putIndex);
        }
        return false;
    } finally {
        lock.unlock();
    }
}

removeAt(index)方法,删除指定位置上的元素

void removeAt(final int removeIndex) {
    final Object[] items = this.items;
    if (removeIndex == takeIndex) { // 当删除的元素是下次取操作要取到的元素时,既队头元素
        items[takeIndex] = null;  // 删除队头元素,并且 takeIndex 加 1
        if (++takeIndex == items.length) // 如果删除得是数组最后一个元素,则 takeIndex 从数组第一个元素开始
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
    } else {
        // 如果删除的不是队头元素
        // 则从删除元素的后面一直到添加元素的位置(removeIndex ~ putIndex)期间的元素都要往前挪一个位置
        // 取 putIndex 作为循环结束判断条件
        final int putIndex = this.putIndex;
        for (int i = removeIndex;;) { // 顺序往前挪一个位置
            int next = i + 1;
            if (next == items.length)// 当循环到数组最后一个元素,下一个元素应该是数组第一个元素
                next = 0;
            if (next != putIndex) { // 如果查找的索引不等于要添加元素的索引,说明元素可以再移动
                items[i] = items[next];
                i = next;
            } else { // 在 removeIndex 索引之后的元素都往前移动完毕后清空最后一个元素
                items[i] = null;
                this.putIndex = i;
                break;
            }
        }
        count--;
        if (itrs != null)
            itrs.removedAt(removeIndex);
    }
    notFull.signal();
}

总结

ArrayBlockingQueue特点是不需要扩容,因为是初始化时指定容量,并利用takeIndex和putIndex循环利用数组。并且有重入锁和两个条件保证并发安全。