ArrayBlockingQueue实现原理

ArrayBlockingQueue

有界阻塞队列,初始化的时候必须要指定队列长度,且指定长度之后不允许进行修改,内部使用数组持有元素。

它的主要属性如下

// 存储队列元素的数组,是个循环数组
final Object[] items;

// 拿数据的索引,用于take,poll,peek,remove方法
int takeIndex;

// 放数据的索引,用于put,offer,add方法
int putIndex;

// 元素个数
int count;

// 可重入锁
final ReentrantLock lock;
// notEmpty条件对象,由lock创建
private final Condition notEmpty;
// notFull条件对象,由lock创建
private final Condition notFull;

可见,ArrayBlockingQueue只有1个锁,同一时刻,要么添加数据,要么删除数据,两者不能并行执行。

插入元素

offer()方法:如果队列已满,直接返回fasle

其中的insert方法如下:

add()方法:如果队列已满,抛出IllegalStateException("Queue full")异常;

put()方法:如果队列已满,当前线程会一直阻塞,直到队列中出现空位或响应中断退出

移除元素

poll()方法:如果队列为空,直接返回null

poll()方法内部调用extract()方法:

take()方法:如果队列为空,当前线程会一直阻塞,直到队列中有元素插入或响应中断退出;

remove()方法:如果队列为空,则抛出NoSuchElementException异常

内容来源:Java阻塞队列ArrayBlockingQueue和LinkedBlockingQueue实现原理分析

Last updated