一、概念
ArrayBlockingQueue 是一个底层又数组实现有界队列,遵循FIFO的规则对元素进行排序,默认情况下不保证线程公平的访问队列。
二、源码分析
基本属性:
/** 底层数组实现 */
final Object[] items;
/** 记录队首元素的索引下标,用于take,poll,peek,remove 等方法*/
int takeIndex;
/** 记录队尾元素的索引下标,索引用于 put,offer,or add 等方法 */
int putIndex;
/**记录队列中的元素个数 */
int count;
/*
* Concurrency control uses the classic two-condition algorithm
* found in any textbook.
*/
/** ReentrantLock 默认是非公平的 */
final ReentrantLock lock;
/** 有2个条件对象,分别表示队列不为空和队列不满的情况 */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;
/** 迭代器状态 */
transient Itrs itrs = null;
//可以通过fair为true来实现公平锁
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();
}
方法:
add():
在不超出队列长度的情况下插入元素,可以立即执行,成功返回true,如果队列满了就抛出异常,其底层实现的是offer方法,不会阻塞。
测试:
private static final int CLEAN_QUEUE_MAX_SIZE = 50;
@Test()
public void test1(){
BlockingQueue<Integer> arrayBlockingQueue = Queues.newArrayBlockingQueue(CLEAN_QUEUE_MAX_SIZE);
IntStream.rangeClosed(0,50).forEach( its -> assertThat(arrayBlockingQueue.add(its), equalTo(true)));
}
源码:
// 调用了父类AbstractQueue的add()方法
public boolean add(E e) {
return super.add(e);
}
// AbstractQueue中的add方法又调用了offer(e)而offer(e)的实现又在ArrayBlockingQueue中
public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
offer(E e):
在不超出队列长度的情况下插入元素的时候则可以立即在队列的尾部插入指定元素,成功时返回true,如果此队列已满,则返回false。不会阻塞。
private static void checkNotNull(Object v) {
if (v == null)
throw new NullPointerException();
}
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();
}
}
//将数据添加到队列中的具体方法
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
items[putIndex] = x;
// 判断当前插入下标是否为数组最后一位,指针移到[0],元素个数+1
if (++putIndex == items.length)
putIndex = 0;
count++;
//唤醒因为notEmpty条件而阻塞的线程,比如上面的调用take方法的线程
notEmpty.signal();
}
offer(E e, long timeout, TimeUnit unit):
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) {
// 如果等待时间过了队列还是满的话就直接返回false,添加元素失败,finally块中释放锁
if (nanos <= 0)
return false;
// 等待设置的时间
nanos = notFull.awaitNanos(nanos);
}
enqueue(e);
return true;
} finally {
lock.unlock();
}
}
put(E e):
如果 BlockQueue 没有空间,则调用此方法的线程被阻断直到 BlockingQueue 里面有空间再继续,会阻塞,可以响应中断。
测试:
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.schedule( () -> {
try {
assertThat(arrayBlockingQueue.take(), equalTo(1));
} catch (InterruptedException e) {
e.printStackTrace();
}
},3, TimeUnit.SECONDS);
executorService.shutdown();
IntStream.rangeClosed(1,51).forEach( its -> {
try {
arrayBlockingQueue.put(its);
System.out.println(its);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
// 因为后面调用了条件变量的await()方法,而await()方法会在中断标志设置后抛出InterruptedException异常后退出,所以还不如在加锁
// 时候先看中断标志是不是被设置了,如果设置了直接抛出InterruptedException异常,就不用再去获取锁了
lock.lockInterruptibly();
try {
while (count == items.length)
//如果队列满的话就阻塞等待,直到notFull的signal方法被调用,也就是队列里有空间了
notFull.await();
enqueue(e);
} finally {
lock.unlock();
}
}
生产中大多数情况下使用offer 避免阻塞引发bug
take()
take方法也是用于取队列中的数据,但是和poll方法不同的是它有可能会阻塞当前的线程,可以打断
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
// 当队列为空时,就会阻塞当前线程
notEmpty.await();
//直到队列中有数据了,调用dequeue方法将数据返回
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];
// 将对应的数组下标位置设置为null释放资源
items[takeIndex] = null;
// 如果为数组最后一位,takeIndex 指向[0],假如已经取到了数组的末尾,那么就要重新开始取
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
//激活因为notFull条件而阻塞的线程
notFull.signal();
return x;
}
void elementDequeued() {
// assert lock.getHoldCount() == 1;
if (count == 0)
queueIsEmpty();
else if (takeIndex == 0)
takeIndexWrapped();
}
poll()
列不为空时返回队首值并移除;队列为空时返回null。非阻塞立即返回。
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
// count为0返回null,否则返回当前队列第一个值
return (count == 0) ? null : dequeue();
} finally {
lock.unlock();
}
}
peek()
peek方法不会真正的从队列中删除元素,实际上只是取出头元素而已。
public E peek() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return itemAt(takeIndex); // null when queue is empty
} finally {
lock.unlock();
}
}
final E itemAt(int i) {
return (E) items[i];
}
drainTo(Collection<? super E> c)
一次性从BlockingQueue获取所有可用的数据对象(还可以指定获取数据的个数),通过该方法,可以提升获取数据效率;不需要多次分批加锁或释放锁。