BlockingQueue源码分析
BlockingQueue首先是一个队列,而Blocking指的是当需要从队列中获取数据时,如果队列当前是空的,那么会一直阻塞直到队列不为空;当需要向队列中添加数据时,如果队列是满的,那么会一直阻塞直到队列中有空间来添加新的数据。
BlockingQueue可以很好地实现生产者-消费者
下面主要分析ArrayBlockingQueue
ArrayBlockingQueue
构造函数
主要参数有两个,一个是指定队列的容量,另外一个是指定是否公平
如果是公平的,那么因为在队列上进行添加或者删除操作而阻塞的线程会按照FIFO的顺序得到处理,即如果A线程和B线程都因为添加操作而阻塞了,那么当队列中有空余空间时,首先让A线程来执行添加操作,再让B线程执行添加操作
从下面的源码中也可以看出,ArrayBlockingQueue使用的是Lock condition来进行并发控制的,并且公平还是不公平,决定创建ReentrantLock的类型是公平的还是不公平的
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();
}
添加
offer方法是从Queue继承下来的
put方法是从BlockingQueue继承下来的
下面通过阅读两个方法的源码来分析不同
public boolean offer(E e) {
// 首先判断添加的元素是否是null
// ArrayBlockingQueue不允许添加NULL,如果添加NULL,会抛出异常
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;
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;
// 如果下一个添加位置越界了,那么从头开始添加,相当于一个循环队列
if (++putIndex == items.length)
putIndex = 0;
count++;
// 因为当前队列肯定不为空了,所以唤醒哪些需要删除数据的线程
notEmpty.signal();
}
从上面offer和put的源码可以看出两者具有以下区别:
当队列已经满了时,offer会直接返回false代表添加失败,而put会阻塞线程,直到被其他线程唤醒并且添加成功才会退出函数
并且因为offer是从Queue继承下来的,所以不能另外抛出异常,而put可以抛出InterruptedException异常
删除
poll是从队列继承下来的
take是从BlockingQueue继承下来的
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
// 如果队列为空,那么返回NULL,否则返回dequee返的结果
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();
}
}
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;
}