ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingQueue.java
Revision: 1.92
Committed: Tue Feb 17 18:55:39 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.91: +1 -1 lines
Log Message:
standardize code sample idiom: * <pre> {@code

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     * Linked list node class
92     */
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 jsr166 1.51 // /**
209     // * Tells whether both locks are held by current thread.
210     // */
211     // boolean isFullyLocked() {
212     // return (putLock.isHeldByCurrentThread() &&
213     // takeLock.isHeldByCurrentThread());
214     // }
215 dl 1.2
216     /**
217 jsr166 1.51 * Creates a {@code LinkedBlockingQueue} with a capacity of
218 dholmes 1.8 * {@link Integer#MAX_VALUE}.
219 dl 1.2 */
220     public LinkedBlockingQueue() {
221     this(Integer.MAX_VALUE);
222     }
223    
224     /**
225 jsr166 1.51 * Creates a {@code LinkedBlockingQueue} with the given (fixed) capacity.
226 tim 1.16 *
227 jsr166 1.43 * @param capacity the capacity of this queue
228 jsr166 1.51 * @throws IllegalArgumentException if {@code capacity} is not greater
229 jsr166 1.43 * than zero
230 dl 1.2 */
231     public LinkedBlockingQueue(int capacity) {
232 dholmes 1.8 if (capacity <= 0) throw new IllegalArgumentException();
233 dl 1.2 this.capacity = capacity;
234 dl 1.6 last = head = new Node<E>(null);
235 dl 1.2 }
236    
237     /**
238 jsr166 1.51 * Creates a {@code LinkedBlockingQueue} with a capacity of
239 dholmes 1.14 * {@link Integer#MAX_VALUE}, initially containing the elements of the
240 tim 1.12 * given collection,
241 dholmes 1.8 * added in traversal order of the collection's iterator.
242 jsr166 1.43 *
243 dholmes 1.9 * @param c the collection of elements to initially contain
244 jsr166 1.43 * @throws NullPointerException if the specified collection or any
245     * of its elements are null
246 dl 1.2 */
247 dholmes 1.10 public LinkedBlockingQueue(Collection<? extends E> c) {
248 dl 1.2 this(Integer.MAX_VALUE);
249 jsr166 1.51 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 dl 1.54 enqueue(new Node<E>(e));
259 jsr166 1.51 ++n;
260     }
261     count.set(n);
262     } finally {
263     putLock.unlock();
264     }
265 dl 1.2 }
266    
267 dholmes 1.8 // this doc comment is overridden to remove the reference to collections
268     // greater in size than Integer.MAX_VALUE
269 tim 1.12 /**
270 dl 1.20 * Returns the number of elements in this queue.
271     *
272 jsr166 1.43 * @return the number of elements in this queue
273 dholmes 1.8 */
274 dl 1.2 public int size() {
275     return count.get();
276 tim 1.1 }
277 dl 1.2
278 dholmes 1.8 // this doc comment is a modified copy of the inherited doc comment,
279     // without the reference to unlimited queues.
280 tim 1.12 /**
281 jsr166 1.41 * Returns the number of additional elements that this queue can ideally
282     * (in the absence of memory or resource constraints) accept without
283 dholmes 1.8 * blocking. This is always equal to the initial capacity of this queue
284 jsr166 1.51 * less the current {@code size} of this queue.
285 jsr166 1.41 *
286     * <p>Note that you <em>cannot</em> always tell if an attempt to insert
287 jsr166 1.51 * an element will succeed by inspecting {@code remainingCapacity}
288 jsr166 1.41 * because it may be the case that another thread is about to
289 jsr166 1.43 * insert or remove an element.
290 dholmes 1.8 */
291 dl 1.2 public int remainingCapacity() {
292     return capacity - count.get();
293     }
294    
295 dholmes 1.22 /**
296 jsr166 1.44 * Inserts the specified element at the tail of this queue, waiting if
297 dholmes 1.22 * necessary for space to become available.
298 jsr166 1.43 *
299     * @throws InterruptedException {@inheritDoc}
300     * @throws NullPointerException {@inheritDoc}
301 dholmes 1.22 */
302 jsr166 1.42 public void put(E e) throws InterruptedException {
303     if (e == null) throw new NullPointerException();
304 jsr166 1.51 // Note: convention in all put/take/etc is to preset local var
305     // holding count negative to indicate failure unless set.
306 tim 1.12 int c = -1;
307 jsr166 1.60 Node<E> node = new Node<E>(e);
308 dl 1.31 final ReentrantLock putLock = this.putLock;
309     final AtomicInteger count = this.count;
310 dl 1.2 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 jsr166 1.51 * signalled if it ever changes from capacity. Similarly
318     * for all other uses of count in other wait guards.
319 dl 1.2 */
320 jsr166 1.51 while (count.get() == capacity) {
321     notFull.await();
322 dl 1.2 }
323 dl 1.54 enqueue(node);
324 dl 1.2 c = count.getAndIncrement();
325 dl 1.6 if (c + 1 < capacity)
326 dl 1.2 notFull.signal();
327 tim 1.17 } finally {
328 dl 1.2 putLock.unlock();
329     }
330 tim 1.12 if (c == 0)
331 dl 1.2 signalNotEmpty();
332 tim 1.1 }
333 dl 1.2
334 dholmes 1.22 /**
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 jsr166 1.43 *
338 jsr166 1.51 * @return {@code true} if successful, or {@code false} if
339 jsr166 1.73 * the specified waiting time elapses before space is available
340 jsr166 1.43 * @throws InterruptedException {@inheritDoc}
341     * @throws NullPointerException {@inheritDoc}
342 dholmes 1.22 */
343 jsr166 1.42 public boolean offer(E e, long timeout, TimeUnit unit)
344 dholmes 1.8 throws InterruptedException {
345 tim 1.12
346 jsr166 1.42 if (e == null) throw new NullPointerException();
347 dl 1.2 long nanos = unit.toNanos(timeout);
348     int c = -1;
349 dl 1.31 final ReentrantLock putLock = this.putLock;
350     final AtomicInteger count = this.count;
351 dholmes 1.8 putLock.lockInterruptibly();
352 dl 1.2 try {
353 jsr166 1.51 while (count.get() == capacity) {
354 dl 1.2 if (nanos <= 0)
355     return false;
356 jsr166 1.51 nanos = notFull.awaitNanos(nanos);
357 dl 1.2 }
358 dl 1.54 enqueue(new Node<E>(e));
359 jsr166 1.51 c = count.getAndIncrement();
360     if (c + 1 < capacity)
361     notFull.signal();
362 tim 1.17 } finally {
363 dl 1.2 putLock.unlock();
364     }
365 tim 1.12 if (c == 0)
366 dl 1.2 signalNotEmpty();
367     return true;
368 tim 1.1 }
369 dl 1.2
370 dl 1.23 /**
371 jsr166 1.44 * 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 jsr166 1.51 * returning {@code true} upon success and {@code false} if this queue
374 jsr166 1.44 * 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 dl 1.23 *
379 jsr166 1.43 * @throws NullPointerException if the specified element is null
380 dl 1.23 */
381 jsr166 1.42 public boolean offer(E e) {
382     if (e == null) throw new NullPointerException();
383 dl 1.31 final AtomicInteger count = this.count;
384 dl 1.2 if (count.get() == capacity)
385     return false;
386 tim 1.12 int c = -1;
387 jsr166 1.60 Node<E> node = new Node<E>(e);
388 dl 1.31 final ReentrantLock putLock = this.putLock;
389 dholmes 1.8 putLock.lock();
390 dl 1.2 try {
391     if (count.get() < capacity) {
392 dl 1.54 enqueue(node);
393 dl 1.2 c = count.getAndIncrement();
394 dl 1.6 if (c + 1 < capacity)
395 dl 1.2 notFull.signal();
396     }
397 tim 1.17 } finally {
398 dl 1.2 putLock.unlock();
399     }
400 tim 1.12 if (c == 0)
401 dl 1.2 signalNotEmpty();
402     return c >= 0;
403 tim 1.1 }
404 dl 1.2
405     public E take() throws InterruptedException {
406     E x;
407     int c = -1;
408 dl 1.31 final AtomicInteger count = this.count;
409     final ReentrantLock takeLock = this.takeLock;
410 dl 1.2 takeLock.lockInterruptibly();
411     try {
412 jsr166 1.51 while (count.get() == 0) {
413     notEmpty.await();
414 dl 1.2 }
415 jsr166 1.51 x = dequeue();
416 dl 1.2 c = count.getAndDecrement();
417     if (c > 1)
418     notEmpty.signal();
419 tim 1.17 } finally {
420 dl 1.2 takeLock.unlock();
421     }
422 tim 1.12 if (c == capacity)
423 dl 1.2 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 dholmes 1.8 long nanos = unit.toNanos(timeout);
431 dl 1.31 final AtomicInteger count = this.count;
432     final ReentrantLock takeLock = this.takeLock;
433 dl 1.2 takeLock.lockInterruptibly();
434     try {
435 jsr166 1.51 while (count.get() == 0) {
436 dl 1.2 if (nanos <= 0)
437     return null;
438 jsr166 1.51 nanos = notEmpty.awaitNanos(nanos);
439 dl 1.2 }
440 jsr166 1.51 x = dequeue();
441     c = count.getAndDecrement();
442     if (c > 1)
443     notEmpty.signal();
444 tim 1.17 } finally {
445 dl 1.2 takeLock.unlock();
446     }
447 tim 1.12 if (c == capacity)
448 dl 1.2 signalNotFull();
449     return x;
450     }
451    
452     public E poll() {
453 dl 1.31 final AtomicInteger count = this.count;
454 dl 1.2 if (count.get() == 0)
455     return null;
456     E x = null;
457 tim 1.12 int c = -1;
458 dl 1.31 final ReentrantLock takeLock = this.takeLock;
459 dl 1.30 takeLock.lock();
460 dl 1.2 try {
461     if (count.get() > 0) {
462 jsr166 1.51 x = dequeue();
463 dl 1.2 c = count.getAndDecrement();
464     if (c > 1)
465     notEmpty.signal();
466     }
467 tim 1.17 } finally {
468 dl 1.2 takeLock.unlock();
469     }
470 tim 1.12 if (c == capacity)
471 dl 1.2 signalNotFull();
472     return x;
473 tim 1.1 }
474 dl 1.2
475     public E peek() {
476     if (count.get() == 0)
477     return null;
478 dl 1.31 final ReentrantLock takeLock = this.takeLock;
479 dholmes 1.8 takeLock.lock();
480 dl 1.2 try {
481     Node<E> first = head.next;
482     if (first == null)
483     return null;
484     else
485     return first.item;
486 tim 1.17 } finally {
487 dl 1.2 takeLock.unlock();
488     }
489 tim 1.1 }
490    
491 dl 1.35 /**
492 jsr166 1.51 * 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 jsr166 1.44 * Removes a single instance of the specified element from this queue,
508 jsr166 1.51 * 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 jsr166 1.44 * elements.
511 jsr166 1.51 * Returns {@code true} if this queue contained the specified element
512 jsr166 1.44 * (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 jsr166 1.51 * @return {@code true} if this queue changed as a result of the call
516 dl 1.35 */
517 dholmes 1.9 public boolean remove(Object o) {
518     if (o == null) return false;
519 dl 1.2 fullyLock();
520     try {
521 jsr166 1.51 for (Node<E> trail = head, p = trail.next;
522     p != null;
523     trail = p, p = p.next) {
524 dholmes 1.9 if (o.equals(p.item)) {
525 jsr166 1.51 unlink(p, trail);
526     return true;
527 dl 1.2 }
528     }
529 jsr166 1.51 return false;
530 tim 1.17 } finally {
531 dl 1.2 fullyUnlock();
532     }
533 tim 1.1 }
534 dl 1.2
535 jsr166 1.43 /**
536 jsr166 1.56 * 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 jsr166 1.43 * 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 jsr166 1.45 *
564 jsr166 1.43 * <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 dl 1.2 public Object[] toArray() {
570     fullyLock();
571     try {
572     int size = count.get();
573 tim 1.12 Object[] a = new Object[size];
574 dl 1.2 int k = 0;
575 tim 1.12 for (Node<E> p = head.next; p != null; p = p.next)
576 dl 1.2 a[k++] = p.item;
577     return a;
578 tim 1.17 } finally {
579 dl 1.2 fullyUnlock();
580     }
581 tim 1.1 }
582 dl 1.2
583 jsr166 1.43 /**
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 jsr166 1.51 * {@code null}.
594 jsr166 1.43 *
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 jsr166 1.51 * <p>Suppose {@code x} is a queue known to contain only strings.
601 jsr166 1.43 * The following code can be used to dump the queue into a newly
602 jsr166 1.51 * allocated array of {@code String}:
603 jsr166 1.43 *
604 jsr166 1.92 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
605 jsr166 1.43 *
606 jsr166 1.51 * Note that {@code toArray(new Object[0])} is identical in function to
607     * {@code toArray()}.
608 jsr166 1.43 *
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 jsr166 1.51 @SuppressWarnings("unchecked")
619 dl 1.2 public <T> T[] toArray(T[] a) {
620     fullyLock();
621     try {
622     int size = count.get();
623     if (a.length < size)
624 dl 1.4 a = (T[])java.lang.reflect.Array.newInstance
625     (a.getClass().getComponentType(), size);
626 tim 1.12
627 dl 1.2 int k = 0;
628 jsr166 1.51 for (Node<E> p = head.next; p != null; p = p.next)
629 dl 1.2 a[k++] = (T)p.item;
630 jsr166 1.47 if (a.length > k)
631     a[k] = null;
632 dl 1.2 return a;
633 tim 1.17 } finally {
634 dl 1.2 fullyUnlock();
635     }
636 tim 1.1 }
637 dl 1.2
638     public String toString() {
639     fullyLock();
640     try {
641 jsr166 1.55 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 tim 1.17 } finally {
656 dl 1.2 fullyUnlock();
657     }
658 tim 1.1 }
659 dl 1.2
660 dl 1.35 /**
661     * Atomically removes all of the elements from this queue.
662     * The queue will be empty after this call returns.
663     */
664 dl 1.24 public void clear() {
665     fullyLock();
666     try {
667 jsr166 1.51 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 dl 1.24 if (count.getAndSet(0) == capacity)
674 jsr166 1.51 notFull.signal();
675 dl 1.24 } finally {
676     fullyUnlock();
677     }
678     }
679    
680 jsr166 1.43 /**
681     * @throws UnsupportedOperationException {@inheritDoc}
682     * @throws ClassCastException {@inheritDoc}
683     * @throws NullPointerException {@inheritDoc}
684     * @throws IllegalArgumentException {@inheritDoc}
685     */
686 dl 1.24 public int drainTo(Collection<? super E> c) {
687 jsr166 1.51 return drainTo(c, Integer.MAX_VALUE);
688 dl 1.24 }
689 jsr166 1.40
690 jsr166 1.43 /**
691     * @throws UnsupportedOperationException {@inheritDoc}
692     * @throws ClassCastException {@inheritDoc}
693     * @throws NullPointerException {@inheritDoc}
694     * @throws IllegalArgumentException {@inheritDoc}
695     */
696 dl 1.24 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 jsr166 1.63 if (maxElements <= 0)
702     return 0;
703 jsr166 1.51 boolean signalNotFull = false;
704     final ReentrantLock takeLock = this.takeLock;
705     takeLock.lock();
706 dl 1.24 try {
707 jsr166 1.51 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 dl 1.24 }
729     } finally {
730 jsr166 1.51 takeLock.unlock();
731     if (signalNotFull)
732     signalNotFull();
733 dl 1.24 }
734     }
735    
736 dholmes 1.14 /**
737     * Returns an iterator over the elements in this queue in proper sequence.
738 jsr166 1.57 * The elements will be returned in order from first (head) to last (tail).
739     *
740 jsr166 1.87 * <p>The returned iterator is
741     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
742 dholmes 1.14 *
743 jsr166 1.43 * @return an iterator over the elements in this queue in proper sequence
744 dholmes 1.14 */
745 dl 1.2 public Iterator<E> iterator() {
746 jsr166 1.59 return new Itr();
747 tim 1.1 }
748 dl 1.2
749     private class Itr implements Iterator<E> {
750 tim 1.12 /*
751 jsr166 1.51 * Basic weakly-consistent iterator. At all times hold the next
752 dl 1.4 * 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 jsr166 1.72
756 dl 1.31 private Node<E> current;
757     private Node<E> lastRet;
758     private E currentElement;
759 tim 1.12
760 dl 1.2 Itr() {
761 jsr166 1.51 fullyLock();
762 dl 1.2 try {
763     current = head.next;
764 dl 1.4 if (current != null)
765     currentElement = current.item;
766 tim 1.17 } finally {
767 jsr166 1.51 fullyUnlock();
768 dl 1.2 }
769     }
770 tim 1.12
771     public boolean hasNext() {
772 dl 1.2 return current != null;
773     }
774    
775 tim 1.12 public E next() {
776 jsr166 1.51 fullyLock();
777 dl 1.2 try {
778     if (current == null)
779     throw new NoSuchElementException();
780     lastRet = current;
781 jsr166 1.91 E item = null;
782     // Unlike other traversal methods, iterators must handle both:
783     // - dequeued nodes (p.next == p)
784     // - (possibly multiple) interior removed nodes (p.item == null)
785     for (Node<E> p = current, q;; p = q) {
786     if ((q = p.next) == p)
787     q = head.next;
788     if (q == null || (item = q.item) != null) {
789     current = q;
790     E x = currentElement;
791     currentElement = item;
792     return x;
793     }
794     }
795 tim 1.17 } finally {
796 jsr166 1.51 fullyUnlock();
797 dl 1.2 }
798     }
799    
800 tim 1.12 public void remove() {
801 dl 1.2 if (lastRet == null)
802 tim 1.12 throw new IllegalStateException();
803 jsr166 1.51 fullyLock();
804 dl 1.2 try {
805     Node<E> node = lastRet;
806     lastRet = null;
807 jsr166 1.51 for (Node<E> trail = head, p = trail.next;
808     p != null;
809     trail = p, p = p.next) {
810     if (p == node) {
811     unlink(p, trail);
812     break;
813     }
814 dl 1.2 }
815 tim 1.17 } finally {
816 jsr166 1.51 fullyUnlock();
817 dl 1.2 }
818     }
819 tim 1.1 }
820 dl 1.2
821 dl 1.77 /** A customized variant of Spliterators.IteratorSpliterator */
822 dl 1.74 static final class LBQSpliterator<E> implements Spliterator<E> {
823 dl 1.80 static final int MAX_BATCH = 1 << 25; // max batch array size;
824 dl 1.74 final LinkedBlockingQueue<E> queue;
825     Node<E> current; // current node; null until initialized
826     int batch; // batch size for splits
827     boolean exhausted; // true when no more nodes
828     long est; // size estimate
829     LBQSpliterator(LinkedBlockingQueue<E> queue) {
830     this.queue = queue;
831     this.est = queue.size();
832     }
833    
834     public long estimateSize() { return est; }
835    
836     public Spliterator<E> trySplit() {
837 dl 1.80 Node<E> h;
838 dl 1.74 final LinkedBlockingQueue<E> q = this.queue;
839 dl 1.80 int b = batch;
840     int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
841 jsr166 1.78 if (!exhausted &&
842 dl 1.80 ((h = current) != null || (h = q.head.next) != null) &&
843     h.next != null) {
844 dl 1.83 Object[] a = new Object[n];
845 dl 1.74 int i = 0;
846     Node<E> p = current;
847     q.fullyLock();
848     try {
849     if (p != null || (p = q.head.next) != null) {
850     do {
851     if ((a[i] = p.item) != null)
852     ++i;
853     } while ((p = p.next) != null && i < n);
854     }
855     } finally {
856     q.fullyUnlock();
857     }
858     if ((current = p) == null) {
859     est = 0L;
860     exhausted = true;
861     }
862 dl 1.77 else if ((est -= i) < 0L)
863     est = 0L;
864 dl 1.80 if (i > 0) {
865     batch = i;
866     return Spliterators.spliterator
867     (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
868     Spliterator.CONCURRENT);
869     }
870 dl 1.74 }
871     return null;
872     }
873    
874 dl 1.81 public void forEachRemaining(Consumer<? super E> action) {
875 dl 1.74 if (action == null) throw new NullPointerException();
876     final LinkedBlockingQueue<E> q = this.queue;
877     if (!exhausted) {
878     exhausted = true;
879     Node<E> p = current;
880     do {
881     E e = null;
882     q.fullyLock();
883     try {
884     if (p == null)
885     p = q.head.next;
886     while (p != null) {
887     e = p.item;
888     p = p.next;
889     if (e != null)
890     break;
891     }
892     } finally {
893     q.fullyUnlock();
894     }
895     if (e != null)
896     action.accept(e);
897     } while (p != null);
898     }
899     }
900    
901     public boolean tryAdvance(Consumer<? super E> action) {
902     if (action == null) throw new NullPointerException();
903     final LinkedBlockingQueue<E> q = this.queue;
904     if (!exhausted) {
905     E e = null;
906     q.fullyLock();
907     try {
908     if (current == null)
909     current = q.head.next;
910     while (current != null) {
911     e = current.item;
912     current = current.next;
913     if (e != null)
914     break;
915     }
916     } finally {
917     q.fullyUnlock();
918     }
919 dl 1.76 if (current == null)
920     exhausted = true;
921 dl 1.74 if (e != null) {
922     action.accept(e);
923     return true;
924     }
925     }
926     return false;
927     }
928    
929     public int characteristics() {
930     return Spliterator.ORDERED | Spliterator.NONNULL |
931     Spliterator.CONCURRENT;
932     }
933     }
934    
935 jsr166 1.86 /**
936     * Returns a {@link Spliterator} over the elements in this queue.
937     *
938 jsr166 1.87 * <p>The returned spliterator is
939     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
940     *
941 jsr166 1.86 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
942     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
943     *
944     * @implNote
945     * The {@code Spliterator} implements {@code trySplit} to permit limited
946     * parallelism.
947     *
948     * @return a {@code Spliterator} over the elements in this queue
949     * @since 1.8
950     */
951 dl 1.76 public Spliterator<E> spliterator() {
952 dl 1.74 return new LBQSpliterator<E>(this);
953     }
954    
955 dl 1.2 /**
956 jsr166 1.68 * Saves this queue to a stream (that is, serializes it).
957 dl 1.2 *
958 jsr166 1.84 * @param s the stream
959 jsr166 1.85 * @throws java.io.IOException if an I/O error occurs
960 dl 1.2 * @serialData The capacity is emitted (int), followed by all of
961 jsr166 1.51 * its elements (each an {@code Object}) in the proper order,
962 dl 1.2 * followed by a null
963     */
964     private void writeObject(java.io.ObjectOutputStream s)
965     throws java.io.IOException {
966    
967 tim 1.12 fullyLock();
968 dl 1.2 try {
969     // Write out any hidden stuff, plus capacity
970     s.defaultWriteObject();
971    
972     // Write out all elements in the proper order.
973 tim 1.12 for (Node<E> p = head.next; p != null; p = p.next)
974 dl 1.2 s.writeObject(p.item);
975    
976     // Use trailing null as sentinel
977     s.writeObject(null);
978 tim 1.17 } finally {
979 dl 1.2 fullyUnlock();
980     }
981 tim 1.1 }
982    
983 dl 1.2 /**
984 jsr166 1.65 * Reconstitutes this queue from a stream (that is, deserializes it).
985 jsr166 1.84 * @param s the stream
986 jsr166 1.85 * @throws ClassNotFoundException if the class of a serialized object
987     * could not be found
988     * @throws java.io.IOException if an I/O error occurs
989 dl 1.2 */
990     private void readObject(java.io.ObjectInputStream s)
991     throws java.io.IOException, ClassNotFoundException {
992 tim 1.12 // Read in capacity, and any hidden stuff
993     s.defaultReadObject();
994 dl 1.2
995 dl 1.19 count.set(0);
996     last = head = new Node<E>(null);
997    
998 dl 1.6 // Read in all elements and place in queue
999 dl 1.2 for (;;) {
1000 jsr166 1.51 @SuppressWarnings("unchecked")
1001 dl 1.2 E item = (E)s.readObject();
1002     if (item == null)
1003     break;
1004     add(item);
1005     }
1006 tim 1.1 }
1007     }