简介
Java 的阻塞队列是应用在多线程中,尤其适合生产者和消费者模式,阻塞队列支持阻塞操作,线程安全,已经实现了繁琐的简单锁和重入锁。
阻塞队列框架
特性
- BlockingQueue不接受 null 元素。
试图 add、put或 offer一个 null元素时,某些实现会出 NullPointerException。null被用作指示 poll操作失败的警戒值。 - BlockingQueue可以是限定容量的。
它在任意给定时间都可以有一个 remainingCapacity,超出此容量,便无法无阻塞地 put额外的元素。没有任何内部容量约束的 BlockingQueue总是报告 Integer.MAX_VALUE的剩余容量。 - BlockingQueue 实现主要用于生产者-使用者队列。
即一个线程向队列添加数据,另外一个线程向队列获取数据。 - BlockingQueue 实现是线程安全的。
所有排队方法都可以使用内部锁定或其他形式的并发控制来自动达到它们的目的,内部实现了繁琐的线程锁机制。
主要方法
操作方式 | 一直阻塞 | 超时退出 | 抛出异常 | 返回值 |
---|---|---|---|---|
插入 | put(e) | offer(timeout,unit) | add(e) | offer(e) |
移除 | take(e) | poll(timeout,unit) | remove() | poll() |
检查 | 无 | 无 | element() | peek() |
ArrayBlockingQueue
- 特性
- 基于数组的阻塞队列,按FIFO原则对元素进行排序。
队列的头部 是在队列中存在时间最长的元素。队列的尾部 是在队列中存在时间最短的元素。新元素插入到队列的尾部,队列检索操作则是从队列头部开始获得元素。 - 容量大小固定。
一旦创建了这样的缓存区,就不能再增加其容量。试图向已满队列中放入元素会导致放入操作受阻塞;试图从空队列中检索元素将导致类似阻塞。 - 可选公平策略。
默认情况下不保证按FIFO顺序访问队列,可以通过创建队列的时设置fair为true,从而允许FIFO顺序访问队列。
- 基于数组的阻塞队列,按FIFO原则对元素进行排序。
公平策略:所谓公平访问队列是指阻塞的所有生产者线程或消费者线程,当队列可用时,可以按照阻塞的先后顺序访问队列,即先阻塞的生产者线程,可以先往队列里插入元素,先阻塞的消费者线程,可以先从队列里获取元素。
通过以下方式来创建可公平访问的队列。
ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<String>(500,true);
实际项目中的应用
在smack中就是用到了ArrayBlockingQueue阻塞队列来存储要发送的消息,一个线程负责从队列中获取消息然后发送出去,其他的线程向队列中插入消息。
初始化阻塞队列:
protected PacketWriter(XMPPConnection connection) {
this.queue = new ArrayBlockingQueue<Packet>(500, true);
this.connection = connection;
init();
}
从队列中获取消息:
private Packet nextPacket() {
Packet packet = null;
// Wait until there's a packet or we're done.
while (!done && (packet = queue.poll()) == null) {
try {
synchronized (queue) {
queue.wait();
}
}
catch (InterruptedException ie) {
// Do nothing
}
}
return packet;
}
向队列中插入消息:
public void sendPacket(Packet packet) {
if (!done) {
// Invoke interceptors for the new packet that is about to be sent. Interceptors
// may modify the content of the packet.
connection.firePacketInterceptors(packet);
try {
queue.put(packet);
}
catch (InterruptedException ie) {
ie.printStackTrace();
return;
}
synchronized (queue) {
queue.notifyAll();
}
// Process packet writer listeners. Note that we're using the sending
// thread so it's expected that listeners are fast.
connection.firePacketSendingListeners(packet);
}
}
插入消息的时候,就用到了put()方法,如果该队列满了,会一直阻塞,直到有空闲。
LinkedBlockingQueue
- 一个基于已链接节点的、范围任意的 blocking queue。
- 此队列按 FIFO(先进先出)排序元素。
- 默认长度 Integer.MAX_VALUE。
- 动态地创建链接节点。
但是为了防止队列过度扩展,构造该队列时可设置固定容量大小。
实际项目应用
也是smack项目中的使用。
MAX_PACKETS = 65536
protected PacketCollector(Connection conection, PacketFilter packetFilter) {
this.conection = conection;
this.packetFilter = packetFilter;
this.resultQueue = new LinkedBlockingQueue<Packet>(MAX_PACKETS);
}
超时的操作:
public Packet nextResult(long timeout) {
long endTime = System.currentTimeMillis() + timeout;
do {
try {
return resultQueue.poll(timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) { /* ignore */ }
} while (System.currentTimeMillis() < endTime);
return null;
}
一直阻塞的操作:
public Packet nextResult() {
while (true) {
try {
return resultQueue.take();
} catch (InterruptedException e) { /* ignore */ }
}
}
从上面的使用来看,smack充分的利用了阻塞队列。
阻塞队列的实现原理
在了解原理之前,需要知道Java中的锁机制和种类,重点了解可重入锁。