ArrayBlockingQueue 可以理解为环形数组的结构保存元素,里面只用了一把重入锁来控制出入队列的操作。另外,它虽然可以保证先进先出,但是入队列或者出队列有公平和非公平的选择,是通过重入锁实现的,默认是非公平的,那么入队列或者出队列不一定是先来的先请求到。
一、代码结构
从下面代码中可以看到ArrayBlockingQueue内部是维护了一个数据items,以及一个重入锁控制访问。
public ArrayBlockingQueue(int capacity) {
this(capacity, false);
}
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();
}
final Object[] items;
/** 获取元素的数组下标,下一次从这里获取元素 */
int takeIndex;
/** 插入元素的数组下标,下一次从这里插入数组 */
int putIndex;
/** 队列中的元素数量 */
int count;
/** 重入锁控制所有操作 */
final ReentrantLock lock;
/** Condition for waiting takes */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;
二、入队列操作
阻塞方法
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();
}
}
// 这是正式的入队列逻辑
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
items[putIndex] = x;
// putIndex加一,如果等于队列最大容量,则下一次从下标为0的地方插入元素
if (++putIndex == items.length)
putIndex = 0;
// 计数器加1
count++;
// 唤醒等待出队列的线程
notEmpty.signal();
}
非阻塞方法
public boolean offer(E e) {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lock();
try {
// 如果队列满了就返回false
if (count == items.length)
return false;
else {
enqueue(e);
return true;
}
} finally {
lock.unlock();
}
}
三、出队列操作
阻塞方法
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
// 轮询如果为0则等待出队列
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
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;
// 如果取数下标等于容量大小,则下一次从0下标开始取
if (++takeIndex == items.length)
takeIndex = 0;
count--;
// 这里是迭代器的逻辑,暂时不考虑研究了
if (itrs != null)
itrs.elementDequeued();
// 唤醒等待入队列的线程
notFull.signal();
return x;
}
非阻塞方法
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
// 只要队列不为空就返回元素,否则返回空
return (count == 0) ? null : dequeue();
} finally {
lock.unlock();
}
}
四、窥视方法
窥视方法直接就是返回takeIndex下标的元素了
public E peek() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return itemAt(takeIndex); // null when queue is empty
} finally {
lock.unlock();
}
}
五、总结
从以上代码分析中,我们可以得出下面几点结论
- ArrayBlockingQueue的非公平模式可能会产生饥饿,某个线程可能长时间获取不到锁。
- 出入队列都要获取同一把锁,会影响并发吞吐量。
- 内部逻辑较简单,容易理解。