ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingQueue.java
Revision: 1.90
Committed: Wed Dec 31 09:37:20 2014 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.89: +0 -2 lines
Log Message:
remove unused/redundant imports

File Contents

# Content
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.AbstractQueue;
10 import java.util.Collection;
11 import java.util.Iterator;
12 import java.util.NoSuchElementException;
13 import java.util.Spliterator;
14 import java.util.Spliterators;
15 import java.util.concurrent.atomic.AtomicInteger;
16 import java.util.concurrent.locks.Condition;
17 import java.util.concurrent.locks.ReentrantLock;
18 import java.util.function.Consumer;
19
20 /**
21 * An optionally-bounded {@linkplain BlockingQueue blocking queue} based on
22 * linked nodes.
23 * This queue orders elements FIFO (first-in-first-out).
24 * The <em>head</em> of the queue is that element that has been on the
25 * queue the longest time.
26 * The <em>tail</em> of the queue is that element that has been on the
27 * queue the shortest time. New elements
28 * are inserted at the tail of the queue, and the queue retrieval
29 * operations obtain elements at the head of the queue.
30 * Linked queues typically have higher throughput than array-based queues but
31 * less predictable performance in most concurrent applications.
32 *
33 * <p>The optional capacity bound constructor argument serves as a
34 * way to prevent excessive queue expansion. The capacity, if unspecified,
35 * is equal to {@link Integer#MAX_VALUE}. Linked nodes are
36 * dynamically created upon each insertion unless this would bring the
37 * queue above capacity.
38 *
39 * <p>This class and its iterator implement all of the
40 * <em>optional</em> methods of the {@link Collection} and {@link
41 * Iterator} interfaces.
42 *
43 * <p>This class is a member of the
44 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
45 * Java Collections Framework</a>.
46 *
47 * @since 1.5
48 * @author Doug Lea
49 * @param <E> the type of elements held in this queue
50 */
51 public class LinkedBlockingQueue<E> extends AbstractQueue<E>
52 implements BlockingQueue<E>, java.io.Serializable {
53 private static final long serialVersionUID = -6903933977591709194L;
54
55 /*
56 * A variant of the "two lock queue" algorithm. The putLock gates
57 * entry to put (and offer), and has an associated condition for
58 * waiting puts. Similarly for the takeLock. The "count" field
59 * that they both rely on is maintained as an atomic to avoid
60 * needing to get both locks in most cases. Also, to minimize need
61 * for puts to get takeLock and vice-versa, cascading notifies are
62 * used. When a put notices that it has enabled at least one take,
63 * it signals taker. That taker in turn signals others if more
64 * items have been entered since the signal. And symmetrically for
65 * takes signalling puts. Operations such as remove(Object) and
66 * iterators acquire both locks.
67 *
68 * Visibility between writers and readers is provided as follows:
69 *
70 * Whenever an element is enqueued, the putLock is acquired and
71 * count updated. A subsequent reader guarantees visibility to the
72 * enqueued Node by either acquiring the putLock (via fullyLock)
73 * or by acquiring the takeLock, and then reading n = count.get();
74 * this gives visibility to the first n items.
75 *
76 * To implement weakly consistent iterators, it appears we need to
77 * keep all Nodes GC-reachable from a predecessor dequeued Node.
78 * That would cause two problems:
79 * - allow a rogue Iterator to cause unbounded memory retention
80 * - cause cross-generational linking of old Nodes to new Nodes if
81 * a Node was tenured while live, which generational GCs have a
82 * hard time dealing with, causing repeated major collections.
83 * However, only non-deleted Nodes need to be reachable from
84 * dequeued Nodes, and reachability does not necessarily have to
85 * be of the kind understood by the GC. We use the trick of
86 * linking a Node that has just been dequeued to itself. Such a
87 * self-link implicitly means to advance to head.next.
88 */
89
90 /**
91 * Linked list node class
92 */
93 static class Node<E> {
94 E item;
95
96 /**
97 * One of:
98 * - the real successor Node
99 * - this Node, meaning the successor is head.next
100 * - null, meaning there is no successor (this is the last node)
101 */
102 Node<E> next;
103
104 Node(E x) { item = x; }
105 }
106
107 /** The capacity bound, or Integer.MAX_VALUE if none */
108 private final int capacity;
109
110 /** Current number of elements */
111 private final AtomicInteger count = new AtomicInteger();
112
113 /**
114 * Head of linked list.
115 * Invariant: head.item == null
116 */
117 transient Node<E> head;
118
119 /**
120 * Tail of linked list.
121 * Invariant: last.next == null
122 */
123 private transient Node<E> last;
124
125 /** Lock held by take, poll, etc */
126 private final ReentrantLock takeLock = new ReentrantLock();
127
128 /** Wait queue for waiting takes */
129 private final Condition notEmpty = takeLock.newCondition();
130
131 /** Lock held by put, offer, etc */
132 private final ReentrantLock putLock = new ReentrantLock();
133
134 /** Wait queue for waiting puts */
135 private final Condition notFull = putLock.newCondition();
136
137 /**
138 * Signals a waiting take. Called only from put/offer (which do not
139 * otherwise ordinarily lock takeLock.)
140 */
141 private void signalNotEmpty() {
142 final ReentrantLock takeLock = this.takeLock;
143 takeLock.lock();
144 try {
145 notEmpty.signal();
146 } finally {
147 takeLock.unlock();
148 }
149 }
150
151 /**
152 * Signals a waiting put. Called only from take/poll.
153 */
154 private void signalNotFull() {
155 final ReentrantLock putLock = this.putLock;
156 putLock.lock();
157 try {
158 notFull.signal();
159 } finally {
160 putLock.unlock();
161 }
162 }
163
164 /**
165 * Links node at end of queue.
166 *
167 * @param node the node
168 */
169 private void enqueue(Node<E> node) {
170 // assert putLock.isHeldByCurrentThread();
171 // assert last.next == null;
172 last = last.next = node;
173 }
174
175 /**
176 * Removes a node from head of queue.
177 *
178 * @return the node
179 */
180 private E dequeue() {
181 // assert takeLock.isHeldByCurrentThread();
182 // assert head.item == null;
183 Node<E> h = head;
184 Node<E> first = h.next;
185 h.next = h; // help GC
186 head = first;
187 E x = first.item;
188 first.item = null;
189 return x;
190 }
191
192 /**
193 * Locks to prevent both puts and takes.
194 */
195 void fullyLock() {
196 putLock.lock();
197 takeLock.lock();
198 }
199
200 /**
201 * Unlocks to allow both puts and takes.
202 */
203 void fullyUnlock() {
204 takeLock.unlock();
205 putLock.unlock();
206 }
207
208 // /**
209 // * Tells whether both locks are held by current thread.
210 // */
211 // boolean isFullyLocked() {
212 // return (putLock.isHeldByCurrentThread() &&
213 // takeLock.isHeldByCurrentThread());
214 // }
215
216 /**
217 * Creates a {@code LinkedBlockingQueue} with a capacity of
218 * {@link Integer#MAX_VALUE}.
219 */
220 public LinkedBlockingQueue() {
221 this(Integer.MAX_VALUE);
222 }
223
224 /**
225 * Creates a {@code LinkedBlockingQueue} with the given (fixed) capacity.
226 *
227 * @param capacity the capacity of this queue
228 * @throws IllegalArgumentException if {@code capacity} is not greater
229 * than zero
230 */
231 public LinkedBlockingQueue(int capacity) {
232 if (capacity <= 0) throw new IllegalArgumentException();
233 this.capacity = capacity;
234 last = head = new Node<E>(null);
235 }
236
237 /**
238 * Creates a {@code LinkedBlockingQueue} with a capacity of
239 * {@link Integer#MAX_VALUE}, initially containing the elements of the
240 * given collection,
241 * added in traversal order of the collection's iterator.
242 *
243 * @param c the collection of elements to initially contain
244 * @throws NullPointerException if the specified collection or any
245 * of its elements are null
246 */
247 public LinkedBlockingQueue(Collection<? extends E> c) {
248 this(Integer.MAX_VALUE);
249 final ReentrantLock putLock = this.putLock;
250 putLock.lock(); // Never contended, but necessary for visibility
251 try {
252 int n = 0;
253 for (E e : c) {
254 if (e == null)
255 throw new NullPointerException();
256 if (n == capacity)
257 throw new IllegalStateException("Queue full");
258 enqueue(new Node<E>(e));
259 ++n;
260 }
261 count.set(n);
262 } finally {
263 putLock.unlock();
264 }
265 }
266
267 // this doc comment is overridden to remove the reference to collections
268 // greater in size than Integer.MAX_VALUE
269 /**
270 * Returns the number of elements in this queue.
271 *
272 * @return the number of elements in this queue
273 */
274 public int size() {
275 return count.get();
276 }
277
278 // this doc comment is a modified copy of the inherited doc comment,
279 // without the reference to unlimited queues.
280 /**
281 * Returns the number of additional elements that this queue can ideally
282 * (in the absence of memory or resource constraints) accept without
283 * blocking. This is always equal to the initial capacity of this queue
284 * less the current {@code size} of this queue.
285 *
286 * <p>Note that you <em>cannot</em> always tell if an attempt to insert
287 * an element will succeed by inspecting {@code remainingCapacity}
288 * because it may be the case that another thread is about to
289 * insert or remove an element.
290 */
291 public int remainingCapacity() {
292 return capacity - count.get();
293 }
294
295 /**
296 * Inserts the specified element at the tail of this queue, waiting if
297 * necessary for space to become available.
298 *
299 * @throws InterruptedException {@inheritDoc}
300 * @throws NullPointerException {@inheritDoc}
301 */
302 public void put(E e) throws InterruptedException {
303 if (e == null) throw new NullPointerException();
304 // Note: convention in all put/take/etc is to preset local var
305 // holding count negative to indicate failure unless set.
306 int c = -1;
307 Node<E> node = new Node<E>(e);
308 final ReentrantLock putLock = this.putLock;
309 final AtomicInteger count = this.count;
310 putLock.lockInterruptibly();
311 try {
312 /*
313 * Note that count is used in wait guard even though it is
314 * not protected by lock. This works because count can
315 * only decrease at this point (all other puts are shut
316 * out by lock), and we (or some other waiting put) are
317 * signalled if it ever changes from capacity. Similarly
318 * for all other uses of count in other wait guards.
319 */
320 while (count.get() == capacity) {
321 notFull.await();
322 }
323 enqueue(node);
324 c = count.getAndIncrement();
325 if (c + 1 < capacity)
326 notFull.signal();
327 } finally {
328 putLock.unlock();
329 }
330 if (c == 0)
331 signalNotEmpty();
332 }
333
334 /**
335 * Inserts the specified element at the tail of this queue, waiting if
336 * necessary up to the specified wait time for space to become available.
337 *
338 * @return {@code true} if successful, or {@code false} if
339 * the specified waiting time elapses before space is available
340 * @throws InterruptedException {@inheritDoc}
341 * @throws NullPointerException {@inheritDoc}
342 */
343 public boolean offer(E e, long timeout, TimeUnit unit)
344 throws InterruptedException {
345
346 if (e == null) throw new NullPointerException();
347 long nanos = unit.toNanos(timeout);
348 int c = -1;
349 final ReentrantLock putLock = this.putLock;
350 final AtomicInteger count = this.count;
351 putLock.lockInterruptibly();
352 try {
353 while (count.get() == capacity) {
354 if (nanos <= 0)
355 return false;
356 nanos = notFull.awaitNanos(nanos);
357 }
358 enqueue(new Node<E>(e));
359 c = count.getAndIncrement();
360 if (c + 1 < capacity)
361 notFull.signal();
362 } finally {
363 putLock.unlock();
364 }
365 if (c == 0)
366 signalNotEmpty();
367 return true;
368 }
369
370 /**
371 * Inserts the specified element at the tail of this queue if it is
372 * possible to do so immediately without exceeding the queue's capacity,
373 * returning {@code true} upon success and {@code false} if this queue
374 * is full.
375 * When using a capacity-restricted queue, this method is generally
376 * preferable to method {@link BlockingQueue#add add}, which can fail to
377 * insert an element only by throwing an exception.
378 *
379 * @throws NullPointerException if the specified element is null
380 */
381 public boolean offer(E e) {
382 if (e == null) throw new NullPointerException();
383 final AtomicInteger count = this.count;
384 if (count.get() == capacity)
385 return false;
386 int c = -1;
387 Node<E> node = new Node<E>(e);
388 final ReentrantLock putLock = this.putLock;
389 putLock.lock();
390 try {
391 if (count.get() < capacity) {
392 enqueue(node);
393 c = count.getAndIncrement();
394 if (c + 1 < capacity)
395 notFull.signal();
396 }
397 } finally {
398 putLock.unlock();
399 }
400 if (c == 0)
401 signalNotEmpty();
402 return c >= 0;
403 }
404
405 public E take() throws InterruptedException {
406 E x;
407 int c = -1;
408 final AtomicInteger count = this.count;
409 final ReentrantLock takeLock = this.takeLock;
410 takeLock.lockInterruptibly();
411 try {
412 while (count.get() == 0) {
413 notEmpty.await();
414 }
415 x = dequeue();
416 c = count.getAndDecrement();
417 if (c > 1)
418 notEmpty.signal();
419 } finally {
420 takeLock.unlock();
421 }
422 if (c == capacity)
423 signalNotFull();
424 return x;
425 }
426
427 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
428 E x = null;
429 int c = -1;
430 long nanos = unit.toNanos(timeout);
431 final AtomicInteger count = this.count;
432 final ReentrantLock takeLock = this.takeLock;
433 takeLock.lockInterruptibly();
434 try {
435 while (count.get() == 0) {
436 if (nanos <= 0)
437 return null;
438 nanos = notEmpty.awaitNanos(nanos);
439 }
440 x = dequeue();
441 c = count.getAndDecrement();
442 if (c > 1)
443 notEmpty.signal();
444 } finally {
445 takeLock.unlock();
446 }
447 if (c == capacity)
448 signalNotFull();
449 return x;
450 }
451
452 public E poll() {
453 final AtomicInteger count = this.count;
454 if (count.get() == 0)
455 return null;
456 E x = null;
457 int c = -1;
458 final ReentrantLock takeLock = this.takeLock;
459 takeLock.lock();
460 try {
461 if (count.get() > 0) {
462 x = dequeue();
463 c = count.getAndDecrement();
464 if (c > 1)
465 notEmpty.signal();
466 }
467 } finally {
468 takeLock.unlock();
469 }
470 if (c == capacity)
471 signalNotFull();
472 return x;
473 }
474
475 public E peek() {
476 if (count.get() == 0)
477 return null;
478 final ReentrantLock takeLock = this.takeLock;
479 takeLock.lock();
480 try {
481 Node<E> first = head.next;
482 if (first == null)
483 return null;
484 else
485 return first.item;
486 } finally {
487 takeLock.unlock();
488 }
489 }
490
491 /**
492 * Unlinks interior Node p with predecessor trail.
493 */
494 void unlink(Node<E> p, Node<E> trail) {
495 // assert isFullyLocked();
496 // p.next is not changed, to allow iterators that are
497 // traversing p to maintain their weak-consistency guarantee.
498 p.item = null;
499 trail.next = p.next;
500 if (last == p)
501 last = trail;
502 if (count.getAndDecrement() == capacity)
503 notFull.signal();
504 }
505
506 /**
507 * Removes a single instance of the specified element from this queue,
508 * if it is present. More formally, removes an element {@code e} such
509 * that {@code o.equals(e)}, if this queue contains one or more such
510 * elements.
511 * Returns {@code true} if this queue contained the specified element
512 * (or equivalently, if this queue changed as a result of the call).
513 *
514 * @param o element to be removed from this queue, if present
515 * @return {@code true} if this queue changed as a result of the call
516 */
517 public boolean remove(Object o) {
518 if (o == null) return false;
519 fullyLock();
520 try {
521 for (Node<E> trail = head, p = trail.next;
522 p != null;
523 trail = p, p = p.next) {
524 if (o.equals(p.item)) {
525 unlink(p, trail);
526 return true;
527 }
528 }
529 return false;
530 } finally {
531 fullyUnlock();
532 }
533 }
534
535 /**
536 * Returns {@code true} if this queue contains the specified element.
537 * More formally, returns {@code true} if and only if this queue contains
538 * at least one element {@code e} such that {@code o.equals(e)}.
539 *
540 * @param o object to be checked for containment in this queue
541 * @return {@code true} if this queue contains the specified element
542 */
543 public boolean contains(Object o) {
544 if (o == null) return false;
545 fullyLock();
546 try {
547 for (Node<E> p = head.next; p != null; p = p.next)
548 if (o.equals(p.item))
549 return true;
550 return false;
551 } finally {
552 fullyUnlock();
553 }
554 }
555
556 /**
557 * Returns an array containing all of the elements in this queue, in
558 * proper sequence.
559 *
560 * <p>The returned array will be "safe" in that no references to it are
561 * maintained by this queue. (In other words, this method must allocate
562 * a new array). The caller is thus free to modify the returned array.
563 *
564 * <p>This method acts as bridge between array-based and collection-based
565 * APIs.
566 *
567 * @return an array containing all of the elements in this queue
568 */
569 public Object[] toArray() {
570 fullyLock();
571 try {
572 int size = count.get();
573 Object[] a = new Object[size];
574 int k = 0;
575 for (Node<E> p = head.next; p != null; p = p.next)
576 a[k++] = p.item;
577 return a;
578 } finally {
579 fullyUnlock();
580 }
581 }
582
583 /**
584 * Returns an array containing all of the elements in this queue, in
585 * proper sequence; the runtime type of the returned array is that of
586 * the specified array. If the queue fits in the specified array, it
587 * is returned therein. Otherwise, a new array is allocated with the
588 * runtime type of the specified array and the size of this queue.
589 *
590 * <p>If this queue fits in the specified array with room to spare
591 * (i.e., the array has more elements than this queue), the element in
592 * the array immediately following the end of the queue is set to
593 * {@code null}.
594 *
595 * <p>Like the {@link #toArray()} method, this method acts as bridge between
596 * array-based and collection-based APIs. Further, this method allows
597 * precise control over the runtime type of the output array, and may,
598 * under certain circumstances, be used to save allocation costs.
599 *
600 * <p>Suppose {@code x} is a queue known to contain only strings.
601 * The following code can be used to dump the queue into a newly
602 * allocated array of {@code String}:
603 *
604 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
605 *
606 * Note that {@code toArray(new Object[0])} is identical in function to
607 * {@code toArray()}.
608 *
609 * @param a the array into which the elements of the queue are to
610 * be stored, if it is big enough; otherwise, a new array of the
611 * same runtime type is allocated for this purpose
612 * @return an array containing all of the elements in this queue
613 * @throws ArrayStoreException if the runtime type of the specified array
614 * is not a supertype of the runtime type of every element in
615 * this queue
616 * @throws NullPointerException if the specified array is null
617 */
618 @SuppressWarnings("unchecked")
619 public <T> T[] toArray(T[] a) {
620 fullyLock();
621 try {
622 int size = count.get();
623 if (a.length < size)
624 a = (T[])java.lang.reflect.Array.newInstance
625 (a.getClass().getComponentType(), size);
626
627 int k = 0;
628 for (Node<E> p = head.next; p != null; p = p.next)
629 a[k++] = (T)p.item;
630 if (a.length > k)
631 a[k] = null;
632 return a;
633 } finally {
634 fullyUnlock();
635 }
636 }
637
638 public String toString() {
639 fullyLock();
640 try {
641 Node<E> p = head.next;
642 if (p == null)
643 return "[]";
644
645 StringBuilder sb = new StringBuilder();
646 sb.append('[');
647 for (;;) {
648 E e = p.item;
649 sb.append(e == this ? "(this Collection)" : e);
650 p = p.next;
651 if (p == null)
652 return sb.append(']').toString();
653 sb.append(',').append(' ');
654 }
655 } finally {
656 fullyUnlock();
657 }
658 }
659
660 /**
661 * Atomically removes all of the elements from this queue.
662 * The queue will be empty after this call returns.
663 */
664 public void clear() {
665 fullyLock();
666 try {
667 for (Node<E> p, h = head; (p = h.next) != null; h = p) {
668 h.next = h;
669 p.item = null;
670 }
671 head = last;
672 // assert head.item == null && head.next == null;
673 if (count.getAndSet(0) == capacity)
674 notFull.signal();
675 } finally {
676 fullyUnlock();
677 }
678 }
679
680 /**
681 * @throws UnsupportedOperationException {@inheritDoc}
682 * @throws ClassCastException {@inheritDoc}
683 * @throws NullPointerException {@inheritDoc}
684 * @throws IllegalArgumentException {@inheritDoc}
685 */
686 public int drainTo(Collection<? super E> c) {
687 return drainTo(c, Integer.MAX_VALUE);
688 }
689
690 /**
691 * @throws UnsupportedOperationException {@inheritDoc}
692 * @throws ClassCastException {@inheritDoc}
693 * @throws NullPointerException {@inheritDoc}
694 * @throws IllegalArgumentException {@inheritDoc}
695 */
696 public int drainTo(Collection<? super E> c, int maxElements) {
697 if (c == null)
698 throw new NullPointerException();
699 if (c == this)
700 throw new IllegalArgumentException();
701 if (maxElements <= 0)
702 return 0;
703 boolean signalNotFull = false;
704 final ReentrantLock takeLock = this.takeLock;
705 takeLock.lock();
706 try {
707 int n = Math.min(maxElements, count.get());
708 // count.get provides visibility to first n Nodes
709 Node<E> h = head;
710 int i = 0;
711 try {
712 while (i < n) {
713 Node<E> p = h.next;
714 c.add(p.item);
715 p.item = null;
716 h.next = h;
717 h = p;
718 ++i;
719 }
720 return n;
721 } finally {
722 // Restore invariants even if c.add() threw
723 if (i > 0) {
724 // assert h.item == null;
725 head = h;
726 signalNotFull = (count.getAndAdd(-i) == capacity);
727 }
728 }
729 } finally {
730 takeLock.unlock();
731 if (signalNotFull)
732 signalNotFull();
733 }
734 }
735
736 /**
737 * Returns an iterator over the elements in this queue in proper sequence.
738 * The elements will be returned in order from first (head) to last (tail).
739 *
740 * <p>The returned iterator is
741 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
742 *
743 * @return an iterator over the elements in this queue in proper sequence
744 */
745 public Iterator<E> iterator() {
746 return new Itr();
747 }
748
749 private class Itr implements Iterator<E> {
750 /*
751 * Basic weakly-consistent iterator. At all times hold the next
752 * item to hand out so that if hasNext() reports true, we will
753 * still have it to return even if lost race with a take etc.
754 */
755
756 private Node<E> current;
757 private Node<E> lastRet;
758 private E currentElement;
759
760 Itr() {
761 fullyLock();
762 try {
763 current = head.next;
764 if (current != null)
765 currentElement = current.item;
766 } finally {
767 fullyUnlock();
768 }
769 }
770
771 public boolean hasNext() {
772 return current != null;
773 }
774
775 /**
776 * Returns the next live successor of p, or null if no such.
777 *
778 * Unlike other traversal methods, iterators need to handle both:
779 * - dequeued nodes (p.next == p)
780 * - (possibly multiple) interior removed nodes (p.item == null)
781 */
782 private Node<E> nextNode(Node<E> p) {
783 for (;;) {
784 Node<E> s = p.next;
785 if (s == p)
786 return head.next;
787 if (s == null || s.item != null)
788 return s;
789 p = s;
790 }
791 }
792
793 public E next() {
794 fullyLock();
795 try {
796 if (current == null)
797 throw new NoSuchElementException();
798 E x = currentElement;
799 lastRet = current;
800 current = nextNode(current);
801 currentElement = (current == null) ? null : current.item;
802 return x;
803 } finally {
804 fullyUnlock();
805 }
806 }
807
808 public void remove() {
809 if (lastRet == null)
810 throw new IllegalStateException();
811 fullyLock();
812 try {
813 Node<E> node = lastRet;
814 lastRet = null;
815 for (Node<E> trail = head, p = trail.next;
816 p != null;
817 trail = p, p = p.next) {
818 if (p == node) {
819 unlink(p, trail);
820 break;
821 }
822 }
823 } finally {
824 fullyUnlock();
825 }
826 }
827 }
828
829 /** A customized variant of Spliterators.IteratorSpliterator */
830 static final class LBQSpliterator<E> implements Spliterator<E> {
831 static final int MAX_BATCH = 1 << 25; // max batch array size;
832 final LinkedBlockingQueue<E> queue;
833 Node<E> current; // current node; null until initialized
834 int batch; // batch size for splits
835 boolean exhausted; // true when no more nodes
836 long est; // size estimate
837 LBQSpliterator(LinkedBlockingQueue<E> queue) {
838 this.queue = queue;
839 this.est = queue.size();
840 }
841
842 public long estimateSize() { return est; }
843
844 public Spliterator<E> trySplit() {
845 Node<E> h;
846 final LinkedBlockingQueue<E> q = this.queue;
847 int b = batch;
848 int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
849 if (!exhausted &&
850 ((h = current) != null || (h = q.head.next) != null) &&
851 h.next != null) {
852 Object[] a = new Object[n];
853 int i = 0;
854 Node<E> p = current;
855 q.fullyLock();
856 try {
857 if (p != null || (p = q.head.next) != null) {
858 do {
859 if ((a[i] = p.item) != null)
860 ++i;
861 } while ((p = p.next) != null && i < n);
862 }
863 } finally {
864 q.fullyUnlock();
865 }
866 if ((current = p) == null) {
867 est = 0L;
868 exhausted = true;
869 }
870 else if ((est -= i) < 0L)
871 est = 0L;
872 if (i > 0) {
873 batch = i;
874 return Spliterators.spliterator
875 (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
876 Spliterator.CONCURRENT);
877 }
878 }
879 return null;
880 }
881
882 public void forEachRemaining(Consumer<? super E> action) {
883 if (action == null) throw new NullPointerException();
884 final LinkedBlockingQueue<E> q = this.queue;
885 if (!exhausted) {
886 exhausted = true;
887 Node<E> p = current;
888 do {
889 E e = null;
890 q.fullyLock();
891 try {
892 if (p == null)
893 p = q.head.next;
894 while (p != null) {
895 e = p.item;
896 p = p.next;
897 if (e != null)
898 break;
899 }
900 } finally {
901 q.fullyUnlock();
902 }
903 if (e != null)
904 action.accept(e);
905 } while (p != null);
906 }
907 }
908
909 public boolean tryAdvance(Consumer<? super E> action) {
910 if (action == null) throw new NullPointerException();
911 final LinkedBlockingQueue<E> q = this.queue;
912 if (!exhausted) {
913 E e = null;
914 q.fullyLock();
915 try {
916 if (current == null)
917 current = q.head.next;
918 while (current != null) {
919 e = current.item;
920 current = current.next;
921 if (e != null)
922 break;
923 }
924 } finally {
925 q.fullyUnlock();
926 }
927 if (current == null)
928 exhausted = true;
929 if (e != null) {
930 action.accept(e);
931 return true;
932 }
933 }
934 return false;
935 }
936
937 public int characteristics() {
938 return Spliterator.ORDERED | Spliterator.NONNULL |
939 Spliterator.CONCURRENT;
940 }
941 }
942
943 /**
944 * Returns a {@link Spliterator} over the elements in this queue.
945 *
946 * <p>The returned spliterator is
947 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
948 *
949 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
950 * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
951 *
952 * @implNote
953 * The {@code Spliterator} implements {@code trySplit} to permit limited
954 * parallelism.
955 *
956 * @return a {@code Spliterator} over the elements in this queue
957 * @since 1.8
958 */
959 public Spliterator<E> spliterator() {
960 return new LBQSpliterator<E>(this);
961 }
962
963 /**
964 * Saves this queue to a stream (that is, serializes it).
965 *
966 * @param s the stream
967 * @throws java.io.IOException if an I/O error occurs
968 * @serialData The capacity is emitted (int), followed by all of
969 * its elements (each an {@code Object}) in the proper order,
970 * followed by a null
971 */
972 private void writeObject(java.io.ObjectOutputStream s)
973 throws java.io.IOException {
974
975 fullyLock();
976 try {
977 // Write out any hidden stuff, plus capacity
978 s.defaultWriteObject();
979
980 // Write out all elements in the proper order.
981 for (Node<E> p = head.next; p != null; p = p.next)
982 s.writeObject(p.item);
983
984 // Use trailing null as sentinel
985 s.writeObject(null);
986 } finally {
987 fullyUnlock();
988 }
989 }
990
991 /**
992 * Reconstitutes this queue from a stream (that is, deserializes it).
993 * @param s the stream
994 * @throws ClassNotFoundException if the class of a serialized object
995 * could not be found
996 * @throws java.io.IOException if an I/O error occurs
997 */
998 private void readObject(java.io.ObjectInputStream s)
999 throws java.io.IOException, ClassNotFoundException {
1000 // Read in capacity, and any hidden stuff
1001 s.defaultReadObject();
1002
1003 count.set(0);
1004 last = head = new Node<E>(null);
1005
1006 // Read in all elements and place in queue
1007 for (;;) {
1008 @SuppressWarnings("unchecked")
1009 E item = (E)s.readObject();
1010 if (item == null)
1011 break;
1012 add(item);
1013 }
1014 }
1015 }