有哪些
为什么
阻塞队列这块的应用场景,比较多的仍然是对于生产者消 费者场景的应用,但是由于分布式架构的普及,是的大家 更多的关注在分布式消息队列上。所以其实如果把阻塞队 列比作成分布式消息队列的话,那么所谓的生产者和消费 者其实就是基于阻塞队列的解耦。
另外,阻塞队列是一个 fifo 的队列,所以对于希望在线程 级别需要实现对目标服务的顺序访问的场景中,也可以使 用
怎么用
插入操作
add(e) :添加元素到队列中,如果队列满了,继续插入 元素会报错,IllegalStateException。
offer(e) : 添加元素到队列,同时会返回元素是否插入 成功的状态,如果成功则返回 true
put(e) :当阻塞队列满了以后,生产者继续通过 put 添加元素,队列会一直阻塞生产者线程,直到队列可用
offer(e,time,unit) :当阻塞队列满了以后继续添加元素, 生产者线程会被阻塞指定时间,如果超时,则线程直接 退出
移除操作
remove():当队列为空时,调用 remove 会返回 false, 如果元素移除成功,则返回 true
poll(): 当队列中存在元素,则从队列中取出一个元素, 如果队列为空,则直接返回 null
take():基于阻塞的方式获取队列中的元素,如果队列为 空,则 take 方法会一直阻塞,直到队列中有新的数据可 以消费
poll(time,unit):带超时机制的获取数据,如果队列为空, 则会等待指定的时间再去获取元素返回
原理分析
ArrayBlockingQueue为例
构造函数
ArrayBlockingQueue 提供了三个构造方法(int capacity, boolean fair, Collection<? extends E> c) ,分别如下。
capacity: 表示数组的长度,也就是队列的长度
fair:表示是否为公平的阻塞队列,默认情况下构造的是非 公平的阻塞队列。
其中第三个构造方法就不解释了,它提供了接收一个几个 作为数据初始化的方法
add
调用父类的模板方法解决这个通用问题
//从父类的 add 方法可以看到,这里做了一个队列是否满了的判
断,如果队列满了直接抛出一个异常
public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
offer
1. 判断添加的数据是否为空
2. 添加重入锁
3. 判断队列长度,如果队列长度等于数组长度,表示满了 直接返回 false
4. 否则,直接调用 enqueue 将元素添加到队列中
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();
}
}
enqueue
方法内部通过 putIndex 索引直接将 元素添加到数组 items
/**
* Inserts element at current put position, advances, and signals.
* Call only when holding lock.
*/
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
items[putIndex] = x;//通过 putIndex 对数据赋值
if (++putIndex == items.length)// 当putIndex 等于数组长度时,将 putIndex 重置为 0
putIndex = 0;
count++;//记录队列元素的个数
notEmpty.signal();;//唤醒处于等待状态下的线程,表示当前队列中的元素不为空,如果存在消费者线程阻塞,就可以开始取出元素
}
putIndex 为什么会在等于数 组长度的时候重新设置为 0
因为 ArrayBlockingQueue 是一个 FIFO 的队列,队列添加 元素时,是从队尾获取 putIndex 来存储元素,当 putIndex 等于数组长度时,下次就需要从数组头部开始添加了。 下面这个图模拟了添加到不同长度的元素时,putIndex 的 变化,当 putIndex 等于数组长度时,不可能让 putIndex 继 续累加,否则会超出数组初始化的容量大小。
同时大家还 需要思考两个问题
1. 当元素满了以后是无法继续添加的,因为会报错
2. 其次,队列中的元素肯定会有一个消费者线程通过 take 或者其他方法来获取数据,而获取数据的同时元素也会 从队列中移除
put
/**
* Inserts the specified element at the tail of this queue, waiting
* for space to become available if the queue is full.
*
* @throws InterruptedException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();//这个也是获得锁,但是和 lock 的区别是,这个方法优先允许在待时由其他线程调用等待线程的 interrupt 方法来中断等待直接返回。而 lock方法是尝试获得锁成功后才响应中断
try {
while (count == items.length)
notFull.await();;//队列满了的情况下,当前线程将会被 notFull 条件对象挂起加到等待队列中
enqueue(e);
} finally {
lock.unlock();
}
}
take
take 方法是一种阻塞获取队列中元素的方法,它的实现原理很简单,有就删除没有就阻塞,注意这个阻 塞是可以中断的,如果队列没有数据那么就加入 notEmpty 条件队列等待(有数据就直接取走,方法结束),如果有新的 put 线程添加了数据,那么 put 操作将会唤醒 take 线程, 执行 take 操作。
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();//如果队列为空的情况下,直接通过 await 方法阻塞
return dequeue();
} finally {
lock.unlock();
}
}
dequeue
这个是出队列的方法,主要是删除队列头部的元素并发返 回给客户端
takeIndex,是用来记录拿数据的索引值
/**
* Extracts element at current take position, advances, and signals.
* Call only when holding lock.
*/
private E dequeue() {
// assert lock.getHoldCount() == 1;
// assert items[takeIndex] != null;
final Object[] items = this.items;
@SuppressWarnings("unchecked")
E x = (E) items[takeIndex]; //默认获取 0 位置的元素
items[takeIndex] = null;//将该位置的元素设置为空
if (++takeIndex == items.length))//这里的作用也是一样,如果拿到数组的最大值,那么重置为 0,继续从头部位置开始获取数据
takeIndex = 0;
count--;//记录 元素个数递减
if (itrs != null)
itrs.elementDequeued();//同时更新迭代器中的元素数据
notFull.signal();//触发因为队列满了以后导致的被阻塞的线程
return x;
}
itrs.elementDequeued();
ArrayBlockingQueue 中,实现了迭代器的功能,也就是可 以通过迭代器来遍历阻塞队列中的元素。所以 itrs.elementDequeued() 是用来更新迭代器中的元 素数据的
takeIndex 的索引变化和putIndex类似,同时随着数据的移除,会唤 醒处于 put 阻塞状态下的线程来继续添加数据
remove
是移除一个指定元素
/**
* Removes a single instance of the specified element from this queue,
* if it is present. More formally, removes an element {@code e} such
* that {@code o.equals(e)}, if this queue contains one or more such
* elements.
* Returns {@code true} if this queue contained the specified element
* (or equivalently, if this queue changed as a result of the call).
*
* <p>Removal of interior elements in circular array based queues
* is an intrinsically slow and disruptive operation, so should
* be undertaken only in exceptional circumstances, ideally
* only when the queue is known not to be accessible by other
* threads.
*
* @param o element to be removed from this queue, if present
* @return {@code true} if this queue changed as a result of the call
*/
public boolean remove(Object o) {
if (o == null) return false;
final Object[] items = this.items;//获取数组元素
final ReentrantLock lock = this.lock;
lock.lock();//获得锁
try {
if (count > 0) { //如果队列不为空
final int putIndex = this.putIndex;//获取下一个要添加元素时的索引
int i = takeIndex;//获取当前要被移除的元素的索引
do {
if (o.equals(items[i])) {{//从takeIndex 下标开始,找到要被删除的元素
removeAt(i);//移除指定元素
return true;//返回执行结果
}
//当前删除索引执行加 1 后判断是否与数组长度相等
//若为 true,说明索引已到数组尽头,将 i 设置为 0
if (++i == items.length)
i = 0;
} while (i != putIndex);//继续查找,直到找到最后一个元素
}
return false;
} finally {
lock.unlock();
}
}
附加:AtomicInteger.getAndIncrement实现原理
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
Unsafe 类我们前面在分析 AQS 的时候讲过,这个类相当 于是一个后门,使得 Java 可以像 C 语言的指针一样直接操 作内存空间。
valueOffset:通过 unsafe.objectFieldOffset() 获取当前 Value 这个变量在内存中的偏移量,后续会基于 这个偏移量从内存中得到value的值来和当前的值做比较, 实现乐观锁
乐观锁:一直循环直到成功