本文講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 -- 對堆的演算法講的很細緻