1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
|
9 |
import java.util.concurrent.locks.Condition; |
10 |
import java.util.concurrent.locks.ReentrantLock; |
11 |
import java.util.AbstractQueue; |
12 |
import java.util.Arrays; |
13 |
import java.util.Collection; |
14 |
import java.util.Comparator; |
15 |
import java.util.Iterator; |
16 |
import java.util.NoSuchElementException; |
17 |
import java.util.PriorityQueue; |
18 |
import java.util.Queue; |
19 |
import java.util.SortedSet; |
20 |
import java.util.Spliterator; |
21 |
import java.util.stream.Stream; |
22 |
import java.util.stream.Streams; |
23 |
import java.util.function.Block; |
24 |
|
25 |
/** |
26 |
* An unbounded {@linkplain BlockingQueue blocking queue} that uses |
27 |
* the same ordering rules as class {@link PriorityQueue} and supplies |
28 |
* blocking retrieval operations. While this queue is logically |
29 |
* unbounded, attempted additions may fail due to resource exhaustion |
30 |
* (causing {@code OutOfMemoryError}). This class does not permit |
31 |
* {@code null} elements. A priority queue relying on {@linkplain |
32 |
* Comparable natural ordering} also does not permit insertion of |
33 |
* non-comparable objects (doing so results in |
34 |
* {@code ClassCastException}). |
35 |
* |
36 |
* <p>This class and its iterator implement all of the |
37 |
* <em>optional</em> methods of the {@link Collection} and {@link |
38 |
* Iterator} interfaces. The Iterator provided in method {@link |
39 |
* #iterator()} is <em>not</em> guaranteed to traverse the elements of |
40 |
* the PriorityBlockingQueue in any particular order. If you need |
41 |
* ordered traversal, consider using |
42 |
* {@code Arrays.sort(pq.toArray())}. Also, method {@code drainTo} |
43 |
* can be used to <em>remove</em> some or all elements in priority |
44 |
* order and place them in another collection. |
45 |
* |
46 |
* <p>Operations on this class make no guarantees about the ordering |
47 |
* of elements with equal priority. If you need to enforce an |
48 |
* ordering, you can define custom classes or comparators that use a |
49 |
* secondary key to break ties in primary priority values. For |
50 |
* example, here is a class that applies first-in-first-out |
51 |
* tie-breaking to comparable elements. To use it, you would insert a |
52 |
* {@code new FIFOEntry(anEntry)} instead of a plain entry object. |
53 |
* |
54 |
* <pre> {@code |
55 |
* class FIFOEntry<E extends Comparable<? super E>> |
56 |
* implements Comparable<FIFOEntry<E>> { |
57 |
* static final AtomicLong seq = new AtomicLong(0); |
58 |
* final long seqNum; |
59 |
* final E entry; |
60 |
* public FIFOEntry(E entry) { |
61 |
* seqNum = seq.getAndIncrement(); |
62 |
* this.entry = entry; |
63 |
* } |
64 |
* public E getEntry() { return entry; } |
65 |
* public int compareTo(FIFOEntry<E> other) { |
66 |
* int res = entry.compareTo(other.entry); |
67 |
* if (res == 0 && other.entry != this.entry) |
68 |
* res = (seqNum < other.seqNum ? -1 : 1); |
69 |
* return res; |
70 |
* } |
71 |
* }}</pre> |
72 |
* |
73 |
* <p>This class is a member of the |
74 |
* <a href="{@docRoot}/../technotes/guides/collections/index.html"> |
75 |
* Java Collections Framework</a>. |
76 |
* |
77 |
* @since 1.5 |
78 |
* @author Doug Lea |
79 |
* @param <E> the type of elements held in this collection |
80 |
*/ |
81 |
@SuppressWarnings("unchecked") |
82 |
public class PriorityBlockingQueue<E> extends AbstractQueue<E> |
83 |
implements BlockingQueue<E>, java.io.Serializable { |
84 |
private static final long serialVersionUID = 5595510919245408276L; |
85 |
|
86 |
/* |
87 |
* The implementation uses an array-based binary heap, with public |
88 |
* operations protected with a single lock. However, allocation |
89 |
* during resizing uses a simple spinlock (used only while not |
90 |
* holding main lock) in order to allow takes to operate |
91 |
* concurrently with allocation. This avoids repeated |
92 |
* postponement of waiting consumers and consequent element |
93 |
* build-up. The need to back away from lock during allocation |
94 |
* makes it impossible to simply wrap delegated |
95 |
* java.util.PriorityQueue operations within a lock, as was done |
96 |
* in a previous version of this class. To maintain |
97 |
* interoperability, a plain PriorityQueue is still used during |
98 |
* serialization, which maintains compatibility at the expense of |
99 |
* transiently doubling overhead. |
100 |
*/ |
101 |
|
102 |
/** |
103 |
* Default array capacity. |
104 |
*/ |
105 |
private static final int DEFAULT_INITIAL_CAPACITY = 11; |
106 |
|
107 |
/** |
108 |
* The maximum size of array to allocate. |
109 |
* Some VMs reserve some header words in an array. |
110 |
* Attempts to allocate larger arrays may result in |
111 |
* OutOfMemoryError: Requested array size exceeds VM limit |
112 |
*/ |
113 |
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; |
114 |
|
115 |
/** |
116 |
* Priority queue represented as a balanced binary heap: the two |
117 |
* children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The |
118 |
* priority queue is ordered by comparator, or by the elements' |
119 |
* natural ordering, if comparator is null: For each node n in the |
120 |
* heap and each descendant d of n, n <= d. The element with the |
121 |
* lowest value is in queue[0], assuming the queue is nonempty. |
122 |
*/ |
123 |
private transient Object[] queue; |
124 |
|
125 |
/** |
126 |
* The number of elements in the priority queue. |
127 |
*/ |
128 |
private transient int size; |
129 |
|
130 |
/** |
131 |
* The comparator, or null if priority queue uses elements' |
132 |
* natural ordering. |
133 |
*/ |
134 |
private transient Comparator<? super E> comparator; |
135 |
|
136 |
/** |
137 |
* Lock used for all public operations |
138 |
*/ |
139 |
private final ReentrantLock lock; |
140 |
|
141 |
/** |
142 |
* Condition for blocking when empty |
143 |
*/ |
144 |
private final Condition notEmpty; |
145 |
|
146 |
/** |
147 |
* Spinlock for allocation, acquired via CAS. |
148 |
*/ |
149 |
private transient volatile int allocationSpinLock; |
150 |
|
151 |
/** |
152 |
* A plain PriorityQueue used only for serialization, |
153 |
* to maintain compatibility with previous versions |
154 |
* of this class. Non-null only during serialization/deserialization. |
155 |
*/ |
156 |
private PriorityQueue<E> q; |
157 |
|
158 |
/** |
159 |
* Creates a {@code PriorityBlockingQueue} with the default |
160 |
* initial capacity (11) that orders its elements according to |
161 |
* their {@linkplain Comparable natural ordering}. |
162 |
*/ |
163 |
public PriorityBlockingQueue() { |
164 |
this(DEFAULT_INITIAL_CAPACITY, null); |
165 |
} |
166 |
|
167 |
/** |
168 |
* Creates a {@code PriorityBlockingQueue} with the specified |
169 |
* initial capacity that orders its elements according to their |
170 |
* {@linkplain Comparable natural ordering}. |
171 |
* |
172 |
* @param initialCapacity the initial capacity for this priority queue |
173 |
* @throws IllegalArgumentException if {@code initialCapacity} is less |
174 |
* than 1 |
175 |
*/ |
176 |
public PriorityBlockingQueue(int initialCapacity) { |
177 |
this(initialCapacity, null); |
178 |
} |
179 |
|
180 |
/** |
181 |
* Creates a {@code PriorityBlockingQueue} with the specified initial |
182 |
* capacity that orders its elements according to the specified |
183 |
* comparator. |
184 |
* |
185 |
* @param initialCapacity the initial capacity for this priority queue |
186 |
* @param comparator the comparator that will be used to order this |
187 |
* priority queue. If {@code null}, the {@linkplain Comparable |
188 |
* natural ordering} of the elements will be used. |
189 |
* @throws IllegalArgumentException if {@code initialCapacity} is less |
190 |
* than 1 |
191 |
*/ |
192 |
public PriorityBlockingQueue(int initialCapacity, |
193 |
Comparator<? super E> comparator) { |
194 |
if (initialCapacity < 1) |
195 |
throw new IllegalArgumentException(); |
196 |
this.lock = new ReentrantLock(); |
197 |
this.notEmpty = lock.newCondition(); |
198 |
this.comparator = comparator; |
199 |
this.queue = new Object[initialCapacity]; |
200 |
} |
201 |
|
202 |
/** |
203 |
* Creates a {@code PriorityBlockingQueue} containing the elements |
204 |
* in the specified collection. If the specified collection is a |
205 |
* {@link SortedSet} or a {@link PriorityQueue}, this |
206 |
* priority queue will be ordered according to the same ordering. |
207 |
* Otherwise, this priority queue will be ordered according to the |
208 |
* {@linkplain Comparable natural ordering} of its elements. |
209 |
* |
210 |
* @param c the collection whose elements are to be placed |
211 |
* into this priority queue |
212 |
* @throws ClassCastException if elements of the specified collection |
213 |
* cannot be compared to one another according to the priority |
214 |
* queue's ordering |
215 |
* @throws NullPointerException if the specified collection or any |
216 |
* of its elements are null |
217 |
*/ |
218 |
public PriorityBlockingQueue(Collection<? extends E> c) { |
219 |
this.lock = new ReentrantLock(); |
220 |
this.notEmpty = lock.newCondition(); |
221 |
boolean heapify = true; // true if not known to be in heap order |
222 |
boolean screen = true; // true if must screen for nulls |
223 |
if (c instanceof SortedSet<?>) { |
224 |
SortedSet<? extends E> ss = (SortedSet<? extends E>) c; |
225 |
this.comparator = (Comparator<? super E>) ss.comparator(); |
226 |
heapify = false; |
227 |
} |
228 |
else if (c instanceof PriorityBlockingQueue<?>) { |
229 |
PriorityBlockingQueue<? extends E> pq = |
230 |
(PriorityBlockingQueue<? extends E>) c; |
231 |
this.comparator = (Comparator<? super E>) pq.comparator(); |
232 |
screen = false; |
233 |
if (pq.getClass() == PriorityBlockingQueue.class) // exact match |
234 |
heapify = false; |
235 |
} |
236 |
Object[] a = c.toArray(); |
237 |
int n = a.length; |
238 |
// If c.toArray incorrectly doesn't return Object[], copy it. |
239 |
if (a.getClass() != Object[].class) |
240 |
a = Arrays.copyOf(a, n, Object[].class); |
241 |
if (screen && (n == 1 || this.comparator != null)) { |
242 |
for (int i = 0; i < n; ++i) |
243 |
if (a[i] == null) |
244 |
throw new NullPointerException(); |
245 |
} |
246 |
this.queue = a; |
247 |
this.size = n; |
248 |
if (heapify) |
249 |
heapify(); |
250 |
} |
251 |
|
252 |
/** |
253 |
* Tries to grow array to accommodate at least one more element |
254 |
* (but normally expand by about 50%), giving up (allowing retry) |
255 |
* on contention (which we expect to be rare). Call only while |
256 |
* holding lock. |
257 |
* |
258 |
* @param array the heap array |
259 |
* @param oldCap the length of the array |
260 |
*/ |
261 |
private void tryGrow(Object[] array, int oldCap) { |
262 |
lock.unlock(); // must release and then re-acquire main lock |
263 |
Object[] newArray = null; |
264 |
if (allocationSpinLock == 0 && |
265 |
UNSAFE.compareAndSwapInt(this, allocationSpinLockOffset, |
266 |
0, 1)) { |
267 |
try { |
268 |
int newCap = oldCap + ((oldCap < 64) ? |
269 |
(oldCap + 2) : // grow faster if small |
270 |
(oldCap >> 1)); |
271 |
if (newCap - MAX_ARRAY_SIZE > 0) { // possible overflow |
272 |
int minCap = oldCap + 1; |
273 |
if (minCap < 0 || minCap > MAX_ARRAY_SIZE) |
274 |
throw new OutOfMemoryError(); |
275 |
newCap = MAX_ARRAY_SIZE; |
276 |
} |
277 |
if (newCap > oldCap && queue == array) |
278 |
newArray = new Object[newCap]; |
279 |
} finally { |
280 |
allocationSpinLock = 0; |
281 |
} |
282 |
} |
283 |
if (newArray == null) // back off if another thread is allocating |
284 |
Thread.yield(); |
285 |
lock.lock(); |
286 |
if (newArray != null && queue == array) { |
287 |
queue = newArray; |
288 |
System.arraycopy(array, 0, newArray, 0, oldCap); |
289 |
} |
290 |
} |
291 |
|
292 |
/** |
293 |
* Mechanics for poll(). Call only while holding lock. |
294 |
*/ |
295 |
private E dequeue() { |
296 |
int n = size - 1; |
297 |
if (n < 0) |
298 |
return null; |
299 |
else { |
300 |
Object[] array = queue; |
301 |
E result = (E) array[0]; |
302 |
E x = (E) array[n]; |
303 |
array[n] = null; |
304 |
Comparator<? super E> cmp = comparator; |
305 |
if (cmp == null) |
306 |
siftDownComparable(0, x, array, n); |
307 |
else |
308 |
siftDownUsingComparator(0, x, array, n, cmp); |
309 |
size = n; |
310 |
return result; |
311 |
} |
312 |
} |
313 |
|
314 |
/** |
315 |
* Inserts item x at position k, maintaining heap invariant by |
316 |
* promoting x up the tree until it is greater than or equal to |
317 |
* its parent, or is the root. |
318 |
* |
319 |
* To simplify and speed up coercions and comparisons. the |
320 |
* Comparable and Comparator versions are separated into different |
321 |
* methods that are otherwise identical. (Similarly for siftDown.) |
322 |
* These methods are static, with heap state as arguments, to |
323 |
* simplify use in light of possible comparator exceptions. |
324 |
* |
325 |
* @param k the position to fill |
326 |
* @param x the item to insert |
327 |
* @param array the heap array |
328 |
* @param n heap size |
329 |
*/ |
330 |
private static <T> void siftUpComparable(int k, T x, Object[] array) { |
331 |
Comparable<? super T> key = (Comparable<? super T>) x; |
332 |
while (k > 0) { |
333 |
int parent = (k - 1) >>> 1; |
334 |
Object e = array[parent]; |
335 |
if (key.compareTo((T) e) >= 0) |
336 |
break; |
337 |
array[k] = e; |
338 |
k = parent; |
339 |
} |
340 |
array[k] = key; |
341 |
} |
342 |
|
343 |
private static <T> void siftUpUsingComparator(int k, T x, Object[] array, |
344 |
Comparator<? super T> cmp) { |
345 |
while (k > 0) { |
346 |
int parent = (k - 1) >>> 1; |
347 |
Object e = array[parent]; |
348 |
if (cmp.compare(x, (T) e) >= 0) |
349 |
break; |
350 |
array[k] = e; |
351 |
k = parent; |
352 |
} |
353 |
array[k] = x; |
354 |
} |
355 |
|
356 |
/** |
357 |
* Inserts item x at position k, maintaining heap invariant by |
358 |
* demoting x down the tree repeatedly until it is less than or |
359 |
* equal to its children or is a leaf. |
360 |
* |
361 |
* @param k the position to fill |
362 |
* @param x the item to insert |
363 |
* @param array the heap array |
364 |
* @param n heap size |
365 |
*/ |
366 |
private static <T> void siftDownComparable(int k, T x, Object[] array, |
367 |
int n) { |
368 |
if (n > 0) { |
369 |
Comparable<? super T> key = (Comparable<? super T>)x; |
370 |
int half = n >>> 1; // loop while a non-leaf |
371 |
while (k < half) { |
372 |
int child = (k << 1) + 1; // assume left child is least |
373 |
Object c = array[child]; |
374 |
int right = child + 1; |
375 |
if (right < n && |
376 |
((Comparable<? super T>) c).compareTo((T) array[right]) > 0) |
377 |
c = array[child = right]; |
378 |
if (key.compareTo((T) c) <= 0) |
379 |
break; |
380 |
array[k] = c; |
381 |
k = child; |
382 |
} |
383 |
array[k] = key; |
384 |
} |
385 |
} |
386 |
|
387 |
private static <T> void siftDownUsingComparator(int k, T x, Object[] array, |
388 |
int n, |
389 |
Comparator<? super T> cmp) { |
390 |
if (n > 0) { |
391 |
int half = n >>> 1; |
392 |
while (k < half) { |
393 |
int child = (k << 1) + 1; |
394 |
Object c = array[child]; |
395 |
int right = child + 1; |
396 |
if (right < n && cmp.compare((T) c, (T) array[right]) > 0) |
397 |
c = array[child = right]; |
398 |
if (cmp.compare(x, (T) c) <= 0) |
399 |
break; |
400 |
array[k] = c; |
401 |
k = child; |
402 |
} |
403 |
array[k] = x; |
404 |
} |
405 |
} |
406 |
|
407 |
/** |
408 |
* Establishes the heap invariant (described above) in the entire tree, |
409 |
* assuming nothing about the order of the elements prior to the call. |
410 |
*/ |
411 |
private void heapify() { |
412 |
Object[] array = queue; |
413 |
int n = size; |
414 |
int half = (n >>> 1) - 1; |
415 |
Comparator<? super E> cmp = comparator; |
416 |
if (cmp == null) { |
417 |
for (int i = half; i >= 0; i--) |
418 |
siftDownComparable(i, (E) array[i], array, n); |
419 |
} |
420 |
else { |
421 |
for (int i = half; i >= 0; i--) |
422 |
siftDownUsingComparator(i, (E) array[i], array, n, cmp); |
423 |
} |
424 |
} |
425 |
|
426 |
/** |
427 |
* Inserts the specified element into this priority queue. |
428 |
* |
429 |
* @param e the element to add |
430 |
* @return {@code true} (as specified by {@link Collection#add}) |
431 |
* @throws ClassCastException if the specified element cannot be compared |
432 |
* with elements currently in the priority queue according to the |
433 |
* priority queue's ordering |
434 |
* @throws NullPointerException if the specified element is null |
435 |
*/ |
436 |
public boolean add(E e) { |
437 |
return offer(e); |
438 |
} |
439 |
|
440 |
/** |
441 |
* Inserts the specified element into this priority queue. |
442 |
* As the queue is unbounded, this method will never return {@code false}. |
443 |
* |
444 |
* @param e the element to add |
445 |
* @return {@code true} (as specified by {@link Queue#offer}) |
446 |
* @throws ClassCastException if the specified element cannot be compared |
447 |
* with elements currently in the priority queue according to the |
448 |
* priority queue's ordering |
449 |
* @throws NullPointerException if the specified element is null |
450 |
*/ |
451 |
public boolean offer(E e) { |
452 |
if (e == null) |
453 |
throw new NullPointerException(); |
454 |
final ReentrantLock lock = this.lock; |
455 |
lock.lock(); |
456 |
int n, cap; |
457 |
Object[] array; |
458 |
while ((n = size) >= (cap = (array = queue).length)) |
459 |
tryGrow(array, cap); |
460 |
try { |
461 |
Comparator<? super E> cmp = comparator; |
462 |
if (cmp == null) |
463 |
siftUpComparable(n, e, array); |
464 |
else |
465 |
siftUpUsingComparator(n, e, array, cmp); |
466 |
size = n + 1; |
467 |
notEmpty.signal(); |
468 |
} finally { |
469 |
lock.unlock(); |
470 |
} |
471 |
return true; |
472 |
} |
473 |
|
474 |
/** |
475 |
* Inserts the specified element into this priority queue. |
476 |
* As the queue is unbounded, this method will never block. |
477 |
* |
478 |
* @param e the element to add |
479 |
* @throws ClassCastException if the specified element cannot be compared |
480 |
* with elements currently in the priority queue according to the |
481 |
* priority queue's ordering |
482 |
* @throws NullPointerException if the specified element is null |
483 |
*/ |
484 |
public void put(E e) { |
485 |
offer(e); // never need to block |
486 |
} |
487 |
|
488 |
/** |
489 |
* Inserts the specified element into this priority queue. |
490 |
* As the queue is unbounded, this method will never block or |
491 |
* return {@code false}. |
492 |
* |
493 |
* @param e the element to add |
494 |
* @param timeout This parameter is ignored as the method never blocks |
495 |
* @param unit This parameter is ignored as the method never blocks |
496 |
* @return {@code true} (as specified by |
497 |
* {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer}) |
498 |
* @throws ClassCastException if the specified element cannot be compared |
499 |
* with elements currently in the priority queue according to the |
500 |
* priority queue's ordering |
501 |
* @throws NullPointerException if the specified element is null |
502 |
*/ |
503 |
public boolean offer(E e, long timeout, TimeUnit unit) { |
504 |
return offer(e); // never need to block |
505 |
} |
506 |
|
507 |
public E poll() { |
508 |
final ReentrantLock lock = this.lock; |
509 |
lock.lock(); |
510 |
try { |
511 |
return dequeue(); |
512 |
} finally { |
513 |
lock.unlock(); |
514 |
} |
515 |
} |
516 |
|
517 |
public E take() throws InterruptedException { |
518 |
final ReentrantLock lock = this.lock; |
519 |
lock.lockInterruptibly(); |
520 |
E result; |
521 |
try { |
522 |
while ( (result = dequeue()) == null) |
523 |
notEmpty.await(); |
524 |
} finally { |
525 |
lock.unlock(); |
526 |
} |
527 |
return result; |
528 |
} |
529 |
|
530 |
public E poll(long timeout, TimeUnit unit) throws InterruptedException { |
531 |
long nanos = unit.toNanos(timeout); |
532 |
final ReentrantLock lock = this.lock; |
533 |
lock.lockInterruptibly(); |
534 |
E result; |
535 |
try { |
536 |
while ( (result = dequeue()) == null && nanos > 0) |
537 |
nanos = notEmpty.awaitNanos(nanos); |
538 |
} finally { |
539 |
lock.unlock(); |
540 |
} |
541 |
return result; |
542 |
} |
543 |
|
544 |
public E peek() { |
545 |
final ReentrantLock lock = this.lock; |
546 |
lock.lock(); |
547 |
try { |
548 |
return (size == 0) ? null : (E) queue[0]; |
549 |
} finally { |
550 |
lock.unlock(); |
551 |
} |
552 |
} |
553 |
|
554 |
/** |
555 |
* Returns the comparator used to order the elements in this queue, |
556 |
* or {@code null} if this queue uses the {@linkplain Comparable |
557 |
* natural ordering} of its elements. |
558 |
* |
559 |
* @return the comparator used to order the elements in this queue, |
560 |
* or {@code null} if this queue uses the natural |
561 |
* ordering of its elements |
562 |
*/ |
563 |
public Comparator<? super E> comparator() { |
564 |
return comparator; |
565 |
} |
566 |
|
567 |
public int size() { |
568 |
final ReentrantLock lock = this.lock; |
569 |
lock.lock(); |
570 |
try { |
571 |
return size; |
572 |
} finally { |
573 |
lock.unlock(); |
574 |
} |
575 |
} |
576 |
|
577 |
/** |
578 |
* Always returns {@code Integer.MAX_VALUE} because |
579 |
* a {@code PriorityBlockingQueue} is not capacity constrained. |
580 |
* @return {@code Integer.MAX_VALUE} always |
581 |
*/ |
582 |
public int remainingCapacity() { |
583 |
return Integer.MAX_VALUE; |
584 |
} |
585 |
|
586 |
private int indexOf(Object o) { |
587 |
if (o != null) { |
588 |
Object[] array = queue; |
589 |
int n = size; |
590 |
for (int i = 0; i < n; i++) |
591 |
if (o.equals(array[i])) |
592 |
return i; |
593 |
} |
594 |
return -1; |
595 |
} |
596 |
|
597 |
/** |
598 |
* Removes the ith element from queue. |
599 |
*/ |
600 |
private void removeAt(int i) { |
601 |
Object[] array = queue; |
602 |
int n = size - 1; |
603 |
if (n == i) // removed last element |
604 |
array[i] = null; |
605 |
else { |
606 |
E moved = (E) array[n]; |
607 |
array[n] = null; |
608 |
Comparator<? super E> cmp = comparator; |
609 |
if (cmp == null) |
610 |
siftDownComparable(i, moved, array, n); |
611 |
else |
612 |
siftDownUsingComparator(i, moved, array, n, cmp); |
613 |
if (array[i] == moved) { |
614 |
if (cmp == null) |
615 |
siftUpComparable(i, moved, array); |
616 |
else |
617 |
siftUpUsingComparator(i, moved, array, cmp); |
618 |
} |
619 |
} |
620 |
size = n; |
621 |
} |
622 |
|
623 |
/** |
624 |
* Removes a single instance of the specified element from this queue, |
625 |
* if it is present. More formally, removes an element {@code e} such |
626 |
* that {@code o.equals(e)}, if this queue contains one or more such |
627 |
* elements. Returns {@code true} if and only if this queue contained |
628 |
* the specified element (or equivalently, if this queue changed as a |
629 |
* result of the call). |
630 |
* |
631 |
* @param o element to be removed from this queue, if present |
632 |
* @return {@code true} if this queue changed as a result of the call |
633 |
*/ |
634 |
public boolean remove(Object o) { |
635 |
final ReentrantLock lock = this.lock; |
636 |
lock.lock(); |
637 |
try { |
638 |
int i = indexOf(o); |
639 |
if (i == -1) |
640 |
return false; |
641 |
removeAt(i); |
642 |
return true; |
643 |
} finally { |
644 |
lock.unlock(); |
645 |
} |
646 |
} |
647 |
|
648 |
/** |
649 |
* Identity-based version for use in Itr.remove |
650 |
*/ |
651 |
void removeEQ(Object o) { |
652 |
final ReentrantLock lock = this.lock; |
653 |
lock.lock(); |
654 |
try { |
655 |
Object[] array = queue; |
656 |
for (int i = 0, n = size; i < n; i++) { |
657 |
if (o == array[i]) { |
658 |
removeAt(i); |
659 |
break; |
660 |
} |
661 |
} |
662 |
} finally { |
663 |
lock.unlock(); |
664 |
} |
665 |
} |
666 |
|
667 |
/** |
668 |
* Returns {@code true} if this queue contains the specified element. |
669 |
* More formally, returns {@code true} if and only if this queue contains |
670 |
* at least one element {@code e} such that {@code o.equals(e)}. |
671 |
* |
672 |
* @param o object to be checked for containment in this queue |
673 |
* @return {@code true} if this queue contains the specified element |
674 |
*/ |
675 |
public boolean contains(Object o) { |
676 |
final ReentrantLock lock = this.lock; |
677 |
lock.lock(); |
678 |
try { |
679 |
return indexOf(o) != -1; |
680 |
} finally { |
681 |
lock.unlock(); |
682 |
} |
683 |
} |
684 |
|
685 |
/** |
686 |
* Returns an array containing all of the elements in this queue. |
687 |
* The returned array elements are in no particular order. |
688 |
* |
689 |
* <p>The returned array will be "safe" in that no references to it are |
690 |
* maintained by this queue. (In other words, this method must allocate |
691 |
* a new array). The caller is thus free to modify the returned array. |
692 |
* |
693 |
* <p>This method acts as bridge between array-based and collection-based |
694 |
* APIs. |
695 |
* |
696 |
* @return an array containing all of the elements in this queue |
697 |
*/ |
698 |
public Object[] toArray() { |
699 |
final ReentrantLock lock = this.lock; |
700 |
lock.lock(); |
701 |
try { |
702 |
return Arrays.copyOf(queue, size); |
703 |
} finally { |
704 |
lock.unlock(); |
705 |
} |
706 |
} |
707 |
|
708 |
public String toString() { |
709 |
final ReentrantLock lock = this.lock; |
710 |
lock.lock(); |
711 |
try { |
712 |
int n = size; |
713 |
if (n == 0) |
714 |
return "[]"; |
715 |
StringBuilder sb = new StringBuilder(); |
716 |
sb.append('['); |
717 |
for (int i = 0; i < n; ++i) { |
718 |
Object e = queue[i]; |
719 |
sb.append(e == this ? "(this Collection)" : e); |
720 |
if (i != n - 1) |
721 |
sb.append(',').append(' '); |
722 |
} |
723 |
return sb.append(']').toString(); |
724 |
} finally { |
725 |
lock.unlock(); |
726 |
} |
727 |
} |
728 |
|
729 |
/** |
730 |
* @throws UnsupportedOperationException {@inheritDoc} |
731 |
* @throws ClassCastException {@inheritDoc} |
732 |
* @throws NullPointerException {@inheritDoc} |
733 |
* @throws IllegalArgumentException {@inheritDoc} |
734 |
*/ |
735 |
public int drainTo(Collection<? super E> c) { |
736 |
return drainTo(c, Integer.MAX_VALUE); |
737 |
} |
738 |
|
739 |
/** |
740 |
* @throws UnsupportedOperationException {@inheritDoc} |
741 |
* @throws ClassCastException {@inheritDoc} |
742 |
* @throws NullPointerException {@inheritDoc} |
743 |
* @throws IllegalArgumentException {@inheritDoc} |
744 |
*/ |
745 |
public int drainTo(Collection<? super E> c, int maxElements) { |
746 |
if (c == null) |
747 |
throw new NullPointerException(); |
748 |
if (c == this) |
749 |
throw new IllegalArgumentException(); |
750 |
if (maxElements <= 0) |
751 |
return 0; |
752 |
final ReentrantLock lock = this.lock; |
753 |
lock.lock(); |
754 |
try { |
755 |
int n = Math.min(size, maxElements); |
756 |
for (int i = 0; i < n; i++) { |
757 |
c.add((E) queue[0]); // In this order, in case add() throws. |
758 |
dequeue(); |
759 |
} |
760 |
return n; |
761 |
} finally { |
762 |
lock.unlock(); |
763 |
} |
764 |
} |
765 |
|
766 |
/** |
767 |
* Atomically removes all of the elements from this queue. |
768 |
* The queue will be empty after this call returns. |
769 |
*/ |
770 |
public void clear() { |
771 |
final ReentrantLock lock = this.lock; |
772 |
lock.lock(); |
773 |
try { |
774 |
Object[] array = queue; |
775 |
int n = size; |
776 |
size = 0; |
777 |
for (int i = 0; i < n; i++) |
778 |
array[i] = null; |
779 |
} finally { |
780 |
lock.unlock(); |
781 |
} |
782 |
} |
783 |
|
784 |
/** |
785 |
* Returns an array containing all of the elements in this queue; the |
786 |
* runtime type of the returned array is that of the specified array. |
787 |
* The returned array elements are in no particular order. |
788 |
* If the queue fits in the specified array, it is returned therein. |
789 |
* Otherwise, a new array is allocated with the runtime type of the |
790 |
* specified array and the size of this queue. |
791 |
* |
792 |
* <p>If this queue fits in the specified array with room to spare |
793 |
* (i.e., the array has more elements than this queue), the element in |
794 |
* the array immediately following the end of the queue is set to |
795 |
* {@code null}. |
796 |
* |
797 |
* <p>Like the {@link #toArray()} method, this method acts as bridge between |
798 |
* array-based and collection-based APIs. Further, this method allows |
799 |
* precise control over the runtime type of the output array, and may, |
800 |
* under certain circumstances, be used to save allocation costs. |
801 |
* |
802 |
* <p>Suppose {@code x} is a queue known to contain only strings. |
803 |
* The following code can be used to dump the queue into a newly |
804 |
* allocated array of {@code String}: |
805 |
* |
806 |
* <pre> {@code String[] y = x.toArray(new String[0]);}</pre> |
807 |
* |
808 |
* Note that {@code toArray(new Object[0])} is identical in function to |
809 |
* {@code toArray()}. |
810 |
* |
811 |
* @param a the array into which the elements of the queue are to |
812 |
* be stored, if it is big enough; otherwise, a new array of the |
813 |
* same runtime type is allocated for this purpose |
814 |
* @return an array containing all of the elements in this queue |
815 |
* @throws ArrayStoreException if the runtime type of the specified array |
816 |
* is not a supertype of the runtime type of every element in |
817 |
* this queue |
818 |
* @throws NullPointerException if the specified array is null |
819 |
*/ |
820 |
public <T> T[] toArray(T[] a) { |
821 |
final ReentrantLock lock = this.lock; |
822 |
lock.lock(); |
823 |
try { |
824 |
int n = size; |
825 |
if (a.length < n) |
826 |
// Make a new array of a's runtime type, but my contents: |
827 |
return (T[]) Arrays.copyOf(queue, size, a.getClass()); |
828 |
System.arraycopy(queue, 0, a, 0, n); |
829 |
if (a.length > n) |
830 |
a[n] = null; |
831 |
return a; |
832 |
} finally { |
833 |
lock.unlock(); |
834 |
} |
835 |
} |
836 |
|
837 |
/** |
838 |
* Returns an iterator over the elements in this queue. The |
839 |
* iterator does not return the elements in any particular order. |
840 |
* |
841 |
* <p>The returned iterator is a "weakly consistent" iterator that |
842 |
* will never throw {@link java.util.ConcurrentModificationException |
843 |
* ConcurrentModificationException}, and guarantees to traverse |
844 |
* elements as they existed upon construction of the iterator, and |
845 |
* may (but is not guaranteed to) reflect any modifications |
846 |
* subsequent to construction. |
847 |
* |
848 |
* @return an iterator over the elements in this queue |
849 |
*/ |
850 |
public Iterator<E> iterator() { |
851 |
return new Itr(toArray()); |
852 |
} |
853 |
|
854 |
/** |
855 |
* Snapshot iterator that works off copy of underlying q array. |
856 |
*/ |
857 |
final class Itr implements Iterator<E> { |
858 |
final Object[] array; // Array of all elements |
859 |
int cursor; // index of next element to return |
860 |
int lastRet; // index of last element, or -1 if no such |
861 |
|
862 |
Itr(Object[] array) { |
863 |
lastRet = -1; |
864 |
this.array = array; |
865 |
} |
866 |
|
867 |
public boolean hasNext() { |
868 |
return cursor < array.length; |
869 |
} |
870 |
|
871 |
public E next() { |
872 |
if (cursor >= array.length) |
873 |
throw new NoSuchElementException(); |
874 |
lastRet = cursor; |
875 |
return (E)array[cursor++]; |
876 |
} |
877 |
|
878 |
public void remove() { |
879 |
if (lastRet < 0) |
880 |
throw new IllegalStateException(); |
881 |
removeEQ(array[lastRet]); |
882 |
lastRet = -1; |
883 |
} |
884 |
} |
885 |
|
886 |
/** |
887 |
* Saves this queue to a stream (that is, serializes it). |
888 |
* |
889 |
* For compatibility with previous version of this class, elements |
890 |
* are first copied to a java.util.PriorityQueue, which is then |
891 |
* serialized. |
892 |
*/ |
893 |
private void writeObject(java.io.ObjectOutputStream s) |
894 |
throws java.io.IOException { |
895 |
lock.lock(); |
896 |
try { |
897 |
// avoid zero capacity argument |
898 |
q = new PriorityQueue<E>(Math.max(size, 1), comparator); |
899 |
q.addAll(this); |
900 |
s.defaultWriteObject(); |
901 |
} finally { |
902 |
q = null; |
903 |
lock.unlock(); |
904 |
} |
905 |
} |
906 |
|
907 |
/** |
908 |
* Reconstitutes this queue from a stream (that is, deserializes it). |
909 |
*/ |
910 |
private void readObject(java.io.ObjectInputStream s) |
911 |
throws java.io.IOException, ClassNotFoundException { |
912 |
try { |
913 |
s.defaultReadObject(); |
914 |
this.queue = new Object[q.size()]; |
915 |
comparator = q.comparator(); |
916 |
addAll(q); |
917 |
} finally { |
918 |
q = null; |
919 |
} |
920 |
} |
921 |
|
922 |
// wrapping constructor in method avoids transient javac problems |
923 |
final PBQSpliterator<E> spliterator() { |
924 |
Object[] a = toArray(); |
925 |
return new PBQSpliterator(a, 0, a.length); |
926 |
} |
927 |
|
928 |
public Stream<E> stream() { |
929 |
int flags = Streams.STREAM_IS_SIZED; |
930 |
return Streams.stream |
931 |
(() -> spliterator(), flags); |
932 |
} |
933 |
public Stream<E> parallelStream() { |
934 |
int flags = Streams.STREAM_IS_SIZED; |
935 |
return Streams.parallelStream |
936 |
(() -> spliterator(), flags); |
937 |
} |
938 |
|
939 |
/** Index-based split-by-two Spliterator */ |
940 |
static final class PBQSpliterator<E> implements Spliterator<E>, Iterator<E> { |
941 |
private final Object[] array; |
942 |
private int index; // current index, modified on advance/split |
943 |
private final int fence; // one past last index |
944 |
|
945 |
/** Create new spliterator covering the given array and range */ |
946 |
PBQSpliterator(Object[] array, int origin, int fence) { |
947 |
this.array = array; this.index = origin; this.fence = fence; |
948 |
} |
949 |
|
950 |
public PBQSpliterator<E> trySplit() { |
951 |
int lo = index, mid = (lo + fence) >>> 1; |
952 |
return (lo >= mid)? null : |
953 |
new PBQSpliterator<E>(array, lo, index = mid); |
954 |
} |
955 |
|
956 |
public void forEach(Block<? super E> block) { |
957 |
Object[] a; int i, hi; // hoist accesses and checks from loop |
958 |
if (block == null) |
959 |
throw new NullPointerException(); |
960 |
if ((a = array).length >= (hi = fence) && |
961 |
(i = index) >= 0 && i < hi) { |
962 |
index = hi; |
963 |
do { |
964 |
@SuppressWarnings("unchecked") E e = (E) a[i]; |
965 |
block.accept(e); |
966 |
} while (++i < hi); |
967 |
} |
968 |
} |
969 |
|
970 |
public boolean tryAdvance(Block<? super E> block) { |
971 |
if (index >= 0 && index < fence) { |
972 |
@SuppressWarnings("unchecked") E e = (E) array[index++]; |
973 |
block.accept(e); |
974 |
return true; |
975 |
} |
976 |
return false; |
977 |
} |
978 |
|
979 |
public long estimateSize() { return (long)(fence - index); } |
980 |
public boolean hasExactSize() { return true; } |
981 |
public boolean hasExactSplits() { return true; } |
982 |
|
983 |
// Iterator support |
984 |
public Iterator<E> iterator() { return this; } |
985 |
public void remove() { throw new UnsupportedOperationException(); } |
986 |
public boolean hasNext() { return index >= 0 && index < fence; } |
987 |
|
988 |
public E next() { |
989 |
if (index < 0 || index >= fence) |
990 |
throw new NoSuchElementException(); |
991 |
@SuppressWarnings("unchecked") E e = (E) array[index++]; |
992 |
return e; |
993 |
} |
994 |
} |
995 |
|
996 |
// Unsafe mechanics |
997 |
private static final sun.misc.Unsafe UNSAFE; |
998 |
private static final long allocationSpinLockOffset; |
999 |
static { |
1000 |
try { |
1001 |
UNSAFE = sun.misc.Unsafe.getUnsafe(); |
1002 |
Class<?> k = PriorityBlockingQueue.class; |
1003 |
allocationSpinLockOffset = UNSAFE.objectFieldOffset |
1004 |
(k.getDeclaredField("allocationSpinLock")); |
1005 |
} catch (Exception e) { |
1006 |
throw new Error(e); |
1007 |
} |
1008 |
} |
1009 |
} |