ArrayBlockingQueue源码解读

作者: 辣公公 | 来源:发表于2016-12-14 01:15 被阅读82次

ArrayBlockingQueue是一个有界的阻塞队列,所有的元素按照先入先出(FIFO)的规则进队出队,在队列的末尾插入元素,在队列的头部取出元素。如下表格,只能在*号处插入数字8。

Head Tail
1 2 3 4 5 6 7 *

ArrayBlockingQueue特殊的地方

  • 一旦初始化后将不能改变其容量大小
  • offer:插入元素,当队列满时返回false插入失败,当队列未满返回true,插入成功。
  • poll:offer 的逆过程,不做解释。
  • add :内部实现是调用offer,当队列满时,throw new IllegalStateException("Queue full")。
  • remove : 内部实现是调用poll,当队列为空时,throw new NoSuchElementException()。
  • put :向队列中插入数据,当队列满时该插入线程会暂停(await),直到有线程signal 后继续插入,直到插入成功为止。
  • take :put的逆过程,不做解释。

源码部分

  1. 几个关键的成员变量(主要看注释
/** The queued items */
    final Object[] items;//数据形式存放所有元素。数组需要指定大小,这也说明了为什么是有界的了

    /** items index for next take, poll, peek or remove */
    int takeIndex;//插入元素的位置

    /** items index for next put, offer, or add */
    int putIndex;//删除元素的位置

    /** Number of elements in the queue */
    int count;//元素的个数

    /*
     * Concurrency control uses the classic two-condition algorithm
     * found in any textbook.
     */

    /** Main lock guarding all access */
    final ReentrantLock lock;//重入锁,构造函数传入的fair就是给他用

    /** Condition for waiting takes */
    private final Condition notEmpty;//用于在删除时阻塞线程

    /** Condition for waiting puts */
    private final Condition notFull;//用于在插入时阻塞线程
注意ArrayBlockingQueue在插入或者删除的时候并没有做元素位置的交换,而是记录相应的位置,简单有图展示一黄色表示有元素

在执行put将变为下图


可以看出ArrayBlockingQueue在循环使用数组
  1. 构造函数-----capacity 队列的容量,fair 锁竞争时是否使用公平锁
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();
    }
  1. 入队:将数组putIndex的值设置成插入的值,然后调整putIndex的位置,count++,最后signal 随机唤醒一个线程,继续执行入队或者出队
private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length)//这里循环时候数组
            putIndex = 0;
        count++;
        notEmpty.signal();
    }
  1. 出队:将数组putIndex的值设置未null,然后调整takeIndex的位置,count--,最后signal 随机唤醒一个线程,继续执行入队或者出队
private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        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;
    }
  1. offer:队列未满时插入
public boolean offer(E e) {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == items.length)
                return false;
            else {
                enqueue(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }
  1. poll:队列为空时返回null,不空是返回队列末尾的元素
public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : dequeue();
        } finally {
            lock.unlock();
        }
    }
  1. put:当队列满时,notFull.await()等待,直到dequeue 发出signal,继续尝试入队操作
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();
        }
    }

插入的元素不能为空

  1. take:当队列未空时,notEmpty.await()等待,直到enqueue 发出signal尝试出队操作
public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

相关文章

  • ArrayBlockingQueue源码解读

    ArrayBlockingQueue是一个有界的阻塞队列,所有的元素按照先入先出(FIFO)的规则进队出队,在队列...

  • ArrayBlockingQueue源码解读

    虽然在某程序员最喜欢的工具调查中,90%的人选择了eclipse,但是我这里还是要强烈推荐idea.我在来我目前公...

  • SynchronousQueue源码解析

    阻塞队列系列 ArrayBlockingQueue源码解析 LinkedBlockingQueue源码解析 通过上...

  • LinkedBlockingQueue源码解析

    阻塞队列系列 ArrayBlockingQueue源码解析 SynchronousQueue源码解析 Linked...

  • DelayQueue源码分析

    阻塞队列系列 ArrayBlockingQueue源码解析 LinkedBlockingQueue源码解析 Syn...

  • ArrayBlockingQueue源码分析

    ArrayBlockingQueue源码分析 ArrayBlockingQueue是一个用数组实现的队列,所以在效...

  • BlockingQueue

    ArrayBlockingQueue源码分析LinkedBlockingQueue源码分析 使用阻塞队列实现的生产...

  • ArrayBlockingQueue源码分析

    前言 ArrayBlockingQueue以数组的方式实现了BlockingQueue接口。其是线程安全的,提供了...

  • ArrayBlockingQueue源码解析

    ArrayBlockingQueue是一个用数组实现的有界阻塞队列,通过全局独占锁来实现出队和入队操作,同时只能有...

  • java源码-ArrayBlockingQueue

    开篇  ArrayBlockingQueue是数组实现的线程安全的有界的阻塞队列。 线程安全是指ArrayBloc...

网友评论

    本文标题:ArrayBlockingQueue源码解读

    本文链接:https://www.haomeiwen.com/subject/axzbmttx.html