在Java中有这么一个接口BlockingQueue,它的子类有ArrayBlockingQueue和LinkedBlockingQueue,它们通常被称为阻塞队列。
关于阻塞队列,通常是用于解决“生产者——消费者”问题,而在本文中只针对LinkedBlockingQueue的源码进行讲解。本人建议是在阅读本文之前,先了解ArrayBlockingQueue(其中有对阻塞队列更加详细的描述)。
LinkedBlockingQueue重要属性
// 队列最大容量
private final int capacity;
// 队列元素数量
private final AtomicInteger count = new AtomicInteger();
// 队列头元素
transient Node<E> head;
// 队列末尾元素
private transient Node<E> last;
// 获取独占锁
private final ReentrantLock takeLock = new ReentrantLock();
// 条件队列,存放获取元素的的线程(因为队列为空无法获取,所以添加到该条件队列中,等待唤醒)
private final Condition notEmpty = takeLock.newCondition();
// 添加独占锁
private final ReentrantLock putLock = new ReentrantLock();
// 条件队列,存放添加元素的线程(因为队列满了无法添加,所以添加到该条件队列中,等待唤醒)
private final Condition notFull = putLock.newCondition();
通过以上属性的讲解,其实可以发现,LinkedBlockingQueue的底层实现是利用了两把独占锁,一把用于获取元素,一把用于添加元素。也就是说,获取元素和添加元素是两个独立操作,不会相互影响,以此来提高存取效率。
Node内部类
/**
* 由此可以看出LinkedBlockingQueue的内部是单向链表
*/
static class Node<E> {
E item;
Node<E> next;
Node(E x) { item = x; }
}
LinkedBlockingQueue常用方法源码解析
add & offer
public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
public boolean offer(E e) {
if (e == null) throw new NullPointerException();
final AtomicInteger count = this.count;
if (count.get() == capacity) // 队列已满,直接返回false
return false;
int c = -1;
Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock;
putLock.lock(); // 请求添加锁
try {
if (count.get() < capacity) { // 队列未满
enqueue(node); // 添加元素
c = count.getAndIncrement(); // 元素数量加1
if (c + 1 < capacity) // 添加完一个元素后,再判断当前元素数量加1,仍小于最大容量
notFull.signal(); // 则唤醒一个正在等待中的添加元素线程,再次进行添加元素
}
} finally {
putLock.unlock(); // 释放添加锁
}
if (c == 0) // c初始值为-1,等于0说明当前队列中已添加了一个元素
signalNotEmpty(); // 唤醒获取元素线程
return c >= 0;
}
private void enqueue(Node<E> node) {
last = last.next = node; // 将元素添加至队列末尾
}
private void signalNotEmpty() {
final ReentrantLock takeLock = this.takeLock;
takeLock.lock(); // 请求获取锁
try {
notEmpty.signal(); // 唤醒一个正在等待的获取元素线程
} finally {
takeLock.unlock(); // 释放获取锁
}
}
可以看到,add和offer方法在添加元素的过程中,首先判断当前队列是否已满,若已满则返回false;否则添加元素。
put
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
int c = -1;
Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
putLock.lockInterruptibly(); // 请求添加锁,在请求锁过程中,如果有其他线程对当前线程进行中断,则抛出异常终止添加操作
try {
while (count.get() == capacity) { // 队列已满
notFull.await(); // 将该添加元素线程加入notFull条件队列,等待唤醒
}
enqueue(node); // 队列未满,添加元素
c = count.getAndIncrement();
if (c + 1 < capacity) //
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}
put方法同样也是添加元素,但是它是首先判断当前队列是否已满,若已满,则陷入等待,并释放锁,直到队列不满的时候再被唤醒;否则直接添加元素。
poll
public E poll() {
final AtomicInteger count = this.count;
if (count.get() == 0)
return null;
E x = null;
int c = -1;
final ReentrantLock takeLock = this.takeLock;
takeLock.lock();
try {
if (count.get() > 0) { // 队列不为空
x = dequeue(); // 移除并获取头元素
c = count.getAndDecrement();
if (c > 1) // c的初始值为-1,大于1说明,在移除头元素后,队列中还有元素
notEmpty.signal(); // 唤醒一个获取元素线程
}
} finally {
takeLock.unlock();
}
if (c == capacity) // c等于最大容量,说明在移除头元素前,该队列已满,而现在已经移除了一个头元素,队列现在未满
signalNotFull(); // 唤醒添加元素线程
return x;
}
private E dequeue() {
// 移除头元素
Node<E> h = head;
Node<E> first = h.next;
h.next = h; // help GC
head = first;
E x = first.item;
first.item = null;
return x;
}
private void signalNotFull() {
final ReentrantLock putLock = this.putLock;
putLock.lock();
try {
notFull.signal(); // 唤醒添加元素线程
} finally {
putLock.unlock();
}
}
poll方法在获取元素的过程中,先判断当前队列是否为空,若不为空,再获取元素;否则直接返回空。
take
public E take() throws InterruptedException {
E x;
int c = -1;
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
takeLock.lockInterruptibly();
try {
while (count.get() == 0) { // 队列为空
notEmpty.await(); // 将该获取元素线程加入到条件队列,等待唤醒
}
x = dequeue(); // 队列不为空,则删除并获取头元素
c = count.getAndDecrement();
if (c > 1) // c初始值为-1,大于1说明,删除头元素后,还有元素
notEmpty.signal(); // 唤醒一个获取元素线程
} finally {
takeLock.unlock();
}
if (c == capacity) // c等于最大容量,说明在删除头元素前,队列已满,而现在已删除一个头元素,现队列未满
signalNotFull(); // 唤醒添加元素线程
return x;
}
take方法同样也是获取元素,不同的是,在获取元素的过程中,首先判断队列是否为空,若为空,则陷入等待,直到队列不为空后再被唤醒;否则直接获取元素。
remove
public boolean remove(Object o) {
if (o == null) return false;
fullyLock(); // 需要同时获取到添加锁和获取锁,才能进行删除操作
try {
for (Node<E> trail = head, p = trail.next; p != null; trail = p, p = p.next) { // 循环遍历删除指定元素
if (o.equals(p.item)) {
unlink(p, trail); // 移除元素
return true;
}
}
return false;
} finally {
fullyUnlock(); // 释放添加锁和获取锁
}
}
void fullyLock() {
putLock.lock();
takeLock.lock();
}
void unlink(Node<E> p, Node<E> trail) {
p.item = null;
trail.next = p.next;
if (last == p)
last = trail;
if (count.getAndDecrement() == capacity) // 移除元素前,队列已满
notFull.signal(); // 移除元素后,现队列未满,唤醒添加元素线程
}
void fullyUnlock() {
takeLock.unlock();
putLock.unlock();
}
到此,LinkedBlockingQueue的源码解析就结束了。我们可以通过以上的源码分析得知,LinkedBlockingQueue由两把锁:putLock和takeLock控制达到读写分离的效果。同时,remove方法中也可以看到,执行删除元素操作的条件是需要同时获取到两把锁,说明在执行删除操作的同时,不能执行读写操作。这样意味着,LinkedBlockingQueue不适用于频繁删除的场景。