JDK源码之ArrayBlockingQueue(源码+解读)

ArrayBlockingQueue是基于数组实现的有界BlockingQueue,该队列满足先入先出(FIFO)特性。它是由一个固定大小的数组保存元素,一旦创建好以后,容量就不能改变了。队满时,存数据的操作会别阻塞,队空时,取数据的操作会被阻塞。

主要成员变量:

public class ArrayBlockingQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable {
    
    /** 队列元素存储数组 */
    final Object[] items;

    /** 队头下标,下一次take\poll\peek\remove方法执行位置的下标 */
    int takeIndex;

    /** 队尾下标,下一次put\offer\add方法执行位置的下标 */
    int putIndex;

    /** 队列元素的数量 */
    int count;

    /** 访问锁 */
    final ReentrantLock lock;

    /** 阻塞取值类型方法(take\poll\peek\remove)的控制条件 */
    private final Condition notEmpty;

    /** 阻塞存值方法(put\offer\add)的控制条件 */
    private final Condition notFull;

主要方法:

①add(E) 方法的实现在AbstractQueue抽象类里,通过调用offer(E)作为实现。

    public boolean add(E e) {
        return super.add(e);
    }

②offer(E)

public boolean offer(E e) {
        checkNotNull(e);// 判断e是否为null,如果是则抛出空指针异常
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == items.length)// 判断当前队列元素个数是否等于定义的数组大小,如果等于表示队列已满,添加失败返回false
                return false;
            else {// 否则执行入队操作,返回true
                enqueue(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }

③offer(E, long, TimeUnit)

public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException {

        checkNotNull(e);
        long nanos = unit.toNanos(timeout);// 把timeout转换成纳秒数并返回
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();// 可中断地获取锁,如果当前线程发生interrupt,则释放锁
        try {
            while (count == items.length) {
                if (nanos <= 0)
                    return false;
                nanos = notFull.awaitNanos(nanos);// 一直阻塞并不断尝试入队,超时后返回false
            }
            enqueue(e);
            return true;
        } finally {
            lock.unlock();
        }
    }

④put(E)

public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                notFull.await();// 阻塞当前线程,直到可以插入值
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }

offer(E, long, TimeUnit)和put(E)的区别是offer(E, long, TimeUnit)会一直阻塞线程并不断尝试入队,超时后返回false,而put(E)则会一直阻塞线程,直到可以插入值。

①②③④方法总结:
1、这三个方法使用了重入锁,都是线程安全的。
2、add方法入队失败则抛出异常
3、offer方法会在指定的时间内不断尝试入队,如果超时则返回false
4、put方法在未中断的情况下,会一直尝试入队,如果被中断则抛出异常,那么需要由使用者自行处理。notFull对象监视器会在出队时唤醒。

⑤remove(Object o)

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) {// 如果队列中有元素则进入下一步,否则直接返回false
                final int putIndex = this.putIndex;// 队尾下标
                int i = takeIndex;// 队头下标
                do {
                    if (o.equals(items[i])) {
                        removeAt(i);
                        return true;
                    }
                    if (++i == items.length)// ++i,如果i增加到数组初始化容量大小则i重新赋值为0,相当于环形队列
                        i = 0;
                } while (i != putIndex);
            }
            return false;
        } finally {
            lock.unlock();
        }
    }

    void removeAt(final int removeIndex) {
        final Object[] items = this.items;
        if (removeIndex == takeIndex) {// 因为是先进先出队列,如果需要删除的元素的下标等于队头下标,则直接将removeIndex赋值null并将队列元素数量count-1
            // removing front item; just advance
            items[takeIndex] = null;
            if (++takeIndex == items.length)
                takeIndex = 0;
            count--;
            if (itrs != null)
                itrs.elementDequeued();
        } else {// 如果不相等,将需删除元素的后续元素统一前移一位
        
            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 {
                    items[i] = null;
                    this.putIndex = i;
                    break;
                }
            }
            count--;
            if (itrs != null)
                itrs.removedAt(removeIndex);
        }
        // 删除元素后队列肯定不满,唤醒notFull对象监视器
        notFull.signal();
    }

⑥take()

public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {// 取出队头元素,如果队列为空,则等待notEmpty被唤醒,或者线程中断
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

⑦poll() 和 poll(long, TimeUnit)

    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {// 取出队头元素,如果队列为空,返回null
            return (count == 0) ? null : dequeue();
        } finally {
            lock.unlock();
        }
    }

    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0) {
                if (nanos <= 0)
                    return null;
                nanos = notEmpty.awaitNanos(nanos);// 阻塞指定时长后再次尝试出队操作
            }
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

⑤⑥⑦总结:
1、remove\poll\take方法都是线程安全的
2、remove方法可以移除任意对象,需要遍历比对对象来确定下标的位置,并且可能需要移动大量数据的位置,效率较低。
3、removeAt方法可以移除指定下标的元素,也可能需要移动大量数据位置,但是比remove少了循环比对过程,效率稍微好一点。
4、poll和take只能移除对头元素,效率极高。

⑧peek() 用于查看队头元素

	public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return itemAt(takeIndex); // null when queue is empty
        } finally {
            lock.unlock();
        }
    }

⑨enqueue(E)

	private void enqueue(E x) {
        final Object[] items = this.items;
        items[putIndex] = x;// 把x添加到队尾
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        notEmpty.signal();// 唤醒notEmpty对象监视器
    }

add\offer\put方法都会调用enqueue方法,唤醒notEmpty对象监视器的作用在于,通知可被notEmpty阻塞的取值方法(poll或者take)有元素入队,可以执行取值操作。

⑩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--;// 队列元素个数-1
        if (itrs != null)
            itrs.elementDequeued();// 迭代器执行elementDequeued(用来保证一致性)
        notFull.signal();// 唤醒notFull对象监视器
        return x;
    }

唤醒notFull对象监视器,用于通知可被notFull阻塞的存值方法(offer或者put)有元素被移除,可以执行入队操作。

总结

1、ArrayBlockingQueue是使用数组进行存储的
2、enqueue()和dequeue()方法是入队和出队的核心方法。它们分别通知“队列非空”和“队列非满”,从而使阻塞中的出队和入队方法能继续执行,以实现生产者消费者模式。
3、插入只能从队尾开始,移除可以是任意位置,但是移除队头以外的元素效率很低。
4、ArrayBlockingQueue是个循环队列

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值