ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingQueue.java
Revision: 1.100
Committed: Sun Dec 11 19:59:51 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.99: +37 -44 lines
Log Message:
8171051: LinkedBlockingQueue spliterator needs to support node self-linking

File Contents

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