ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingQueue.java
Revision: 1.74
Committed: Sun Feb 17 23:36:34 2013 UTC (11 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.73: +123 -0 lines
Log Message:
Spliterator sync

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