LinkedBlockingQueue是一个单向链表的阻塞队列,头部和尾部分别有一个可重入锁控制写入和读取,并且两个锁还各自带了一个condition条件。这样可以增加并发度。
这也可以看作是一个可用在队列两端同时操作的队列
put()和take()方法都是当遇到满了或空了条件会阻塞的方法
offer()和poll()方法都是当遇到满了或空了直接返回false;或者是传入一个等到时间的参数。
其实这就像是生产者和消费者模型.
顺便说一下,如果不给它指定初始容量,会默认容量为Integer.MAX_VALUE,这样很容易导致OOM。
public class LinkedBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
private static final long serialVersionUID = -6903933977591709194L;
// 最简单的node节点了
static class Node<E> {
E item;
Node<E> next;
Node(E x) { item = x; }
}
// 链表容量
private final int capacity;
// 当前的元素个数
private final AtomicInteger count = new AtomicInteger();
// 链表头节点,只是一个标志,头节点存的值是null,真正的头节点是head.next
transient Node<E> head;
// 链表尾节点,只是一个标志,尾节点存的值是真实值,但是它的next是null
private transient Node<E> last;
/** Lock held by take, poll, etc */
// 取元素锁
private final ReentrantLock takeLock = new ReentrantLock();
/** Wait queue for waiting takes */
// 取元素锁的条件
private final Condition notEmpty = takeLock.newCondition();
/** Lock held by put, offer, etc */
// 插入元素锁
private final ReentrantLock putLock = new ReentrantLock();
/** Wait queue for waiting puts */
// 插入元素锁的条件
private final Condition notFull = putLock.newCondition();
/**
* Signals a waiting take. Called only from put/offer (which do not
* otherwise ordinarily lock takeLock.)
*/
// 唤醒一个正在等待取元素的线程
private void signalNotEmpty() {
final ReentrantLock takeLock = this.takeLock;
takeLock.lock();
try {
notEmpty.signal();
} finally {
takeLock.unlock();
}
}
/**
* Signals a waiting put. Called only from take/poll.
*/
// 唤醒一个正在等待插入元素的线程
private void signalNotFull() {
final ReentrantLock putLock = this.putLock;
putLock.lock();
try {
notFull.signal();
} finally {
putLock.unlock();
}
}
// 插入一个元素到队尾,如果队列满了就阻塞等待
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
// 新建一个node
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();
}
// 入队
enqueue(node);
// 元素个数+1,并返回队列原来的元素个数
c = count.getAndIncrement();
// 如果插入一个元素后还没有达到设定的容量就唤醒插入元素的线程,也就是还可以再插入,
// 尽管来
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
// 如果c=0,说明取元素的线程会阻塞,现在插入了一个元素,就唤醒它可以去取元素了
if (c == 0)
signalNotEmpty();
}
// 插入一个元素,如果队列满了,等待指定的时间,如果还是满就返回false,否则插入
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
if (e == null) throw new NullPointerException();
long nanos = unit.toNanos(timeout);
int c = -1;
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
// 如果线程被中断就抛出中断异常,不然就加插入锁
putLock.lockInterruptibly();
try {
while (count.get() == capacity) {
if (nanos <= 0)
return false;
nanos = notFull.awaitNanos(nanos);
}
// 入队
enqueue(new Node<E>(e));
// 把count+1并且返回+1之前的置
c = count.getAndIncrement();
// 如果+1后还没有达到容量就唤醒等待插入的线程,还可以再插入
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
// 如果c=0,说明读取元素的线程在阻塞,现在就可用唤醒它去取元素了
if (c == 0)
signalNotEmpty();
return true;
}
// 取元素,如果队列为空就阻塞
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();
// count+1,返回+1前的值
c = count.getAndDecrement();
// 如果c>1了就可以唤醒取元素的线程了
if (c > 1)
notEmpty.signal();
} finally {
takeLock.unlock();
}
// 如果c=capacity,插入元素的线程会在这个条件下阻塞,此时取走一个元素,就可以唤醒插入元素
// 的线程了
if (c == capacity)
signalNotFull();
return x;
}
// 取走元素,如果队列为空就等待指定的时间,如果还是空就返回false了
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
E x = null;
int c = -1;
long nanos = unit.toNanos(timeout);
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
takeLock.lockInterruptibly();
try {
while (count.get() == 0) {
if (nanos <= 0)
return null;
nanos = notEmpty.awaitNanos(nanos);
}
// 出队
x = dequeue();
c = count.getAndDecrement();
if (c > 1)
notEmpty.signal();
} finally {
takeLock.unlock();
}
if (c == capacity)
signalNotFull();
return x;
}
// 入队,直接把新插入的节点链接到最后一个节点
// 先把node赋值给最后一个节点的下一个节点,然后把这个下一个节点赋值给last节点
private void enqueue(Node<E> node) {
// assert putLock.isHeldByCurrentThread();
// assert last.next == null;
last = last.next = node;
}
// 出队,把头节点删除,把first节点赋值给之前头节点的下一个节点,返回之前头节点的值
private E dequeue() {
// assert takeLock.isHeldByCurrentThread();
// assert head.item == null;
Node<E> h = head;
// first保留的下一个节点的链接不变
Node<E> first = h.next;
h.next = h; // help GC
head = first;
E x = first.item;
first.item = null;
return x;
}
// 取走头节点,不删除头节点
public E peek() {
if (count.get() == 0)
return null;
final ReentrantLock takeLock = this.takeLock;
takeLock.lock();
try {
Node<E> first = head.next;
if (first == null)
return null;
else
return first.item;
} finally {
takeLock.unlock();
}
}
}