本文講PriorityBlockingQueue(優先阻塞隊列)
1. 介紹
一個無界的具有優先級的阻塞隊列,使用跟PriorityQueue相同的順序規則,默認順序是自然順序(從小到大)。若傳入的對象,不支持比較將報錯( ClassCastException)。不允許null。
底層使用的是基於數組的平衡二叉樹堆實現(它的優先級的實現)。
公共方法使用單鎖ReetrantLock保證線程的安全性。
1.1 類結構
- PriorityBlockingQueue類圖
重要的參數
// 數組的默認大小,會自動擴容的
private static final int DEFAULT_INITIAL_CAPACITY = 11;
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
// 為啥是減8,一些虛擬機會在數組中保留一些header words(頭字), 應該學到jvm時,就知道了
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private transient Object[] queue;
...
// 如果是空的話,優先級隊列就使用元素的自然順序(從小到大)
private transient Comparator<? super E> comparator;
保證線程安全的措施
/**
* Lock used for all public operations
*/
private final ReentrantLock lock;
/**
* Condition for blocking when empty
*/
// 為啥沒有notFull,因為該隊列是無界的
private final Condition notEmpty;
/**
* Spinlock for allocation, acquired via CAS.
*/
// 為啥用CAS,而不是鎖,來控制線程安全在擴容時,后面講
private transient volatile int allocationSpinLock;
2. 源碼剖析
我們知道PriorityBlockingQueue實現了BlockingQueue,這篇博客有提到過BlockingQueue可以看一下,它定義了四種方式,對不能立即滿足條件的不同的方法,有不同的處理方式。
我們一起去看看下面幾種類型的方法的具體實現
- 入隊
- 出隊
2.1 入隊
public boolean add(E e) {
return offer(e);
}
public void put(E e) {
offer(e); // never need to block
}
// 忽略時間
public boolean offer(E e, long timeout, TimeUnit unit) {
return offer(e); // never need to block
}
上面幾個入隊方法都是去調用的offer(e),所以主要來看看這個方法的實現吧
public boolean offer(E e) {
if (e == null)
throw new NullPointerException();
final ReentrantLock lock = this.lock;
lock.lock();
int n, cap;
Object[] array;
// 直到擴容成功或溢出為止
while ((n = size) >= (cap = (array = queue).length))
tryGrow(array, cap);
try {
Comparator<? super E> cmp = comparator;
if (cmp == null)
// 二叉堆的插入算法,在后面講
siftUpComparable(n, e, array);
else
siftUpUsingComparator(n, e, array, cmp);
size = n + 1;
notEmpty.signal();
} finally {
lock.unlock();
}
return true;
}
總體步驟很簡單,查看是否需要擴容,然后再插入元素到二叉堆里。我們看看擴容的實現
- 擴容
容量小於64,oldCap + (oldCap + 2); 否則oldCap + (oldCap * 0.5)
private void tryGrow(Object[] array, int oldCap) {
lock.unlock(); // must release and then re-acquire main lock
Object[] newArray = null;
// allocationSpinLock默認是0,表示此時沒有線程在擴容
if (allocationSpinLock == 0 &&
UNSAFE.compareAndSwapInt(this, allocationSpinLockOffset,
0, 1)) {
try {
int newCap = oldCap + ((oldCap < 64) ?
(oldCap + 2) : // grow faster if small
(oldCap >> 1));
// 檢查是否溢出
if (newCap - MAX_ARRAY_SIZE > 0) { // possible overflow
int minCap = oldCap + 1;
if (minCap < 0 || minCap > MAX_ARRAY_SIZE)
throw new OutOfMemoryError();
newCap = MAX_ARRAY_SIZE;
}
if (newCap > oldCap && queue == array)
newArray = new Object[newCap];
} finally {
allocationSpinLock = 0;
}
}
// 此時,另一個線程正在擴容;讓出自己的CPU時間片,下次再去搶占CPU時間片
if (newArray == null) // back off if another thread is allocating
Thread.yield();
// 重新獲取鎖
lock.lock();
// newArray已經被初始化了
// 如果queue != array, queue已經被改變了;有兩種可能:
// 1. 已經有元素被出隊了
// 2. 已經有元素入隊了,此時入隊的線程肯定擴容成功了(在沒有其他元素出隊的情況下)
if (newArray != null && queue == array) {
queue = newArray;
System.arraycopy(array, 0, newArray, 0, oldCap);
}
}
為什么擴容時,會解鎖,並通過CAS去進行新容量的計算?
However, allocation during resizing uses a simple spinlock (used only while not holding main lock) in order to allow takes to operate concurrently with allocation.This avoids repeated postponement of waiting consumers and consequent element build-up.
上面的話,大致意思就是,擴容時使用自旋鎖而不是lock,為了在擴容時,也可以執行出隊操作(上面的代碼中,擴容比較耗費時間)。避免讓阻塞的消費者被反復阻塞(被喚醒后,不滿足條件,又被阻塞,反復)。
Doug Lea 👍👍
2.2 出隊
只講poll()的實現;take()與poll(long timeout, TimeUnit unit)的實現都差不多
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return dequeue();
} finally {
lock.unlock();
}
}
我們先看二叉堆的插入方法siftUpComparable,再看dequeue。
// k = size x為插入的元素
private static <T> void siftUpComparable(int k, T x, Object[] array) {
Comparable<? super T> key = (Comparable<? super T>) x;
while (k > 0) {
int parent = (k - 1) >>> 1; // (k -1) / 2
Object e = array[parent];
if (key.compareTo((T) e) >= 0)
break;
array[k] = e;
k = parent;
}
array[k] = key;
}
這個二叉堆是小根堆(任何一個結點的左右子節點的值都大於自己)
- 堆初始化
此時,我們執行offer(4)。按照上面的源碼,我們最后得到
- offer(4)
整個堆插入的思路: 欲插入的元素是否比其父結點小,則與父結點互相交換(小根堆)
我們再執行poll() -> dequeue()
返回頭部元素,然后重新調整堆元素位置
/**
* Mechanics for poll(). Call only while holding lock.
*/
private E dequeue() {
int n = size - 1;
if (n < 0)
return null;
else {
Object[] array = queue;
// 獲取第一個值
E result = (E) array[0];
// 保存末尾的值,並置空
E x = (E) array[n];
array[n] = null;
Comparator<? super E> cmp = comparator;
if (cmp == null)
// 調整堆的位置
siftDownComparable(0, x, array, n);
else
siftDownUsingComparator(0, x, array, n, cmp);
size = n;
return result;
}
}
將 x元素插入到k位置,為了維持二叉堆的平衡,一直降級x直到它小於或等於它的子節點
private static <T> void siftDownComparable(int k, T x, Object[] array,
int n) {
if (n > 0) {
Comparable<? super T> key = (Comparable<? super T>)x;
int half = n >>> 1; // half = n / 2 // loop while a non-leaf
while (k < half) {
int child = (k << 1) + 1; // assume left child is least child = k * 2 + 1
Object c = array[child];
int right = child + 1;
if (right < n &&
((Comparable<? super T>) c).compareTo((T) array[right]) > 0)
// 左右節點誰小,誰就當父結點
c = array[child = right];
if (key.compareTo((T) c) <= 0)
break;
array[k] = c;
k = child;
}
array[k] = key;
}
}
- 進入siftDownComparable的狀態
執行完畢
堆獲取頭結點后的思路: 將最后一個節點保存起來並置空,將它插入到第一個節點,若不滿足就執行下面的流程.
- 比較第一個節點的左右節點是否小於該節點,是的話,就交換左右節點的最小的一個值的位置,周而復始。直到滿足最小堆的性質為止
3. 總結
- PriorityBlockingQueue入隊后的元素的順序是按照元素的自然順序(Comparator為null時)進行維護的。
- 使用ReetrantLock單鎖,保證線程的安全性;在擴容時,通過CAS來保證只有一個線程可以成功擴容,同時擴容時,還可以進行出隊操作
- 順序通過二叉堆維護的,默認是最小堆
4. 參考
- 深入理解Java PriorityQueue -- 對堆的算法講的很細致