ArrayBlockingQueue是线程安全的阻塞队列,底层是基于数组实现的,既然是数组,那肯定是有界的。
保证线程安全是通过可重入锁ReentrantLock实现,且可以控制是公平锁还是非公平锁
另外,还提供了Condition条件还控制队列的空和满。当插入一个元素进去,发现队列满了,就会调用notFull.await(),取走一个元素的时候,就会调用notFull.signal()唤醒插入元素的那个线程。当取走元素时发现队列是空时,就调用notEmpty.await()阻塞,等待插入线程插入一个元素后调用notEmpty.signal()唤醒需要取走元素的线程。
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
private static final long serialVersionUID = -817911632652898426L;
// 存放元素的数组
final Object[] items;
/** items index for next take, poll, peek or remove */
// 对于下一个要取走的元素的下标,一般指向队列头
int takeIndex;
/** items index for next put, offer, or add */
// 下一个要插入的元素的下标,一般指向队列尾部
int putIndex;
// 元素数量
int count;
/*
* Concurrency control uses the classic two-condition algorithm
* found in any textbook.
*/
// 并发控制的锁,并且带着两个condition条件
final ReentrantLock lock;
// 等待取走元素的条件,取走元素的线程因为这个条件阻塞和被唤醒
private final Condition notEmpty;
// 等待放入元素的条件,插入元素的线程因为这个条件阻塞和被唤醒
private final Condition notFull;
// 迭代器
transient Itrs itrs = null;
// Internal helper methods
/**
* Circularly decrement i.
*/
// 循环的-1,如果i=0,就取数组长度-1,否则就用i-1
final int dec(int i) {
return ((i == 0) ? items.length : i) - 1;
}
// 返回在i处的元素
@SuppressWarnings("unchecked")
final E itemAt(int i) {
return (E) items[i];
}
// 检查插入的元素非null
private static void checkNotNull(Object v) {
if (v == null)
throw new NullPointerException();
}
/**
* Inserts element at current put position, advances, and signals.
* Call only when holding lock.
*/
// 插入元素到队列
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
// 在putIndex处插入元素x,如果下一个要插入的位置为数组长度了,那肯定不能往那插了因为会数
// 组越界,所以把下一个要插入的元素置0,数组满了再插入的话会抛出异常的。
items[putIndex] = x;
if (++putIndex == items.length)
putIndex = 0;
// 元素个数+1
count++;
// 唤醒正在等待取元素的线程
notEmpty.signal();
}
//取出元素
private E dequeue() {
// assert lock.getHoldCount() == 1;
// assert items[takeIndex] != null;
final Object[] items = this.items;
@SuppressWarnings("unchecked")
// 强行把元素类型转成泛型
E x = (E) items[takeIndex];
// 把这一处的元素删除置null,帮助gc回收
items[takeIndex] = null;
// 如果下次取元素的下标达到数组长度了,就置0
if (++takeIndex == items.length)
takeIndex = 0;
// 数组元素-1
count--;
if (itrs != null)
itrs.elementDequeued();
// 唤醒正在因为数组满了而等待的插入元素的线程
notFull.signal();
return x;
}
// 删除在索引removeIndex的元素
void removeAt(final int removeIndex) {
// assert lock.getHoldCount() == 1;
// assert items[removeIndex] != null;
// assert removeIndex >= 0 && removeIndex < items.length;
final Object[] items = this.items;
// 如果要删除的索引位置正好是下一次要取元素的位置
if (removeIndex == takeIndex) {
// 正常删除,和出队的操作一致
items[takeIndex] = null;
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
} else {
// an "interior" remove
// 如果删除的位置不是下一个要取走的元素位置
// slide over all others up through putIndex.
// 下一个要放入的元素位置
final int putIndex = this.putIndex;
// 从要删除的位置处开始遍历
// 如果next还没有到达数组尾部putIndex,就把后面的数组元素往前挪
// 如果next已经挪到尾部了,这个时候就把最后一个元素置null,下一个要插入的位置也在这
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;
}
}
// 元素个数-1,并且把迭代器里的元素删除
count--;
if (itrs != null)
itrs.removedAt(removeIndex);
}
// 唤醒正在等待插入元素的线程
notFull.signal();
}
// 构造函数一定要提供数组容量
public ArrayBlockingQueue(int capacity) {
this(capacity, false);
}
// 构造函数,初始化元素
public ArrayBlockingQueue(int capacity, boolean fair,
Collection<? extends E> c) {
this(capacity, fair);
final ReentrantLock lock = this.lock;
lock.lock(); // Lock only for visibility, not mutual exclusion
try {
int i = 0;
try {
for (E e : c) {
checkNotNull(e);
items[i++] = e;
}
} catch (ArrayIndexOutOfBoundsException ex) {
throw new IllegalArgumentException();
}
count = i;
// 一般是0,如果带着Collection进来就是Collection元素个数
putIndex = (i == capacity) ? 0 : i;
} finally {
lock.unlock();
}
}
// 调用AbstractQueue的offer方法,其实调用的是下面重写的offer方法
public boolean add(E e) {
return super.add(e);
}
// 插入元素
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 void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
// 上锁,若当前线程是中断状态,则抛出InterruptedException异常
lock.lockInterruptibly();
try {
// 如果容量满了就等待
while (count == items.length)
notFull.await();
// 入队
enqueue(e);
} finally {
lock.unlock();
}
}
// 插入一个元素,如果队列满了就等待一定时间
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
checkNotNull(e);
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length) {
if (nanos <= 0)
return false;
nanos = notFull.awaitNanos(nanos);
}
enqueue(e);
return true;
} finally {
lock.unlock();
}
}
// 取出队首的元素,队列为空就马上返回null
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (count == 0) ? null : dequeue();
} finally {
lock.unlock();
}
}
// 取出队首元素,移除队首,如果为空就等待,可用时再出队
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return 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();
}
}
// 取出队首元素,但是不移除队列头
public E peek() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return itemAt(takeIndex); // null when queue is empty
} finally {
lock.unlock();
}
}
// 获取元素个数
public int size() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}