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 |
*/ |
329 |
private static <T> void siftUpComparable(int k, T x, Object[] array) { |
330 |
Comparable<? super T> key = (Comparable<? super T>) x; |
331 |
while (k > 0) { |
332 |
int parent = (k - 1) >>> 1; |
333 |
Object e = array[parent]; |
334 |
if (key.compareTo((T) e) >= 0) |
335 |
break; |
336 |
array[k] = e; |
337 |
k = parent; |
338 |
} |
339 |
array[k] = key; |
340 |
} |
341 |
|
342 |
private static <T> void siftUpUsingComparator(int k, T x, Object[] array, |
343 |
Comparator<? super T> cmp) { |
344 |
while (k > 0) { |
345 |
int parent = (k - 1) >>> 1; |
346 |
Object e = array[parent]; |
347 |
if (cmp.compare(x, (T) e) >= 0) |
348 |
break; |
349 |
array[k] = e; |
350 |
k = parent; |
351 |
} |
352 |
array[k] = x; |
353 |
} |
354 |
|
355 |
/** |
356 |
* Inserts item x at position k, maintaining heap invariant by |
357 |
* demoting x down the tree repeatedly until it is less than or |
358 |
* equal to its children or is a leaf. |
359 |
* |
360 |
* @param k the position to fill |
361 |
* @param x the item to insert |
362 |
* @param array the heap array |
363 |
* @param n heap size |
364 |
*/ |
365 |
private static <T> void siftDownComparable(int k, T x, Object[] array, |
366 |
int n) { |
367 |
if (n > 0) { |
368 |
Comparable<? super T> key = (Comparable<? super T>)x; |
369 |
int half = n >>> 1; // loop while a non-leaf |
370 |
while (k < half) { |
371 |
int child = (k << 1) + 1; // assume left child is least |
372 |
Object c = array[child]; |
373 |
int right = child + 1; |
374 |
if (right < n && |
375 |
((Comparable<? super T>) c).compareTo((T) array[right]) > 0) |
376 |
c = array[child = right]; |
377 |
if (key.compareTo((T) c) <= 0) |
378 |
break; |
379 |
array[k] = c; |
380 |
k = child; |
381 |
} |
382 |
array[k] = key; |
383 |
} |
384 |
} |
385 |
|
386 |
private static <T> void siftDownUsingComparator(int k, T x, Object[] array, |
387 |
int n, |
388 |
Comparator<? super T> cmp) { |
389 |
if (n > 0) { |
390 |
int half = n >>> 1; |
391 |
while (k < half) { |
392 |
int child = (k << 1) + 1; |
393 |
Object c = array[child]; |
394 |
int right = child + 1; |
395 |
if (right < n && cmp.compare((T) c, (T) array[right]) > 0) |
396 |
c = array[child = right]; |
397 |
if (cmp.compare(x, (T) c) <= 0) |
398 |
break; |
399 |
array[k] = c; |
400 |
k = child; |
401 |
} |
402 |
array[k] = x; |
403 |
} |
404 |
} |
405 |
|
406 |
/** |
407 |
* Establishes the heap invariant (described above) in the entire tree, |
408 |
* assuming nothing about the order of the elements prior to the call. |
409 |
*/ |
410 |
private void heapify() { |
411 |
Object[] array = queue; |
412 |
int n = size; |
413 |
int half = (n >>> 1) - 1; |
414 |
Comparator<? super E> cmp = comparator; |
415 |
if (cmp == null) { |
416 |
for (int i = half; i >= 0; i--) |
417 |
siftDownComparable(i, (E) array[i], array, n); |
418 |
} |
419 |
else { |
420 |
for (int i = half; i >= 0; i--) |
421 |
siftDownUsingComparator(i, (E) array[i], array, n, cmp); |
422 |
} |
423 |
} |
424 |
|
425 |
/** |
426 |
* Inserts the specified element into this priority queue. |
427 |
* |
428 |
* @param e the element to add |
429 |
* @return {@code true} (as specified by {@link Collection#add}) |
430 |
* @throws ClassCastException if the specified element cannot be compared |
431 |
* with elements currently in the priority queue according to the |
432 |
* priority queue's ordering |
433 |
* @throws NullPointerException if the specified element is null |
434 |
*/ |
435 |
public boolean add(E e) { |
436 |
return offer(e); |
437 |
} |
438 |
|
439 |
/** |
440 |
* Inserts the specified element into this priority queue. |
441 |
* As the queue is unbounded, this method will never return {@code false}. |
442 |
* |
443 |
* @param e the element to add |
444 |
* @return {@code true} (as specified by {@link Queue#offer}) |
445 |
* @throws ClassCastException if the specified element cannot be compared |
446 |
* with elements currently in the priority queue according to the |
447 |
* priority queue's ordering |
448 |
* @throws NullPointerException if the specified element is null |
449 |
*/ |
450 |
public boolean offer(E e) { |
451 |
if (e == null) |
452 |
throw new NullPointerException(); |
453 |
final ReentrantLock lock = this.lock; |
454 |
lock.lock(); |
455 |
int n, cap; |
456 |
Object[] array; |
457 |
while ((n = size) >= (cap = (array = queue).length)) |
458 |
tryGrow(array, cap); |
459 |
try { |
460 |
Comparator<? super E> cmp = comparator; |
461 |
if (cmp == null) |
462 |
siftUpComparable(n, e, array); |
463 |
else |
464 |
siftUpUsingComparator(n, e, array, cmp); |
465 |
size = n + 1; |
466 |
notEmpty.signal(); |
467 |
} finally { |
468 |
lock.unlock(); |
469 |
} |
470 |
return true; |
471 |
} |
472 |
|
473 |
/** |
474 |
* Inserts the specified element into this priority queue. |
475 |
* As the queue is unbounded, this method will never block. |
476 |
* |
477 |
* @param e the element to add |
478 |
* @throws ClassCastException if the specified element cannot be compared |
479 |
* with elements currently in the priority queue according to the |
480 |
* priority queue's ordering |
481 |
* @throws NullPointerException if the specified element is null |
482 |
*/ |
483 |
public void put(E e) { |
484 |
offer(e); // never need to block |
485 |
} |
486 |
|
487 |
/** |
488 |
* Inserts the specified element into this priority queue. |
489 |
* As the queue is unbounded, this method will never block or |
490 |
* return {@code false}. |
491 |
* |
492 |
* @param e the element to add |
493 |
* @param timeout This parameter is ignored as the method never blocks |
494 |
* @param unit This parameter is ignored as the method never blocks |
495 |
* @return {@code true} (as specified by |
496 |
* {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer}) |
497 |
* @throws ClassCastException if the specified element cannot be compared |
498 |
* with elements currently in the priority queue according to the |
499 |
* priority queue's ordering |
500 |
* @throws NullPointerException if the specified element is null |
501 |
*/ |
502 |
public boolean offer(E e, long timeout, TimeUnit unit) { |
503 |
return offer(e); // never need to block |
504 |
} |
505 |
|
506 |
public E poll() { |
507 |
final ReentrantLock lock = this.lock; |
508 |
lock.lock(); |
509 |
try { |
510 |
return dequeue(); |
511 |
} finally { |
512 |
lock.unlock(); |
513 |
} |
514 |
} |
515 |
|
516 |
public E take() throws InterruptedException { |
517 |
final ReentrantLock lock = this.lock; |
518 |
lock.lockInterruptibly(); |
519 |
E result; |
520 |
try { |
521 |
while ( (result = dequeue()) == null) |
522 |
notEmpty.await(); |
523 |
} finally { |
524 |
lock.unlock(); |
525 |
} |
526 |
return result; |
527 |
} |
528 |
|
529 |
public E poll(long timeout, TimeUnit unit) throws InterruptedException { |
530 |
long nanos = unit.toNanos(timeout); |
531 |
final ReentrantLock lock = this.lock; |
532 |
lock.lockInterruptibly(); |
533 |
E result; |
534 |
try { |
535 |
while ( (result = dequeue()) == null && nanos > 0) |
536 |
nanos = notEmpty.awaitNanos(nanos); |
537 |
} finally { |
538 |
lock.unlock(); |
539 |
} |
540 |
return result; |
541 |
} |
542 |
|
543 |
public E peek() { |
544 |
final ReentrantLock lock = this.lock; |
545 |
lock.lock(); |
546 |
try { |
547 |
return (size == 0) ? null : (E) queue[0]; |
548 |
} finally { |
549 |
lock.unlock(); |
550 |
} |
551 |
} |
552 |
|
553 |
/** |
554 |
* Returns the comparator used to order the elements in this queue, |
555 |
* or {@code null} if this queue uses the {@linkplain Comparable |
556 |
* natural ordering} of its elements. |
557 |
* |
558 |
* @return the comparator used to order the elements in this queue, |
559 |
* or {@code null} if this queue uses the natural |
560 |
* ordering of its elements |
561 |
*/ |
562 |
public Comparator<? super E> comparator() { |
563 |
return comparator; |
564 |
} |
565 |
|
566 |
public int size() { |
567 |
final ReentrantLock lock = this.lock; |
568 |
lock.lock(); |
569 |
try { |
570 |
return size; |
571 |
} finally { |
572 |
lock.unlock(); |
573 |
} |
574 |
} |
575 |
|
576 |
/** |
577 |
* Always returns {@code Integer.MAX_VALUE} because |
578 |
* a {@code PriorityBlockingQueue} is not capacity constrained. |
579 |
* @return {@code Integer.MAX_VALUE} always |
580 |
*/ |
581 |
public int remainingCapacity() { |
582 |
return Integer.MAX_VALUE; |
583 |
} |
584 |
|
585 |
private int indexOf(Object o) { |
586 |
if (o != null) { |
587 |
Object[] array = queue; |
588 |
int n = size; |
589 |
for (int i = 0; i < n; i++) |
590 |
if (o.equals(array[i])) |
591 |
return i; |
592 |
} |
593 |
return -1; |
594 |
} |
595 |
|
596 |
/** |
597 |
* Removes the ith element from queue. |
598 |
*/ |
599 |
private void removeAt(int i) { |
600 |
Object[] array = queue; |
601 |
int n = size - 1; |
602 |
if (n == i) // removed last element |
603 |
array[i] = null; |
604 |
else { |
605 |
E moved = (E) array[n]; |
606 |
array[n] = null; |
607 |
Comparator<? super E> cmp = comparator; |
608 |
if (cmp == null) |
609 |
siftDownComparable(i, moved, array, n); |
610 |
else |
611 |
siftDownUsingComparator(i, moved, array, n, cmp); |
612 |
if (array[i] == moved) { |
613 |
if (cmp == null) |
614 |
siftUpComparable(i, moved, array); |
615 |
else |
616 |
siftUpUsingComparator(i, moved, array, cmp); |
617 |
} |
618 |
} |
619 |
size = n; |
620 |
} |
621 |
|
622 |
/** |
623 |
* Removes a single instance of the specified element from this queue, |
624 |
* if it is present. More formally, removes an element {@code e} such |
625 |
* that {@code o.equals(e)}, if this queue contains one or more such |
626 |
* elements. Returns {@code true} if and only if this queue contained |
627 |
* the specified element (or equivalently, if this queue changed as a |
628 |
* result of the call). |
629 |
* |
630 |
* @param o element to be removed from this queue, if present |
631 |
* @return {@code true} if this queue changed as a result of the call |
632 |
*/ |
633 |
public boolean remove(Object o) { |
634 |
final ReentrantLock lock = this.lock; |
635 |
lock.lock(); |
636 |
try { |
637 |
int i = indexOf(o); |
638 |
if (i == -1) |
639 |
return false; |
640 |
removeAt(i); |
641 |
return true; |
642 |
} finally { |
643 |
lock.unlock(); |
644 |
} |
645 |
} |
646 |
|
647 |
/** |
648 |
* Identity-based version for use in Itr.remove |
649 |
*/ |
650 |
void removeEQ(Object o) { |
651 |
final ReentrantLock lock = this.lock; |
652 |
lock.lock(); |
653 |
try { |
654 |
Object[] array = queue; |
655 |
for (int i = 0, n = size; i < n; i++) { |
656 |
if (o == array[i]) { |
657 |
removeAt(i); |
658 |
break; |
659 |
} |
660 |
} |
661 |
} finally { |
662 |
lock.unlock(); |
663 |
} |
664 |
} |
665 |
|
666 |
/** |
667 |
* Returns {@code true} if this queue contains the specified element. |
668 |
* More formally, returns {@code true} if and only if this queue contains |
669 |
* at least one element {@code e} such that {@code o.equals(e)}. |
670 |
* |
671 |
* @param o object to be checked for containment in this queue |
672 |
* @return {@code true} if this queue contains the specified element |
673 |
*/ |
674 |
public boolean contains(Object o) { |
675 |
final ReentrantLock lock = this.lock; |
676 |
lock.lock(); |
677 |
try { |
678 |
return indexOf(o) != -1; |
679 |
} finally { |
680 |
lock.unlock(); |
681 |
} |
682 |
} |
683 |
|
684 |
/** |
685 |
* Returns an array containing all of the elements in this queue. |
686 |
* The returned array elements are in no particular order. |
687 |
* |
688 |
* <p>The returned array will be "safe" in that no references to it are |
689 |
* maintained by this queue. (In other words, this method must allocate |
690 |
* a new array). The caller is thus free to modify the returned array. |
691 |
* |
692 |
* <p>This method acts as bridge between array-based and collection-based |
693 |
* APIs. |
694 |
* |
695 |
* @return an array containing all of the elements in this queue |
696 |
*/ |
697 |
public Object[] toArray() { |
698 |
final ReentrantLock lock = this.lock; |
699 |
lock.lock(); |
700 |
try { |
701 |
return Arrays.copyOf(queue, size); |
702 |
} finally { |
703 |
lock.unlock(); |
704 |
} |
705 |
} |
706 |
|
707 |
public String toString() { |
708 |
final ReentrantLock lock = this.lock; |
709 |
lock.lock(); |
710 |
try { |
711 |
int n = size; |
712 |
if (n == 0) |
713 |
return "[]"; |
714 |
StringBuilder sb = new StringBuilder(); |
715 |
sb.append('['); |
716 |
for (int i = 0; i < n; ++i) { |
717 |
Object e = queue[i]; |
718 |
sb.append(e == this ? "(this Collection)" : e); |
719 |
if (i != n - 1) |
720 |
sb.append(',').append(' '); |
721 |
} |
722 |
return sb.append(']').toString(); |
723 |
} finally { |
724 |
lock.unlock(); |
725 |
} |
726 |
} |
727 |
|
728 |
/** |
729 |
* @throws UnsupportedOperationException {@inheritDoc} |
730 |
* @throws ClassCastException {@inheritDoc} |
731 |
* @throws NullPointerException {@inheritDoc} |
732 |
* @throws IllegalArgumentException {@inheritDoc} |
733 |
*/ |
734 |
public int drainTo(Collection<? super E> c) { |
735 |
return drainTo(c, Integer.MAX_VALUE); |
736 |
} |
737 |
|
738 |
/** |
739 |
* @throws UnsupportedOperationException {@inheritDoc} |
740 |
* @throws ClassCastException {@inheritDoc} |
741 |
* @throws NullPointerException {@inheritDoc} |
742 |
* @throws IllegalArgumentException {@inheritDoc} |
743 |
*/ |
744 |
public int drainTo(Collection<? super E> c, int maxElements) { |
745 |
if (c == null) |
746 |
throw new NullPointerException(); |
747 |
if (c == this) |
748 |
throw new IllegalArgumentException(); |
749 |
if (maxElements <= 0) |
750 |
return 0; |
751 |
final ReentrantLock lock = this.lock; |
752 |
lock.lock(); |
753 |
try { |
754 |
int n = Math.min(size, maxElements); |
755 |
for (int i = 0; i < n; i++) { |
756 |
c.add((E) queue[0]); // In this order, in case add() throws. |
757 |
dequeue(); |
758 |
} |
759 |
return n; |
760 |
} finally { |
761 |
lock.unlock(); |
762 |
} |
763 |
} |
764 |
|
765 |
/** |
766 |
* Atomically removes all of the elements from this queue. |
767 |
* The queue will be empty after this call returns. |
768 |
*/ |
769 |
public void clear() { |
770 |
final ReentrantLock lock = this.lock; |
771 |
lock.lock(); |
772 |
try { |
773 |
Object[] array = queue; |
774 |
int n = size; |
775 |
size = 0; |
776 |
for (int i = 0; i < n; i++) |
777 |
array[i] = null; |
778 |
} finally { |
779 |
lock.unlock(); |
780 |
} |
781 |
} |
782 |
|
783 |
/** |
784 |
* Returns an array containing all of the elements in this queue; the |
785 |
* runtime type of the returned array is that of the specified array. |
786 |
* The returned array elements are in no particular order. |
787 |
* If the queue fits in the specified array, it is returned therein. |
788 |
* Otherwise, a new array is allocated with the runtime type of the |
789 |
* specified array and the size of this queue. |
790 |
* |
791 |
* <p>If this queue fits in the specified array with room to spare |
792 |
* (i.e., the array has more elements than this queue), the element in |
793 |
* the array immediately following the end of the queue is set to |
794 |
* {@code null}. |
795 |
* |
796 |
* <p>Like the {@link #toArray()} method, this method acts as bridge between |
797 |
* array-based and collection-based APIs. Further, this method allows |
798 |
* precise control over the runtime type of the output array, and may, |
799 |
* under certain circumstances, be used to save allocation costs. |
800 |
* |
801 |
* <p>Suppose {@code x} is a queue known to contain only strings. |
802 |
* The following code can be used to dump the queue into a newly |
803 |
* allocated array of {@code String}: |
804 |
* |
805 |
* <pre> {@code String[] y = x.toArray(new String[0]);}</pre> |
806 |
* |
807 |
* Note that {@code toArray(new Object[0])} is identical in function to |
808 |
* {@code toArray()}. |
809 |
* |
810 |
* @param a the array into which the elements of the queue are to |
811 |
* be stored, if it is big enough; otherwise, a new array of the |
812 |
* same runtime type is allocated for this purpose |
813 |
* @return an array containing all of the elements in this queue |
814 |
* @throws ArrayStoreException if the runtime type of the specified array |
815 |
* is not a supertype of the runtime type of every element in |
816 |
* this queue |
817 |
* @throws NullPointerException if the specified array is null |
818 |
*/ |
819 |
public <T> T[] toArray(T[] a) { |
820 |
final ReentrantLock lock = this.lock; |
821 |
lock.lock(); |
822 |
try { |
823 |
int n = size; |
824 |
if (a.length < n) |
825 |
// Make a new array of a's runtime type, but my contents: |
826 |
return (T[]) Arrays.copyOf(queue, size, a.getClass()); |
827 |
System.arraycopy(queue, 0, a, 0, n); |
828 |
if (a.length > n) |
829 |
a[n] = null; |
830 |
return a; |
831 |
} finally { |
832 |
lock.unlock(); |
833 |
} |
834 |
} |
835 |
|
836 |
/** |
837 |
* Returns an iterator over the elements in this queue. The |
838 |
* iterator does not return the elements in any particular order. |
839 |
* |
840 |
* <p>The returned iterator is a "weakly consistent" iterator that |
841 |
* will never throw {@link java.util.ConcurrentModificationException |
842 |
* ConcurrentModificationException}, and guarantees to traverse |
843 |
* elements as they existed upon construction of the iterator, and |
844 |
* may (but is not guaranteed to) reflect any modifications |
845 |
* subsequent to construction. |
846 |
* |
847 |
* @return an iterator over the elements in this queue |
848 |
*/ |
849 |
public Iterator<E> iterator() { |
850 |
return new Itr(toArray()); |
851 |
} |
852 |
|
853 |
/** |
854 |
* Snapshot iterator that works off copy of underlying q array. |
855 |
*/ |
856 |
final class Itr implements Iterator<E> { |
857 |
final Object[] array; // Array of all elements |
858 |
int cursor; // index of next element to return |
859 |
int lastRet; // index of last element, or -1 if no such |
860 |
|
861 |
Itr(Object[] array) { |
862 |
lastRet = -1; |
863 |
this.array = array; |
864 |
} |
865 |
|
866 |
public boolean hasNext() { |
867 |
return cursor < array.length; |
868 |
} |
869 |
|
870 |
public E next() { |
871 |
if (cursor >= array.length) |
872 |
throw new NoSuchElementException(); |
873 |
lastRet = cursor; |
874 |
return (E)array[cursor++]; |
875 |
} |
876 |
|
877 |
public void remove() { |
878 |
if (lastRet < 0) |
879 |
throw new IllegalStateException(); |
880 |
removeEQ(array[lastRet]); |
881 |
lastRet = -1; |
882 |
} |
883 |
} |
884 |
|
885 |
/** |
886 |
* Saves this queue to a stream (that is, serializes it). |
887 |
* |
888 |
* For compatibility with previous version of this class, elements |
889 |
* are first copied to a java.util.PriorityQueue, which is then |
890 |
* serialized. |
891 |
*/ |
892 |
private void writeObject(java.io.ObjectOutputStream s) |
893 |
throws java.io.IOException { |
894 |
lock.lock(); |
895 |
try { |
896 |
// avoid zero capacity argument |
897 |
q = new PriorityQueue<E>(Math.max(size, 1), comparator); |
898 |
q.addAll(this); |
899 |
s.defaultWriteObject(); |
900 |
} finally { |
901 |
q = null; |
902 |
lock.unlock(); |
903 |
} |
904 |
} |
905 |
|
906 |
/** |
907 |
* Reconstitutes this queue from a stream (that is, deserializes it). |
908 |
*/ |
909 |
private void readObject(java.io.ObjectInputStream s) |
910 |
throws java.io.IOException, ClassNotFoundException { |
911 |
try { |
912 |
s.defaultReadObject(); |
913 |
this.queue = new Object[q.size()]; |
914 |
comparator = q.comparator(); |
915 |
addAll(q); |
916 |
} finally { |
917 |
q = null; |
918 |
} |
919 |
} |
920 |
|
921 |
// wrapping constructor in method avoids transient javac problems |
922 |
final PBQSpliterator<E> spliterator() { |
923 |
Object[] a = toArray(); |
924 |
return new PBQSpliterator<E>(a, 0, a.length); |
925 |
} |
926 |
|
927 |
public Stream<E> stream() { |
928 |
int flags = Streams.STREAM_IS_SIZED; |
929 |
return Streams.stream |
930 |
(() -> spliterator(), flags); |
931 |
} |
932 |
public Stream<E> parallelStream() { |
933 |
int flags = Streams.STREAM_IS_SIZED; |
934 |
return Streams.parallelStream |
935 |
(() -> spliterator(), flags); |
936 |
} |
937 |
|
938 |
/** Index-based split-by-two Spliterator */ |
939 |
static final class PBQSpliterator<E> implements Spliterator<E> { |
940 |
private final Object[] array; |
941 |
private int index; // current index, modified on advance/split |
942 |
private final int fence; // one past last index |
943 |
|
944 |
/** Create new spliterator covering the given array and range */ |
945 |
PBQSpliterator(Object[] array, int origin, int fence) { |
946 |
this.array = array; this.index = origin; this.fence = fence; |
947 |
} |
948 |
|
949 |
public PBQSpliterator<E> trySplit() { |
950 |
int lo = index, mid = (lo + fence) >>> 1; |
951 |
return (lo >= mid) ? null : |
952 |
new PBQSpliterator<E>(array, lo, index = mid); |
953 |
} |
954 |
|
955 |
public void forEach(Block<? super E> block) { |
956 |
Object[] a; int i, hi; // hoist accesses and checks from loop |
957 |
if (block == null) |
958 |
throw new NullPointerException(); |
959 |
if ((a = array).length >= (hi = fence) && |
960 |
(i = index) >= 0 && i < hi) { |
961 |
index = hi; |
962 |
do { |
963 |
@SuppressWarnings("unchecked") E e = (E) a[i]; |
964 |
block.accept(e); |
965 |
} while (++i < hi); |
966 |
} |
967 |
} |
968 |
|
969 |
public boolean tryAdvance(Block<? super E> block) { |
970 |
if (index >= 0 && index < fence) { |
971 |
@SuppressWarnings("unchecked") E e = (E) array[index++]; |
972 |
block.accept(e); |
973 |
return true; |
974 |
} |
975 |
return false; |
976 |
} |
977 |
|
978 |
public long estimateSize() { return (long)(fence - index); } |
979 |
public boolean hasExactSize() { return true; } |
980 |
public boolean hasExactSplits() { return true; } |
981 |
} |
982 |
|
983 |
// Unsafe mechanics |
984 |
private static final sun.misc.Unsafe UNSAFE; |
985 |
private static final long allocationSpinLockOffset; |
986 |
static { |
987 |
try { |
988 |
UNSAFE = sun.misc.Unsafe.getUnsafe(); |
989 |
Class<?> k = PriorityBlockingQueue.class; |
990 |
allocationSpinLockOffset = UNSAFE.objectFieldOffset |
991 |
(k.getDeclaredField("allocationSpinLock")); |
992 |
} catch (Exception e) { |
993 |
throw new Error(e); |
994 |
} |
995 |
} |
996 |
} |