系列傳送門:
- Java併發包源碼學習系列:AbstractQueuedSynchronizer
- Java併發包源碼學習系列:CLH同步隊列及同步資源獲取與釋放
- Java併發包源碼學習系列:AQS共享式與獨佔式獲取與釋放資源的區別
- Java併發包源碼學習系列:ReentrantLock可重入獨佔鎖詳解
- Java併發包源碼學習系列:ReentrantReadWriteLock讀寫鎖解析
- Java併發包源碼學習系列:詳解Condition條件隊列、signal和await
- Java併發包源碼學習系列:掛起與喚醒線程LockSupport工具類
- Java併發包源碼學習系列:JDK1.8的ConcurrentHashMap源碼解析
- Java併發包源碼學習系列:阻塞隊列BlockingQueue及實現原理分析
ArrayBlockingQueue概述
ArrayBlockingQueue是由數組構成的有界阻塞隊列,支持FIFO的次序對元素進行排序。
這是一個典型的有界緩衝結構,可指定大小存儲元素,供生產線程插入,供消費線程獲取,但注意,容量一旦指定,便不可修改。
隊列空時嘗試take操作和隊列滿時嘗試put操作都會阻塞執行操作的線程。
該類還支持可供選擇的公平性策略,ReentrantLock
可重入鎖實現,默認採用非公平策略,當隊列可用時,阻塞的線程都可以爭奪訪問隊列的資格。
阻塞隊列通過
ReentrantLock
+Condition
實現併發環境下的等待通知機制:讀操作和寫操作都需要獲取到AQS獨佔鎖才能進行操作,如果隊列爲空,則讀操作線程將會被包裝爲條件節點扔到讀線程等待條件隊列中,等待寫線程寫入新的元素,同時讀線程將會被喚醒,反之亦然。
類圖結構及重要字段
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
// 序列號, 用於序列化
private static final long serialVersionUID = -817911632652898426L;
// 底層存儲數據的定長數組
final Object[] items;
// 移除操作的index,可以理解爲隊頭位置
int takeIndex;
// 添加操作的index,可以理解爲隊尾位置
int putIndex;
// 元素個數
int count;
// 獨佔重入鎖
final ReentrantLock lock;
// 等待takes的條件對象
private final Condition notEmpty;
// 等待puts的條件對象
private final Condition notFull;
// Itrs表示隊列和迭代器之間的共享數據,其實用來存儲多個迭代器實例的
transient Itrs itrs = null;
}
構造器
使用ArrayBlockingQueue的時候,必須指定一個capacity阻塞隊列的容量。可以傳入可選的fair值,以採取不同公平性策略,默認使用非公平的策略。另外,可以傳入集合對象,直接構造阻塞隊列。
// 必須指定容量, 默認採用非公平策略
public ArrayBlockingQueue(int capacity) {
this(capacity, false);
}
// 另外,可指定公平性策略
public ArrayBlockingQueue(int capacity, boolean fair) {
// 對容量進行簡單校驗
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new Object[capacity]; // 初始化底層數組
lock = new ReentrantLock(fair); // 初始化lock
notEmpty = lock.newCondition(); // 初始化條件變量notEmpty
notFull = lock.newCondition(); // 初始化條件變量notFull
}
// 另外,可指定傳入集合直接構造
public ArrayBlockingQueue(int capacity, boolean fair,
Collection<? extends E> c) {
this(capacity, fair);
// 加鎖只是爲了可見性, 而不是爲了互斥特性
final ReentrantLock lock = this.lock;
lock.lock(); // Lock only for visibility, not mutual exclusion
try {
int i = 0;
try {
for (E e : c) { // 遍歷賦值
checkNotNull(e);
items[i++] = e;
}
} catch (ArrayIndexOutOfBoundsException ex) {
throw new IllegalArgumentException();
}
count = i;
putIndex = (i == capacity) ? 0 : i;
} finally {
lock.unlock();
}
}
出隊和入隊操作
隊列的操作最核心的部分莫過於入隊和出隊了,後面分析的方法基本上都基於這兩個工具方法。
入隊enqueue
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
// 把元素x放入數組
items[putIndex] = x;
// 下一個元素應該存放的下標位置
if (++putIndex == items.length)
putIndex = 0;
count++;
// 激活notEmpty的條件隊列因調用take操作而被阻塞的一個線程
notEmpty.signal();
}
- 將元素x置入數組中。
- 計算下一個元素應該存放的下標位置。
- 元素個數器遞增,這裏count前加了鎖,值都是從主內存中獲取,不會存在內存不可見問題,並且更新也會直接刷新回主內存中。
- 最後激活notEmpty的條件隊列因調用take操作而被阻塞的一個線程。
出隊dequeue
private E dequeue() {
// assert lock.getHoldCount() == 1;
// assert items[takeIndex] != null;
final Object[] items = this.items;
@SuppressWarnings("unchecked")
// 獲取元素
E x = (E) items[takeIndex];
// 置null
items[takeIndex] = null;
// 重新設置對頭下標
if (++takeIndex == items.length)
takeIndex = 0;
// 更新元素計數器
count--;
// 更新迭代器中的元素數據,itrs只用在使用迭代器的時候才實例化哦
if (itrs != null)
itrs.elementDequeued();
// 激活notFull的條件隊列因調用put操作而被阻塞的一個線程
notFull.signal();
return x;
}
- 獲取元素,並將當前位置置null。
- 重新設置隊頭下標。
- 元素計數器遞減。
- 更新迭代器中的元素數據,itrs默認情況下都是爲null的,只有使用迭代器的時候纔會實例化Itrs。
- 激活notFull的條件隊列因調用put操作而被阻塞的一個線程。
阻塞式操作
E take() 阻塞式獲取
take操作將會獲取當前隊列頭部元素並移除,如果隊列爲空則阻塞當前線程直到隊列不爲空,退出阻塞時返回獲取的元素。
那,線程阻塞至何時如何知道呢,其實當前線程將會因
notEmpty.await()
被包裝成等待節點置入notEmpty的條件隊列中,一旦enqueue操作成功觸發,也就是入隊成功,將會執行notEmpty.signal()
喚醒條件隊列中等待的線程,被轉移到AQS隊列中參與鎖的爭奪。
如果線程在阻塞時被其他線程設置了中斷標誌,則拋出InterruptedException異常並返回。
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
// 可響應中斷式地獲取鎖
lock.lockInterruptibly();
try {
// 如果隊列爲空,則將當前線程包裝爲等待節點置入notEmpty的條件隊列中
while (count == 0)
notEmpty.await();
// 非空,則執行入隊操作,入隊時喚醒notFull的條件隊列中的第一個線程
return dequeue();
} finally {
lock.unlock();
}
}
void put(E e) 阻塞式插入
put操作將向隊尾插入元素,如果隊列未滿則插入,如果隊列已滿,則阻塞當前線程直到隊列不滿。
如果線程在阻塞時被其他線程設置了中斷標誌,則拋出InterruptedException異常並返回。
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
// 如果隊列滿,則將當前線程包裝爲等待節點置入notFull的條件隊列中
while (count == items.length)
notFull.await();
// 非滿,則執行入隊操作,入隊時喚醒notEmpty的條件隊列中的第一個線程
enqueue(e);
} finally {
lock.unlock();
}
}
E poll(timeout, unit) 阻塞式超時獲取
在take阻塞式獲取方法的基礎上額外增加超時功能,傳入一個timeout,獲取不到而阻塞的時候,如果時間到了,即使還獲取不到,也只能立即返回null。
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0) {
// 隊列仍爲空,但是時間到了,必須返回了
if (nanos <= 0)
return null;
// 在條件隊列裏等着,但是需要更新時間
nanos = notEmpty.awaitNanos(nanos);
}
return dequeue();
} finally {
lock.unlock();
}
}
boolean offer(e, timeout, unit) 阻塞式超時插入
在put阻塞式插入方法的基礎上額外增加超時功能,傳入一個timeout,獲取不到而阻塞的時候,如果時間到了,即使還獲取不到,也只能立即返回null。
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
checkNotNull(e);
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length) {
if (nanos <= 0)
return false;
nanos = notFull.awaitNanos(nanos);
}
enqueue(e);
return true;
} finally {
lock.unlock();
}
}
其他常規操作
boolean offer(E e)
offer(E e)是非阻塞的方法,向隊尾插入一個元素,如果隊列未滿,則插入成功並返回true;如果隊列已滿則丟棄當前元素,並返回false。
public boolean offer(E e) {
checkNotNull(e); // 如果插入元素爲null,則拋出NullPointerException異常
// 獲取獨佔鎖
final ReentrantLock lock = this.lock;
lock.lock();
try {
// 如果隊列滿, 則返回false
if (count == items.length)
return false;
else {
// 否則則入隊
enqueue(e);
return true;
}
} finally {
lock.unlock();
}
}
E poll()
從隊列頭部獲取並移除第一個元素,如果隊列爲空則返回null。
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
// 如果爲空,返回null, 否則執行出隊操作
return (count == 0) ? null : dequeue();
} finally {
lock.unlock();
}
}
Boolean remove(Object o)
移除隊列中與元素o相等【指的是equals方法判定相同】的元素,移除成功返回true,如果隊列爲空或沒有匹配元素,則返回false。
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 {
// 找到了對應的元素的位置,removeAt刪除該位置的元素
if (o.equals(items[i])) {
removeAt(i);
return true;
}
if (++i == items.length)
i = 0;
} while (i != putIndex);
}
return false;
} finally {
lock.unlock();
}
}
// 移除removeIndex位置的元素
void removeAt(final int removeIndex) {
// assert lock.getHoldCount() == 1;
// assert items[removeIndex] != null;
// assert removeIndex >= 0 && removeIndex < items.length;
final Object[] items = this.items;
// 如果要移除元素的位置正好就是 隊頭位置,和之前出隊操作一樣
if (removeIndex == takeIndex) {
// removing front item; just advance
items[takeIndex] = null;
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
} else {
// an "interior" remove
// slide over all others up through putIndex.
final int putIndex = this.putIndex;
// 移除的不是隊頭,那就要對應將後面的元素補充上來,並更新putIndex的位置
for (int i = removeIndex;;) {
int next = i + 1;
if (next == items.length)
next = 0;
// 移除的不是隊尾,後面的元素補充上來
if (next != putIndex) {
items[i] = items[next];
i = next;
} else {
// 移除的是隊尾元素
items[i] = null;
this.putIndex = i;
break;
}
}
count--;
if (itrs != null)
itrs.removedAt(removeIndex);
}
notFull.signal();
}
總結
-
ArrayBlockingQueue基於數組的有界阻塞隊列,必須指定容量大小,及隊列中最多允許的元素個數。
-
提供了take和put兩個阻塞式的操作,還提供了阻塞式+超時機制的操作。
-
阻塞隊列通過
ReentrantLock
+Condition
實現併發環境下的等待通知機制:讀操作和寫操作都需要獲取到AQS獨佔鎖才能進行操作,如果隊列爲空,則讀操作線程將會被包裝爲條件節點扔到讀線程等待條件隊列中阻塞,等待寫線程寫入新的元素,並喚醒等待中的讀線程,反之亦然。
本篇重點看了出隊入隊相關方法,其餘部分如迭代器相關不是本文重點,如果想了解學習可以參看:ArrayBlockingQueue 迭代器
參考閱讀
- 《Java併發編程之美》
- 《Java併發編程的藝術》