ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingQueue.java
Revision: 1.106
Committed: Wed Dec 28 04:52:39 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.105: +3 -1 lines
Log Message:
succ: bytecode golf

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