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