PriorityBlockingQueue
PriorityQueue 的線程安全版,建議先閱讀 PriorityQueue
初始化
初始容量 11,因此,如果能預估元素個數,最好能設置元素個數,避免元素拷貝
支持從 Collection,SortedSet,PriorityBlockingQueue 等初始化
容量擴展
- 如果容量小於 64,每次擴容爲 2 * capacity + 2
- 如果容量大於等於 64,每次擴容爲 capacity + 0.5 * capacity
- 使用 CAS 保證對線程情況下,只有一個線程進行擴容
private void tryGrow(Object[] array, int oldCap) {
// 1. 擴容前釋放鎖,
lock.unlock(); // must release and then re-acquire main lock
Object[] newArray = null;
// 2. 多個線程同時調用到這裏,只有一個線程在這裏條件是成立的
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;
}
}
// 3. 其他線程進入 yield
if (newArray == null) // back off if another thread is allocating
Thread.yield();
// 4. 成功的線程拿到了鎖,並且將 queue 指向新的地址,這裏必須加鎖。
lock.lock();
if (newArray != null && queue == array) {
queue = newArray;
System.arraycopy(array, 0, newArray, 0, oldCap);
}
}
- 先釋放鎖,原因是擴容過程的時間比較長,其他線程都會阻塞在 peek,offer,poll 等操作,而擴容期間如果釋放了鎖,那麼其他線程的其他操作就不會阻塞
- 用 CAS 操作減少了線程間同步消耗
- Thread.yield 的目的是其他線程在調用 offer 的時候,儘量讓出 CPU,這樣正在執行擴容的線程才容易拿到鎖。爲什麼這樣?逆向思考,如果沒有 Thread.yield,由於調用的地方是 while 循環(自旋鎖),當多個線程執行 offer 的時候,其他線程會進行大量的 lock.lock() 和 lock.unlock() 循環,增加 CPU 的消耗,加劇了鎖的競爭。而且真正執行擴容線程,拿到鎖的難度加大。
- 在 queue 指向新數組的時候必須重新獲取鎖,原因是這個時候其他線程不能再對該數組進行操作,否則會有線程安全問題
實現原理
父子節點
- 父節點總是小於等於孩子節點
- 同一層孩子節點間的大小無需維護
parent = (k - 1) >>> 1
left_child = (k << 1) + 1
right_child = (k << 1) + 2
siftUp
調整的過程爲:從 k 指定的位置開始,將 x 逐層與當前點的 parent 進行比較並交換,直到滿足x >= queue[parent] 爲止。
算法複雜度:Log(N)
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;
Object e = array[parent];
if (key.compareTo((T) e) >= 0)
break;
array[k] = e;
k = parent;
}
array[k] = key;
}
private static <T> void siftUpUsingComparator(int k, T x, Object[] array,
Comparator<? super T> cmp) {
while (k > 0) {
int parent = (k - 1) >>> 1;
Object e = array[parent];
if (cmp.compare(x, (T) e) >= 0)
break;
array[k] = e;
k = parent;
}
array[k] = x;
}
siftDown
調整的過程爲:從 k 指定的位置開始,將 x 逐層向下與當前點的左右孩子中較小的那個交換,直到 x 小於或等於左右孩子中的任何一個爲止。
算法複雜度:Log(N)
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; // loop while a non-leaf
while (k < half) {
int child = (k << 1) + 1; // assume left child is least
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;
}
}
private static <T> void siftDownUsingComparator(int k, T x, Object[] array,
int n,
Comparator<? super T> cmp) {
if (n > 0) {
int half = n >>> 1;
while (k < half) {
int child = (k << 1) + 1;
Object c = array[child];
int right = child + 1;
if (right < n && cmp.compare((T) c, (T) array[right]) > 0)
c = array[child = right];
if (cmp.compare(x, (T) c) <= 0)
break;
array[k] = c;
k = child;
}
array[k] = x;
}
}
heapify
以非葉子節點從下到上建立堆
private void heapify() {
Object[] array = queue;
int n = size;
int half = (n >>> 1) - 1;
Comparator<? super E> cmp = comparator;
if (cmp == null) {
for (int i = half; i >= 0; i--)
siftDownComparable(i, (E) array[i], array, n);
}
else {
for (int i = half; i >= 0; i--)
siftDownUsingComparator(i, (E) array[i], array, n, cmp);
}
}
offer
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;
}
private void tryGrow(Object[] array, int oldCap) {
// 1. 擴容前釋放鎖,
lock.unlock(); // must release and then re-acquire main lock
Object[] newArray = null;
// 2. 多個線程同時調用到這裏,只有一個線程在這裏條件是成立的
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;
}
}
// 3. 其他線程進入 yield
if (newArray == null) // back off if another thread is allocating
Thread.yield();
// 4. 成功的線程拿到了鎖,並且將 queue 指向新的地址,這裏必須加鎖。
lock.lock();
if (newArray != null && queue == array) {
queue = newArray;
System.arraycopy(array, 0, newArray, 0, oldCap);
}
}
這裏想象一種情景,假設有 n 線程同時調用 offer
-
如果當前數組容量夠,那麼,理解了 siftUp,實現很簡單。
-
如果當前數組容量不夠,那麼,其他 x 線程拿到了鎖,其他線程阻塞。當 x 進行擴容前,釋放了鎖,那麼,又有 y 線程可以獲取到鎖,在 x 在原子操作的地方對 allocationSpinLock 進行了設置,y 進來的時候,if 條件判斷失敗,於是 y 線程 yield,即使 y 被再次調度,while 循環的原因,其還是會再次 yield。當 y 線程yield且x 在擴容期間,如果有其他線程等待,那麼,也會進入 tryGrow 方法,如果 x 線程擴容時間足夠成,那麼 n 個線程都可能進入 tryGrow,並且 yield。 當 x 線程擴容完成後,又重新拿到鎖,由於其他線程很可能在 yield,x 很容易地拿到了鎖,完成擴容,並將元素加入隊列,並釋放鎖。而 y 等其他線程被再次調度的時候,依次重新獲取鎖,此時,while 循環條件已經不成立,將元素加入了隊列並釋放鎖。
poll
如果掌握了 siftDown 操作,那麼理解起來就非常容易了。
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;
}
}
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return dequeue();
} finally {
lock.unlock();
}
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
// 會響應中斷信號
lock.lockInterruptibly();
E result;
try {
// 避免虛假喚醒
while ( (result = dequeue()) == null)
// 一直等待,直到其他線程調用 offer 喚醒該操作
notEmpty.await();
} finally {
lock.unlock();
}
return result;
}
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
// 會響應中斷信號
lock.lockInterruptibly();
E result;
try {
// 避免虛假喚醒
while ( (result = dequeue()) == null && nanos > 0)
// 等待 nanos 納秒或其他線程調用 offer 會喚醒該操作
nanos = notEmpty.awaitNanos(nanos);
} finally {
lock.unlock();
}
return result;
}
remove
public boolean remove(Object o) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
int i = indexOf(o);
if (i == -1)
return false;
removeAt(i);
return true;
} finally {
lock.unlock();
}
}
private int indexOf(Object o) {
if (o != null) {
Object[] array = queue;
int n = size;
for (int i = 0; i < n; i++)
if (o.equals(array[i]))
return i;
}
return -1;
}
/**
* Removes the ith element from queue.
*/
private void removeAt(int i) {
Object[] array = queue;
int n = size - 1;
if (n == i) // removed last element
array[i] = null;
else {
E moved = (E) array[n];
array[n] = null;
Comparator<? super E> cmp = comparator;
if (cmp == null)
// moved 加入 i,確保 i 的子元素是有序的
siftDownComparable(i, moved, array, n);
else
siftDownUsingComparator(i, moved, array, n, cmp);
// 如果子元素已經是有序的,確保 i 的父元素是有序的
if (array[i] == moved) {
if (cmp == null)
siftUpComparable(i, moved, array);
else
siftUpUsingComparator(i, moved, array, cmp);
}
}
size = n;
}
總結
- 擴容對性能的影響。如果能夠預估大小,最好初始化指定容量。
- 對於寫多線程的代碼有很多可以參考的思路
- PriorityQueue 的線程安全版