ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingQueue.java
Revision: 1.113
Committed: Tue Jan 30 19:00:33 2018 UTC (6 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.112: +25 -26 lines
Log Message:
rely on blank finals and definite assignment in offer/poll methods

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 jsr166 1.107 import java.util.function.Predicate;
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 jsr166 1.109 * <p>This class and its iterator implement all of the <em>optional</em>
42     * methods of the {@link Collection} and {@link Iterator} interfaces.
43 dl 1.21 *
44 dl 1.34 * <p>This class is a member of the
45 jsr166 1.111 * <a href="{@docRoot}/java/util/package-summary.html#CollectionsFramework">
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.113 final int c;
298     final Node<E> node = new Node<E>(e);
299 dl 1.31 final ReentrantLock putLock = this.putLock;
300     final AtomicInteger count = this.count;
301 dl 1.2 putLock.lockInterruptibly();
302     try {
303     /*
304     * Note that count is used in wait guard even though it is
305     * not protected by lock. This works because count can
306     * only decrease at this point (all other puts are shut
307     * out by lock), and we (or some other waiting put) are
308 jsr166 1.51 * signalled if it ever changes from capacity. Similarly
309     * for all other uses of count in other wait guards.
310 dl 1.2 */
311 jsr166 1.51 while (count.get() == capacity) {
312     notFull.await();
313 dl 1.2 }
314 dl 1.54 enqueue(node);
315 dl 1.2 c = count.getAndIncrement();
316 dl 1.6 if (c + 1 < capacity)
317 dl 1.2 notFull.signal();
318 tim 1.17 } finally {
319 dl 1.2 putLock.unlock();
320     }
321 tim 1.12 if (c == 0)
322 dl 1.2 signalNotEmpty();
323 tim 1.1 }
324 dl 1.2
325 dholmes 1.22 /**
326     * Inserts the specified element at the tail of this queue, waiting if
327     * necessary up to the specified wait time for space to become available.
328 jsr166 1.43 *
329 jsr166 1.51 * @return {@code true} if successful, or {@code false} if
330 jsr166 1.73 * the specified waiting time elapses before space is available
331 jsr166 1.43 * @throws InterruptedException {@inheritDoc}
332     * @throws NullPointerException {@inheritDoc}
333 dholmes 1.22 */
334 jsr166 1.42 public boolean offer(E e, long timeout, TimeUnit unit)
335 dholmes 1.8 throws InterruptedException {
336 tim 1.12
337 jsr166 1.42 if (e == null) throw new NullPointerException();
338 dl 1.2 long nanos = unit.toNanos(timeout);
339 jsr166 1.113 final int c;
340 dl 1.31 final ReentrantLock putLock = this.putLock;
341     final AtomicInteger count = this.count;
342 dholmes 1.8 putLock.lockInterruptibly();
343 dl 1.2 try {
344 jsr166 1.51 while (count.get() == capacity) {
345 jsr166 1.98 if (nanos <= 0L)
346 dl 1.2 return false;
347 jsr166 1.51 nanos = notFull.awaitNanos(nanos);
348 dl 1.2 }
349 dl 1.54 enqueue(new Node<E>(e));
350 jsr166 1.51 c = count.getAndIncrement();
351     if (c + 1 < capacity)
352     notFull.signal();
353 tim 1.17 } finally {
354 dl 1.2 putLock.unlock();
355     }
356 tim 1.12 if (c == 0)
357 dl 1.2 signalNotEmpty();
358     return true;
359 tim 1.1 }
360 dl 1.2
361 dl 1.23 /**
362 jsr166 1.44 * Inserts the specified element at the tail of this queue if it is
363     * possible to do so immediately without exceeding the queue's capacity,
364 jsr166 1.51 * returning {@code true} upon success and {@code false} if this queue
365 jsr166 1.44 * is full.
366     * When using a capacity-restricted queue, this method is generally
367     * preferable to method {@link BlockingQueue#add add}, which can fail to
368     * insert an element only by throwing an exception.
369 dl 1.23 *
370 jsr166 1.43 * @throws NullPointerException if the specified element is null
371 dl 1.23 */
372 jsr166 1.42 public boolean offer(E e) {
373     if (e == null) throw new NullPointerException();
374 dl 1.31 final AtomicInteger count = this.count;
375 dl 1.2 if (count.get() == capacity)
376     return false;
377 jsr166 1.113 final int c;
378     final Node<E> node = new Node<E>(e);
379 dl 1.31 final ReentrantLock putLock = this.putLock;
380 dholmes 1.8 putLock.lock();
381 dl 1.2 try {
382 jsr166 1.113 if (count.get() == capacity)
383     return false;
384     enqueue(node);
385     c = count.getAndIncrement();
386     if (c + 1 < capacity)
387     notFull.signal();
388 tim 1.17 } finally {
389 dl 1.2 putLock.unlock();
390     }
391 tim 1.12 if (c == 0)
392 dl 1.2 signalNotEmpty();
393 jsr166 1.113 return true;
394 tim 1.1 }
395 dl 1.2
396     public E take() throws InterruptedException {
397 jsr166 1.113 final E x;
398     final int c;
399 dl 1.31 final AtomicInteger count = this.count;
400     final ReentrantLock takeLock = this.takeLock;
401 dl 1.2 takeLock.lockInterruptibly();
402     try {
403 jsr166 1.51 while (count.get() == 0) {
404     notEmpty.await();
405 dl 1.2 }
406 jsr166 1.51 x = dequeue();
407 dl 1.2 c = count.getAndDecrement();
408     if (c > 1)
409     notEmpty.signal();
410 tim 1.17 } finally {
411 dl 1.2 takeLock.unlock();
412     }
413 tim 1.12 if (c == capacity)
414 dl 1.2 signalNotFull();
415     return x;
416     }
417    
418     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
419 jsr166 1.113 final E x;
420     final int c;
421 dholmes 1.8 long nanos = unit.toNanos(timeout);
422 dl 1.31 final AtomicInteger count = this.count;
423     final ReentrantLock takeLock = this.takeLock;
424 dl 1.2 takeLock.lockInterruptibly();
425     try {
426 jsr166 1.51 while (count.get() == 0) {
427 jsr166 1.98 if (nanos <= 0L)
428 dl 1.2 return null;
429 jsr166 1.51 nanos = notEmpty.awaitNanos(nanos);
430 dl 1.2 }
431 jsr166 1.51 x = dequeue();
432     c = count.getAndDecrement();
433     if (c > 1)
434     notEmpty.signal();
435 tim 1.17 } finally {
436 dl 1.2 takeLock.unlock();
437     }
438 tim 1.12 if (c == capacity)
439 dl 1.2 signalNotFull();
440     return x;
441     }
442    
443     public E poll() {
444 dl 1.31 final AtomicInteger count = this.count;
445 dl 1.2 if (count.get() == 0)
446     return null;
447 jsr166 1.113 final E x;
448     final int c;
449 dl 1.31 final ReentrantLock takeLock = this.takeLock;
450 dl 1.30 takeLock.lock();
451 dl 1.2 try {
452 jsr166 1.113 if (count.get() == 0)
453     return null;
454     x = dequeue();
455     c = count.getAndDecrement();
456     if (c > 1)
457     notEmpty.signal();
458 tim 1.17 } finally {
459 dl 1.2 takeLock.unlock();
460     }
461 tim 1.12 if (c == capacity)
462 dl 1.2 signalNotFull();
463     return x;
464 tim 1.1 }
465 dl 1.2
466     public E peek() {
467 jsr166 1.113 final AtomicInteger count = this.count;
468 dl 1.2 if (count.get() == 0)
469     return null;
470 dl 1.31 final ReentrantLock takeLock = this.takeLock;
471 dholmes 1.8 takeLock.lock();
472 dl 1.2 try {
473 jsr166 1.96 return (count.get() > 0) ? head.next.item : null;
474 tim 1.17 } finally {
475 dl 1.2 takeLock.unlock();
476     }
477 tim 1.1 }
478    
479 dl 1.35 /**
480 jsr166 1.105 * Unlinks interior Node p with predecessor pred.
481 jsr166 1.51 */
482 jsr166 1.105 void unlink(Node<E> p, Node<E> pred) {
483 jsr166 1.100 // assert putLock.isHeldByCurrentThread();
484     // assert takeLock.isHeldByCurrentThread();
485 jsr166 1.51 // p.next is not changed, to allow iterators that are
486     // traversing p to maintain their weak-consistency guarantee.
487     p.item = null;
488 jsr166 1.105 pred.next = p.next;
489 jsr166 1.51 if (last == p)
490 jsr166 1.105 last = pred;
491 jsr166 1.51 if (count.getAndDecrement() == capacity)
492     notFull.signal();
493     }
494    
495     /**
496 jsr166 1.44 * Removes a single instance of the specified element from this queue,
497 jsr166 1.51 * if it is present. More formally, removes an element {@code e} such
498     * that {@code o.equals(e)}, if this queue contains one or more such
499 jsr166 1.44 * elements.
500 jsr166 1.51 * Returns {@code true} if this queue contained the specified element
501 jsr166 1.44 * (or equivalently, if this queue changed as a result of the call).
502     *
503     * @param o element to be removed from this queue, if present
504 jsr166 1.51 * @return {@code true} if this queue changed as a result of the call
505 dl 1.35 */
506 dholmes 1.9 public boolean remove(Object o) {
507     if (o == null) return false;
508 dl 1.2 fullyLock();
509     try {
510 jsr166 1.105 for (Node<E> pred = head, p = pred.next;
511 jsr166 1.51 p != null;
512 jsr166 1.105 pred = p, p = p.next) {
513 dholmes 1.9 if (o.equals(p.item)) {
514 jsr166 1.105 unlink(p, pred);
515 jsr166 1.51 return true;
516 dl 1.2 }
517     }
518 jsr166 1.51 return false;
519 tim 1.17 } finally {
520 dl 1.2 fullyUnlock();
521     }
522 tim 1.1 }
523 dl 1.2
524 jsr166 1.43 /**
525 jsr166 1.56 * Returns {@code true} if this queue contains the specified element.
526     * More formally, returns {@code true} if and only if this queue contains
527     * at least one element {@code e} such that {@code o.equals(e)}.
528     *
529     * @param o object to be checked for containment in this queue
530     * @return {@code true} if this queue contains the specified element
531     */
532     public boolean contains(Object o) {
533     if (o == null) return false;
534     fullyLock();
535     try {
536     for (Node<E> p = head.next; p != null; p = p.next)
537     if (o.equals(p.item))
538     return true;
539     return false;
540     } finally {
541     fullyUnlock();
542     }
543     }
544    
545     /**
546 jsr166 1.43 * Returns an array containing all of the elements in this queue, in
547     * proper sequence.
548     *
549     * <p>The returned array will be "safe" in that no references to it are
550     * maintained by this queue. (In other words, this method must allocate
551     * a new array). The caller is thus free to modify the returned array.
552 jsr166 1.45 *
553 jsr166 1.43 * <p>This method acts as bridge between array-based and collection-based
554     * APIs.
555     *
556     * @return an array containing all of the elements in this queue
557     */
558 dl 1.2 public Object[] toArray() {
559     fullyLock();
560     try {
561     int size = count.get();
562 tim 1.12 Object[] a = new Object[size];
563 dl 1.2 int k = 0;
564 tim 1.12 for (Node<E> p = head.next; p != null; p = p.next)
565 dl 1.2 a[k++] = p.item;
566     return a;
567 tim 1.17 } finally {
568 dl 1.2 fullyUnlock();
569     }
570 tim 1.1 }
571 dl 1.2
572 jsr166 1.43 /**
573     * Returns an array containing all of the elements in this queue, in
574     * proper sequence; the runtime type of the returned array is that of
575     * the specified array. If the queue fits in the specified array, it
576     * is returned therein. Otherwise, a new array is allocated with the
577     * runtime type of the specified array and the size of this queue.
578     *
579     * <p>If this queue fits in the specified array with room to spare
580     * (i.e., the array has more elements than this queue), the element in
581     * the array immediately following the end of the queue is set to
582 jsr166 1.51 * {@code null}.
583 jsr166 1.43 *
584     * <p>Like the {@link #toArray()} method, this method acts as bridge between
585     * array-based and collection-based APIs. Further, this method allows
586     * precise control over the runtime type of the output array, and may,
587     * under certain circumstances, be used to save allocation costs.
588     *
589 jsr166 1.51 * <p>Suppose {@code x} is a queue known to contain only strings.
590 jsr166 1.43 * The following code can be used to dump the queue into a newly
591 jsr166 1.51 * allocated array of {@code String}:
592 jsr166 1.43 *
593 jsr166 1.92 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
594 jsr166 1.43 *
595 jsr166 1.51 * Note that {@code toArray(new Object[0])} is identical in function to
596     * {@code toArray()}.
597 jsr166 1.43 *
598     * @param a the array into which the elements of the queue are to
599     * be stored, if it is big enough; otherwise, a new array of the
600     * same runtime type is allocated for this purpose
601     * @return an array containing all of the elements in this queue
602     * @throws ArrayStoreException if the runtime type of the specified array
603     * is not a supertype of the runtime type of every element in
604     * this queue
605     * @throws NullPointerException if the specified array is null
606     */
607 jsr166 1.51 @SuppressWarnings("unchecked")
608 dl 1.2 public <T> T[] toArray(T[] a) {
609     fullyLock();
610     try {
611     int size = count.get();
612     if (a.length < size)
613 dl 1.4 a = (T[])java.lang.reflect.Array.newInstance
614     (a.getClass().getComponentType(), size);
615 tim 1.12
616 dl 1.2 int k = 0;
617 jsr166 1.51 for (Node<E> p = head.next; p != null; p = p.next)
618 dl 1.2 a[k++] = (T)p.item;
619 jsr166 1.47 if (a.length > k)
620     a[k] = null;
621 dl 1.2 return a;
622 tim 1.17 } finally {
623 dl 1.2 fullyUnlock();
624     }
625 tim 1.1 }
626 dl 1.2
627     public String toString() {
628 jsr166 1.94 return Helpers.collectionToString(this);
629 tim 1.1 }
630 dl 1.2
631 dl 1.35 /**
632     * Atomically removes all of the elements from this queue.
633     * The queue will be empty after this call returns.
634     */
635 dl 1.24 public void clear() {
636     fullyLock();
637     try {
638 jsr166 1.51 for (Node<E> p, h = head; (p = h.next) != null; h = p) {
639     h.next = h;
640     p.item = null;
641     }
642     head = last;
643     // assert head.item == null && head.next == null;
644 dl 1.24 if (count.getAndSet(0) == capacity)
645 jsr166 1.51 notFull.signal();
646 dl 1.24 } finally {
647     fullyUnlock();
648     }
649     }
650    
651 jsr166 1.43 /**
652     * @throws UnsupportedOperationException {@inheritDoc}
653     * @throws ClassCastException {@inheritDoc}
654     * @throws NullPointerException {@inheritDoc}
655     * @throws IllegalArgumentException {@inheritDoc}
656     */
657 dl 1.24 public int drainTo(Collection<? super E> c) {
658 jsr166 1.51 return drainTo(c, Integer.MAX_VALUE);
659 dl 1.24 }
660 jsr166 1.40
661 jsr166 1.43 /**
662     * @throws UnsupportedOperationException {@inheritDoc}
663     * @throws ClassCastException {@inheritDoc}
664     * @throws NullPointerException {@inheritDoc}
665     * @throws IllegalArgumentException {@inheritDoc}
666     */
667 dl 1.24 public int drainTo(Collection<? super E> c, int maxElements) {
668 jsr166 1.101 Objects.requireNonNull(c);
669 dl 1.24 if (c == this)
670     throw new IllegalArgumentException();
671 jsr166 1.63 if (maxElements <= 0)
672     return 0;
673 jsr166 1.51 boolean signalNotFull = false;
674     final ReentrantLock takeLock = this.takeLock;
675     takeLock.lock();
676 dl 1.24 try {
677 jsr166 1.51 int n = Math.min(maxElements, count.get());
678     // count.get provides visibility to first n Nodes
679     Node<E> h = head;
680     int i = 0;
681     try {
682     while (i < n) {
683     Node<E> p = h.next;
684     c.add(p.item);
685     p.item = null;
686     h.next = h;
687     h = p;
688     ++i;
689     }
690     return n;
691     } finally {
692     // Restore invariants even if c.add() threw
693     if (i > 0) {
694     // assert h.item == null;
695     head = h;
696     signalNotFull = (count.getAndAdd(-i) == capacity);
697     }
698 dl 1.24 }
699     } finally {
700 jsr166 1.51 takeLock.unlock();
701     if (signalNotFull)
702     signalNotFull();
703 dl 1.24 }
704     }
705    
706 dholmes 1.14 /**
707 jsr166 1.101 * Used for any element traversal that is not entirely under lock.
708     * Such traversals must handle both:
709     * - dequeued nodes (p.next == p)
710     * - (possibly multiple) interior removed nodes (p.item == null)
711     */
712     Node<E> succ(Node<E> p) {
713 jsr166 1.106 if (p == (p = p.next))
714     p = head.next;
715     return p;
716 jsr166 1.101 }
717    
718     /**
719 dholmes 1.14 * Returns an iterator over the elements in this queue in proper sequence.
720 jsr166 1.57 * The elements will be returned in order from first (head) to last (tail).
721     *
722 jsr166 1.87 * <p>The returned iterator is
723     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
724 dholmes 1.14 *
725 jsr166 1.43 * @return an iterator over the elements in this queue in proper sequence
726 dholmes 1.14 */
727 dl 1.2 public Iterator<E> iterator() {
728 jsr166 1.59 return new Itr();
729 tim 1.1 }
730 dl 1.2
731 jsr166 1.108 /**
732     * Weakly-consistent iterator.
733     *
734     * Lazily updated ancestor field provides expected O(1) remove(),
735     * but still O(n) in the worst case, whenever the saved ancestor
736     * is concurrently deleted.
737     */
738 dl 1.2 private class Itr implements Iterator<E> {
739 jsr166 1.108 private Node<E> next; // Node holding nextItem
740     private E nextItem; // next item to hand out
741 dl 1.31 private Node<E> lastRet;
742 jsr166 1.108 private Node<E> ancestor; // Helps unlink lastRet on remove()
743 tim 1.12
744 dl 1.2 Itr() {
745 jsr166 1.51 fullyLock();
746 dl 1.2 try {
747 jsr166 1.102 if ((next = head.next) != null)
748     nextItem = next.item;
749 tim 1.17 } finally {
750 jsr166 1.51 fullyUnlock();
751 dl 1.2 }
752     }
753 tim 1.12
754     public boolean hasNext() {
755 jsr166 1.102 return next != null;
756 dl 1.2 }
757    
758 tim 1.12 public E next() {
759 jsr166 1.101 Node<E> p;
760 jsr166 1.102 if ((p = next) == null)
761 jsr166 1.100 throw new NoSuchElementException();
762 jsr166 1.101 lastRet = p;
763 jsr166 1.102 E x = nextItem;
764 jsr166 1.51 fullyLock();
765 dl 1.2 try {
766 jsr166 1.102 E e = null;
767     for (p = p.next; p != null && (e = p.item) == null; )
768     p = succ(p);
769     next = p;
770     nextItem = e;
771 tim 1.17 } finally {
772 jsr166 1.51 fullyUnlock();
773 dl 1.2 }
774 jsr166 1.102 return x;
775 jsr166 1.101 }
776    
777     public void forEachRemaining(Consumer<? super E> action) {
778     // A variant of forEachFrom
779     Objects.requireNonNull(action);
780     Node<E> p;
781 jsr166 1.102 if ((p = next) == null) return;
782     lastRet = p;
783     next = null;
784 jsr166 1.110 final int batchSize = 64;
785 jsr166 1.101 Object[] es = null;
786     int n, len = 1;
787     do {
788     fullyLock();
789     try {
790     if (es == null) {
791     p = p.next;
792     for (Node<E> q = p; q != null; q = succ(q))
793     if (q.item != null && ++len == batchSize)
794     break;
795     es = new Object[len];
796 jsr166 1.102 es[0] = nextItem;
797     nextItem = null;
798 jsr166 1.101 n = 1;
799     } else
800     n = 0;
801     for (; p != null && n < len; p = succ(p))
802     if ((es[n] = p.item) != null) {
803     lastRet = p;
804     n++;
805     }
806     } finally {
807     fullyUnlock();
808     }
809     for (int i = 0; i < n; i++) {
810     @SuppressWarnings("unchecked") E e = (E) es[i];
811     action.accept(e);
812     }
813     } while (n > 0 && p != null);
814 dl 1.2 }
815    
816 tim 1.12 public void remove() {
817 jsr166 1.108 Node<E> p = lastRet;
818     if (p == null)
819 tim 1.12 throw new IllegalStateException();
820 jsr166 1.108 lastRet = null;
821 jsr166 1.51 fullyLock();
822 dl 1.2 try {
823 jsr166 1.108 if (p.item != null) {
824     if (ancestor == null)
825     ancestor = head;
826     ancestor = findPred(p, ancestor);
827     unlink(p, ancestor);
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 jsr166 1.100 /**
836     * A customized variant of Spliterators.IteratorSpliterator.
837     * Keep this class in sync with (very similar) LBDSpliterator.
838     */
839     private final class LBQSpliterator implements Spliterator<E> {
840 dl 1.80 static final int MAX_BATCH = 1 << 25; // max batch array size;
841 dl 1.74 Node<E> current; // current node; null until initialized
842     int batch; // batch size for splits
843     boolean exhausted; // true when no more nodes
844 jsr166 1.100 long est = size(); // size estimate
845 jsr166 1.99
846 jsr166 1.100 LBQSpliterator() {}
847    
848 dl 1.74 public long estimateSize() { return est; }
849    
850     public Spliterator<E> trySplit() {
851 dl 1.80 Node<E> h;
852 jsr166 1.78 if (!exhausted &&
853 jsr166 1.100 ((h = current) != null || (h = head.next) != null)
854     && h.next != null) {
855 jsr166 1.104 int n = batch = Math.min(batch + 1, MAX_BATCH);
856 dl 1.83 Object[] a = new Object[n];
857 dl 1.74 int i = 0;
858     Node<E> p = current;
859 jsr166 1.99 fullyLock();
860 dl 1.74 try {
861 jsr166 1.100 if (p != null || (p = head.next) != null)
862     for (; p != null && i < n; p = succ(p))
863 dl 1.74 if ((a[i] = p.item) != null)
864 jsr166 1.100 i++;
865 dl 1.74 } finally {
866 jsr166 1.99 fullyUnlock();
867 dl 1.74 }
868     if ((current = p) == null) {
869     est = 0L;
870     exhausted = true;
871     }
872 dl 1.77 else if ((est -= i) < 0L)
873     est = 0L;
874 jsr166 1.104 if (i > 0)
875 dl 1.80 return Spliterators.spliterator
876 jsr166 1.95 (a, 0, i, (Spliterator.ORDERED |
877     Spliterator.NONNULL |
878     Spliterator.CONCURRENT));
879 dl 1.74 }
880     return null;
881     }
882    
883     public boolean tryAdvance(Consumer<? super E> action) {
884 jsr166 1.101 Objects.requireNonNull(action);
885 dl 1.74 if (!exhausted) {
886     E e = null;
887 jsr166 1.99 fullyLock();
888 dl 1.74 try {
889 jsr166 1.102 Node<E> p;
890     if ((p = current) != null || (p = head.next) != null)
891 jsr166 1.100 do {
892     e = p.item;
893     p = succ(p);
894     } while (e == null && p != null);
895 jsr166 1.103 if ((current = p) == null)
896     exhausted = true;
897 dl 1.74 } finally {
898 jsr166 1.99 fullyUnlock();
899 dl 1.74 }
900     if (e != null) {
901     action.accept(e);
902     return true;
903     }
904     }
905     return false;
906     }
907    
908 jsr166 1.101 public void forEachRemaining(Consumer<? super E> action) {
909     Objects.requireNonNull(action);
910     if (!exhausted) {
911     exhausted = true;
912     Node<E> p = current;
913     current = null;
914     forEachFrom(action, p);
915     }
916     }
917    
918 dl 1.74 public int characteristics() {
919 jsr166 1.100 return (Spliterator.ORDERED |
920     Spliterator.NONNULL |
921     Spliterator.CONCURRENT);
922 dl 1.74 }
923     }
924    
925 jsr166 1.86 /**
926     * Returns a {@link Spliterator} over the elements in this queue.
927     *
928 jsr166 1.87 * <p>The returned spliterator is
929     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
930     *
931 jsr166 1.86 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
932     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
933     *
934     * @implNote
935     * The {@code Spliterator} implements {@code trySplit} to permit limited
936     * parallelism.
937     *
938     * @return a {@code Spliterator} over the elements in this queue
939     * @since 1.8
940     */
941 dl 1.76 public Spliterator<E> spliterator() {
942 jsr166 1.99 return new LBQSpliterator();
943 dl 1.74 }
944    
945 dl 1.2 /**
946 jsr166 1.101 * @throws NullPointerException {@inheritDoc}
947     */
948     public void forEach(Consumer<? super E> action) {
949     Objects.requireNonNull(action);
950     forEachFrom(action, null);
951     }
952    
953     /**
954     * Runs action on each element found during a traversal starting at p.
955     * If p is null, traversal starts at head.
956     */
957     void forEachFrom(Consumer<? super E> action, Node<E> p) {
958     // Extract batches of elements while holding the lock; then
959     // run the action on the elements while not
960 jsr166 1.110 final int batchSize = 64; // max number of elements per batch
961 jsr166 1.101 Object[] es = null; // container for batch of elements
962     int n, len = 0;
963     do {
964     fullyLock();
965     try {
966     if (es == null) {
967     if (p == null) p = head.next;
968     for (Node<E> q = p; q != null; q = succ(q))
969     if (q.item != null && ++len == batchSize)
970     break;
971     es = new Object[len];
972     }
973     for (n = 0; p != null && n < len; p = succ(p))
974     if ((es[n] = p.item) != null)
975     n++;
976     } finally {
977     fullyUnlock();
978     }
979     for (int i = 0; i < n; i++) {
980     @SuppressWarnings("unchecked") E e = (E) es[i];
981     action.accept(e);
982     }
983     } while (n > 0 && p != null);
984     }
985    
986     /**
987 jsr166 1.107 * @throws NullPointerException {@inheritDoc}
988     */
989     public boolean removeIf(Predicate<? super E> filter) {
990     Objects.requireNonNull(filter);
991     return bulkRemove(filter);
992     }
993    
994     /**
995     * @throws NullPointerException {@inheritDoc}
996     */
997     public boolean removeAll(Collection<?> c) {
998     Objects.requireNonNull(c);
999     return bulkRemove(e -> c.contains(e));
1000     }
1001    
1002     /**
1003     * @throws NullPointerException {@inheritDoc}
1004     */
1005     public boolean retainAll(Collection<?> c) {
1006     Objects.requireNonNull(c);
1007     return bulkRemove(e -> !c.contains(e));
1008     }
1009    
1010     /**
1011     * Returns the predecessor of live node p, given a node that was
1012     * once a live ancestor of p (or head); allows unlinking of p.
1013     */
1014 jsr166 1.108 Node<E> findPred(Node<E> p, Node<E> ancestor) {
1015 jsr166 1.107 // assert p.item != null;
1016     if (ancestor.item == null)
1017     ancestor = head;
1018     // Fails with NPE if precondition not satisfied
1019     for (Node<E> q; (q = ancestor.next) != p; )
1020     ancestor = q;
1021     return ancestor;
1022     }
1023    
1024     /** Implementation of bulk remove methods. */
1025     @SuppressWarnings("unchecked")
1026     private boolean bulkRemove(Predicate<? super E> filter) {
1027     boolean removed = false;
1028     Node<E> p = null, ancestor = head;
1029     Node<E>[] nodes = null;
1030     int n, len = 0;
1031     do {
1032     // 1. Extract batch of up to 64 elements while holding the lock.
1033     fullyLock();
1034     try {
1035 jsr166 1.112 if (nodes == null) { // first batch; initialize
1036     p = head.next;
1037 jsr166 1.107 for (Node<E> q = p; q != null; q = succ(q))
1038     if (q.item != null && ++len == 64)
1039     break;
1040     nodes = (Node<E>[]) new Node<?>[len];
1041     }
1042     for (n = 0; p != null && n < len; p = succ(p))
1043     nodes[n++] = p;
1044     } finally {
1045     fullyUnlock();
1046     }
1047    
1048     // 2. Run the filter on the elements while lock is free.
1049 jsr166 1.112 long deathRow = 0L; // "bitset" of size 64
1050 jsr166 1.107 for (int i = 0; i < n; i++) {
1051     final E e;
1052     if ((e = nodes[i].item) != null && filter.test(e))
1053     deathRow |= 1L << i;
1054     }
1055    
1056     // 3. Remove any filtered elements while holding the lock.
1057     if (deathRow != 0) {
1058     fullyLock();
1059     try {
1060     for (int i = 0; i < n; i++) {
1061     final Node<E> q;
1062     if ((deathRow & (1L << i)) != 0L
1063     && (q = nodes[i]).item != null) {
1064     ancestor = findPred(q, ancestor);
1065     unlink(q, ancestor);
1066     removed = true;
1067     }
1068 jsr166 1.112 nodes[i] = null; // help GC
1069 jsr166 1.107 }
1070     } finally {
1071     fullyUnlock();
1072     }
1073     }
1074     } while (n > 0 && p != null);
1075     return removed;
1076     }
1077    
1078     /**
1079 jsr166 1.68 * Saves this queue to a stream (that is, serializes it).
1080 dl 1.2 *
1081 jsr166 1.84 * @param s the stream
1082 jsr166 1.85 * @throws java.io.IOException if an I/O error occurs
1083 dl 1.2 * @serialData The capacity is emitted (int), followed by all of
1084 jsr166 1.51 * its elements (each an {@code Object}) in the proper order,
1085 dl 1.2 * followed by a null
1086     */
1087     private void writeObject(java.io.ObjectOutputStream s)
1088     throws java.io.IOException {
1089    
1090 tim 1.12 fullyLock();
1091 dl 1.2 try {
1092     // Write out any hidden stuff, plus capacity
1093     s.defaultWriteObject();
1094    
1095     // Write out all elements in the proper order.
1096 tim 1.12 for (Node<E> p = head.next; p != null; p = p.next)
1097 dl 1.2 s.writeObject(p.item);
1098    
1099     // Use trailing null as sentinel
1100     s.writeObject(null);
1101 tim 1.17 } finally {
1102 dl 1.2 fullyUnlock();
1103     }
1104 tim 1.1 }
1105    
1106 dl 1.2 /**
1107 jsr166 1.65 * Reconstitutes this queue from a stream (that is, deserializes it).
1108 jsr166 1.84 * @param s the stream
1109 jsr166 1.85 * @throws ClassNotFoundException if the class of a serialized object
1110     * could not be found
1111     * @throws java.io.IOException if an I/O error occurs
1112 dl 1.2 */
1113     private void readObject(java.io.ObjectInputStream s)
1114     throws java.io.IOException, ClassNotFoundException {
1115 tim 1.12 // Read in capacity, and any hidden stuff
1116     s.defaultReadObject();
1117 dl 1.2
1118 dl 1.19 count.set(0);
1119     last = head = new Node<E>(null);
1120    
1121 dl 1.6 // Read in all elements and place in queue
1122 dl 1.2 for (;;) {
1123 jsr166 1.51 @SuppressWarnings("unchecked")
1124 dl 1.2 E item = (E)s.readObject();
1125     if (item == null)
1126     break;
1127     add(item);
1128     }
1129 tim 1.1 }
1130     }