ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingDeque.java
Revision: 1.61
Committed: Wed Nov 16 23:14:52 2016 UTC (7 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.60: +40 -41 lines
Log Message:
slightly cleaner version of spliterator implementation

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4 jsr166 1.27 * http://creativecommons.org/publicdomain/zero/1.0/
5 dl 1.1 */
6    
7     package java.util.concurrent;
8 jsr166 1.21
9     import java.util.AbstractQueue;
10     import java.util.Collection;
11     import java.util.Iterator;
12     import java.util.NoSuchElementException;
13 jsr166 1.53 import java.util.Spliterator;
14     import java.util.Spliterators;
15 jsr166 1.21 import java.util.concurrent.locks.Condition;
16     import java.util.concurrent.locks.ReentrantLock;
17 jsr166 1.53 import java.util.function.Consumer;
18 dl 1.1
19     /**
20     * An optionally-bounded {@linkplain BlockingDeque blocking deque} based on
21     * linked nodes.
22     *
23 jsr166 1.35 * <p>The optional capacity bound constructor argument serves as a
24 dl 1.1 * way to prevent excessive expansion. The capacity, if unspecified,
25     * is equal to {@link Integer#MAX_VALUE}. Linked nodes are
26     * dynamically created upon each insertion unless this would bring the
27     * deque above capacity.
28     *
29     * <p>Most operations run in constant time (ignoring time spent
30     * blocking). Exceptions include {@link #remove(Object) remove},
31     * {@link #removeFirstOccurrence removeFirstOccurrence}, {@link
32     * #removeLastOccurrence removeLastOccurrence}, {@link #contains
33 jsr166 1.9 * contains}, {@link #iterator iterator.remove()}, and the bulk
34 dl 1.1 * operations, all of which run in linear time.
35     *
36     * <p>This class and its iterator implement all of the
37     * <em>optional</em> methods of the {@link Collection} and {@link
38 jsr166 1.9 * Iterator} interfaces.
39     *
40     * <p>This class is a member of the
41 jsr166 1.18 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
42 jsr166 1.9 * Java Collections Framework</a>.
43 dl 1.1 *
44     * @since 1.6
45     * @author Doug Lea
46 jsr166 1.52 * @param <E> the type of elements held in this deque
47 dl 1.1 */
48     public class LinkedBlockingDeque<E>
49     extends AbstractQueue<E>
50 jsr166 1.33 implements BlockingDeque<E>, java.io.Serializable {
51 dl 1.1
52     /*
53     * Implemented as a simple doubly-linked list protected by a
54     * single lock and using conditions to manage blocking.
55 jsr166 1.21 *
56     * To implement weakly consistent iterators, it appears we need to
57     * keep all Nodes GC-reachable from a predecessor dequeued Node.
58     * That would cause two problems:
59     * - allow a rogue Iterator to cause unbounded memory retention
60     * - cause cross-generational linking of old Nodes to new Nodes if
61     * a Node was tenured while live, which generational GCs have a
62     * hard time dealing with, causing repeated major collections.
63     * However, only non-deleted Nodes need to be reachable from
64     * dequeued Nodes, and reachability does not necessarily have to
65     * be of the kind understood by the GC. We use the trick of
66     * linking a Node that has just been dequeued to itself. Such a
67     * self-link implicitly means to jump to "first" (for next links)
68     * or "last" (for prev links).
69 dl 1.1 */
70    
71 jsr166 1.9 /*
72     * We have "diamond" multiple interface/abstract class inheritance
73     * here, and that introduces ambiguities. Often we want the
74     * BlockingDeque javadoc combined with the AbstractQueue
75     * implementation, so a lot of method specs are duplicated here.
76     */
77    
78 dl 1.1 private static final long serialVersionUID = -387911632671998426L;
79    
80     /** Doubly-linked list node class */
81     static final class Node<E> {
82 jsr166 1.21 /**
83     * The item, or null if this node has been removed.
84     */
85 jsr166 1.19 E item;
86 jsr166 1.21
87     /**
88     * One of:
89     * - the real predecessor Node
90     * - this Node, meaning the predecessor is tail
91     * - null, meaning there is no predecessor
92     */
93 dl 1.1 Node<E> prev;
94 jsr166 1.21
95     /**
96     * One of:
97     * - the real successor Node
98     * - this Node, meaning the successor is head
99     * - null, meaning there is no successor
100     */
101 dl 1.1 Node<E> next;
102 jsr166 1.21
103 dl 1.23 Node(E x) {
104 dl 1.1 item = x;
105     }
106     }
107    
108 jsr166 1.21 /**
109     * Pointer to first node.
110     * Invariant: (first == null && last == null) ||
111     * (first.prev == null && first.item != null)
112     */
113     transient Node<E> first;
114    
115     /**
116     * Pointer to last node.
117     * Invariant: (first == null && last == null) ||
118     * (last.next == null && last.item != null)
119     */
120     transient Node<E> last;
121    
122 dl 1.1 /** Number of items in the deque */
123     private transient int count;
124 jsr166 1.21
125 dl 1.1 /** Maximum number of items in the deque */
126     private final int capacity;
127 jsr166 1.21
128 dl 1.1 /** Main lock guarding all access */
129 jsr166 1.21 final ReentrantLock lock = new ReentrantLock();
130    
131 dl 1.1 /** Condition for waiting takes */
132     private final Condition notEmpty = lock.newCondition();
133 jsr166 1.21
134 dl 1.1 /** Condition for waiting puts */
135     private final Condition notFull = lock.newCondition();
136    
137     /**
138 jsr166 1.21 * Creates a {@code LinkedBlockingDeque} with a capacity of
139 dl 1.1 * {@link Integer#MAX_VALUE}.
140     */
141     public LinkedBlockingDeque() {
142     this(Integer.MAX_VALUE);
143     }
144    
145     /**
146 jsr166 1.21 * Creates a {@code LinkedBlockingDeque} with the given (fixed) capacity.
147 jsr166 1.9 *
148 dl 1.1 * @param capacity the capacity of this deque
149 jsr166 1.21 * @throws IllegalArgumentException if {@code capacity} is less than 1
150 dl 1.1 */
151     public LinkedBlockingDeque(int capacity) {
152     if (capacity <= 0) throw new IllegalArgumentException();
153     this.capacity = capacity;
154     }
155    
156     /**
157 jsr166 1.21 * Creates a {@code LinkedBlockingDeque} with a capacity of
158 jsr166 1.9 * {@link Integer#MAX_VALUE}, initially containing the elements of
159     * the given collection, added in traversal order of the
160     * collection's iterator.
161     *
162 dl 1.1 * @param c the collection of elements to initially contain
163 jsr166 1.9 * @throws NullPointerException if the specified collection or any
164     * of its elements are null
165 dl 1.1 */
166     public LinkedBlockingDeque(Collection<? extends E> c) {
167     this(Integer.MAX_VALUE);
168 jsr166 1.21 final ReentrantLock lock = this.lock;
169     lock.lock(); // Never contended, but necessary for visibility
170     try {
171     for (E e : c) {
172     if (e == null)
173     throw new NullPointerException();
174 dl 1.23 if (!linkLast(new Node<E>(e)))
175 jsr166 1.21 throw new IllegalStateException("Deque full");
176     }
177     } finally {
178     lock.unlock();
179     }
180 dl 1.1 }
181    
182    
183     // Basic linking and unlinking operations, called only while holding lock
184    
185     /**
186 dl 1.23 * Links node as first element, or returns false if full.
187 dl 1.1 */
188 dl 1.23 private boolean linkFirst(Node<E> node) {
189 jsr166 1.21 // assert lock.isHeldByCurrentThread();
190 dl 1.1 if (count >= capacity)
191     return false;
192     Node<E> f = first;
193 dl 1.23 node.next = f;
194     first = node;
195 dl 1.1 if (last == null)
196 dl 1.23 last = node;
197 dl 1.1 else
198 dl 1.23 f.prev = node;
199 jsr166 1.21 ++count;
200 dl 1.1 notEmpty.signal();
201     return true;
202     }
203    
204     /**
205 dl 1.23 * Links node as last element, or returns false if full.
206 dl 1.1 */
207 dl 1.23 private boolean linkLast(Node<E> node) {
208 jsr166 1.21 // assert lock.isHeldByCurrentThread();
209 dl 1.1 if (count >= capacity)
210     return false;
211     Node<E> l = last;
212 dl 1.23 node.prev = l;
213     last = node;
214 dl 1.1 if (first == null)
215 dl 1.23 first = node;
216 dl 1.1 else
217 dl 1.23 l.next = node;
218 jsr166 1.21 ++count;
219 dl 1.1 notEmpty.signal();
220     return true;
221     }
222    
223     /**
224 jsr166 1.3 * Removes and returns first element, or null if empty.
225 dl 1.1 */
226     private E unlinkFirst() {
227 jsr166 1.21 // assert lock.isHeldByCurrentThread();
228 dl 1.1 Node<E> f = first;
229     if (f == null)
230     return null;
231     Node<E> n = f.next;
232 jsr166 1.21 E item = f.item;
233     f.item = null;
234     f.next = f; // help GC
235 dl 1.1 first = n;
236 jsr166 1.3 if (n == null)
237 dl 1.1 last = null;
238 jsr166 1.3 else
239 dl 1.1 n.prev = null;
240     --count;
241     notFull.signal();
242 jsr166 1.21 return item;
243 dl 1.1 }
244    
245     /**
246 jsr166 1.3 * Removes and returns last element, or null if empty.
247 dl 1.1 */
248     private E unlinkLast() {
249 jsr166 1.21 // assert lock.isHeldByCurrentThread();
250 dl 1.1 Node<E> l = last;
251     if (l == null)
252     return null;
253     Node<E> p = l.prev;
254 jsr166 1.21 E item = l.item;
255     l.item = null;
256     l.prev = l; // help GC
257 dl 1.1 last = p;
258 jsr166 1.3 if (p == null)
259 dl 1.1 first = null;
260 jsr166 1.3 else
261 dl 1.1 p.next = null;
262     --count;
263     notFull.signal();
264 jsr166 1.21 return item;
265 dl 1.1 }
266    
267     /**
268 jsr166 1.21 * Unlinks x.
269 dl 1.1 */
270 jsr166 1.21 void unlink(Node<E> x) {
271     // assert lock.isHeldByCurrentThread();
272 dl 1.1 Node<E> p = x.prev;
273     Node<E> n = x.next;
274     if (p == null) {
275 jsr166 1.21 unlinkFirst();
276 dl 1.1 } else if (n == null) {
277 jsr166 1.21 unlinkLast();
278 dl 1.1 } else {
279     p.next = n;
280     n.prev = p;
281 jsr166 1.21 x.item = null;
282     // Don't mess with x's links. They may still be in use by
283     // an iterator.
284     --count;
285     notFull.signal();
286 dl 1.1 }
287     }
288    
289 jsr166 1.9 // BlockingDeque methods
290 dl 1.1
291 jsr166 1.9 /**
292 jsr166 1.46 * @throws IllegalStateException if this deque is full
293     * @throws NullPointerException {@inheritDoc}
294 jsr166 1.9 */
295     public void addFirst(E e) {
296     if (!offerFirst(e))
297     throw new IllegalStateException("Deque full");
298     }
299    
300     /**
301 jsr166 1.46 * @throws IllegalStateException if this deque is full
302 jsr166 1.9 * @throws NullPointerException {@inheritDoc}
303     */
304     public void addLast(E e) {
305     if (!offerLast(e))
306     throw new IllegalStateException("Deque full");
307     }
308    
309     /**
310     * @throws NullPointerException {@inheritDoc}
311     */
312 jsr166 1.6 public boolean offerFirst(E e) {
313     if (e == null) throw new NullPointerException();
314 dl 1.23 Node<E> node = new Node<E>(e);
315 jsr166 1.21 final ReentrantLock lock = this.lock;
316 dl 1.1 lock.lock();
317     try {
318 dl 1.23 return linkFirst(node);
319 dl 1.1 } finally {
320     lock.unlock();
321     }
322     }
323    
324 jsr166 1.9 /**
325     * @throws NullPointerException {@inheritDoc}
326     */
327 jsr166 1.6 public boolean offerLast(E e) {
328     if (e == null) throw new NullPointerException();
329 dl 1.23 Node<E> node = new Node<E>(e);
330 jsr166 1.21 final ReentrantLock lock = this.lock;
331 dl 1.1 lock.lock();
332     try {
333 dl 1.23 return linkLast(node);
334 dl 1.1 } finally {
335     lock.unlock();
336     }
337     }
338    
339 jsr166 1.9 /**
340     * @throws NullPointerException {@inheritDoc}
341     * @throws InterruptedException {@inheritDoc}
342     */
343     public void putFirst(E e) throws InterruptedException {
344     if (e == null) throw new NullPointerException();
345 dl 1.23 Node<E> node = new Node<E>(e);
346 jsr166 1.21 final ReentrantLock lock = this.lock;
347 dl 1.1 lock.lock();
348     try {
349 dl 1.23 while (!linkFirst(node))
350 jsr166 1.9 notFull.await();
351 dl 1.1 } finally {
352     lock.unlock();
353     }
354     }
355    
356 jsr166 1.9 /**
357     * @throws NullPointerException {@inheritDoc}
358     * @throws InterruptedException {@inheritDoc}
359     */
360     public void putLast(E e) throws InterruptedException {
361     if (e == null) throw new NullPointerException();
362 dl 1.23 Node<E> node = new Node<E>(e);
363 jsr166 1.21 final ReentrantLock lock = this.lock;
364 dl 1.1 lock.lock();
365     try {
366 dl 1.23 while (!linkLast(node))
367 jsr166 1.9 notFull.await();
368 dl 1.1 } finally {
369     lock.unlock();
370     }
371     }
372    
373 jsr166 1.9 /**
374     * @throws NullPointerException {@inheritDoc}
375     * @throws InterruptedException {@inheritDoc}
376     */
377     public boolean offerFirst(E e, long timeout, TimeUnit unit)
378     throws InterruptedException {
379     if (e == null) throw new NullPointerException();
380 dl 1.23 Node<E> node = new Node<E>(e);
381 jsr166 1.19 long nanos = unit.toNanos(timeout);
382 jsr166 1.21 final ReentrantLock lock = this.lock;
383 jsr166 1.9 lock.lockInterruptibly();
384 dl 1.1 try {
385 dl 1.23 while (!linkFirst(node)) {
386 jsr166 1.59 if (nanos <= 0L)
387 jsr166 1.9 return false;
388     nanos = notFull.awaitNanos(nanos);
389     }
390 jsr166 1.21 return true;
391 dl 1.1 } finally {
392     lock.unlock();
393     }
394     }
395    
396 jsr166 1.9 /**
397     * @throws NullPointerException {@inheritDoc}
398     * @throws InterruptedException {@inheritDoc}
399     */
400     public boolean offerLast(E e, long timeout, TimeUnit unit)
401     throws InterruptedException {
402     if (e == null) throw new NullPointerException();
403 dl 1.23 Node<E> node = new Node<E>(e);
404 jsr166 1.19 long nanos = unit.toNanos(timeout);
405 jsr166 1.21 final ReentrantLock lock = this.lock;
406 jsr166 1.9 lock.lockInterruptibly();
407 dl 1.1 try {
408 dl 1.23 while (!linkLast(node)) {
409 jsr166 1.59 if (nanos <= 0L)
410 jsr166 1.9 return false;
411     nanos = notFull.awaitNanos(nanos);
412     }
413 jsr166 1.21 return true;
414 dl 1.1 } finally {
415     lock.unlock();
416     }
417     }
418    
419 jsr166 1.9 /**
420     * @throws NoSuchElementException {@inheritDoc}
421     */
422     public E removeFirst() {
423     E x = pollFirst();
424 dl 1.1 if (x == null) throw new NoSuchElementException();
425     return x;
426     }
427    
428 jsr166 1.9 /**
429     * @throws NoSuchElementException {@inheritDoc}
430     */
431     public E removeLast() {
432     E x = pollLast();
433 dl 1.1 if (x == null) throw new NoSuchElementException();
434     return x;
435     }
436    
437 jsr166 1.9 public E pollFirst() {
438 jsr166 1.21 final ReentrantLock lock = this.lock;
439 dl 1.1 lock.lock();
440     try {
441 jsr166 1.9 return unlinkFirst();
442 dl 1.1 } finally {
443     lock.unlock();
444     }
445     }
446    
447 jsr166 1.9 public E pollLast() {
448 jsr166 1.21 final ReentrantLock lock = this.lock;
449 dl 1.1 lock.lock();
450     try {
451 jsr166 1.9 return unlinkLast();
452 dl 1.1 } finally {
453     lock.unlock();
454     }
455     }
456    
457     public E takeFirst() throws InterruptedException {
458 jsr166 1.21 final ReentrantLock lock = this.lock;
459 dl 1.1 lock.lock();
460     try {
461     E x;
462     while ( (x = unlinkFirst()) == null)
463     notEmpty.await();
464     return x;
465     } finally {
466     lock.unlock();
467     }
468     }
469    
470     public E takeLast() throws InterruptedException {
471 jsr166 1.21 final ReentrantLock lock = this.lock;
472 dl 1.1 lock.lock();
473     try {
474     E x;
475     while ( (x = unlinkLast()) == null)
476     notEmpty.await();
477     return x;
478     } finally {
479     lock.unlock();
480     }
481     }
482    
483 jsr166 1.9 public E pollFirst(long timeout, TimeUnit unit)
484 dl 1.1 throws InterruptedException {
485 jsr166 1.19 long nanos = unit.toNanos(timeout);
486 jsr166 1.21 final ReentrantLock lock = this.lock;
487 dl 1.1 lock.lockInterruptibly();
488     try {
489 jsr166 1.21 E x;
490     while ( (x = unlinkFirst()) == null) {
491 jsr166 1.59 if (nanos <= 0L)
492 jsr166 1.9 return null;
493     nanos = notEmpty.awaitNanos(nanos);
494 dl 1.1 }
495 jsr166 1.21 return x;
496 dl 1.1 } finally {
497     lock.unlock();
498     }
499     }
500 jsr166 1.3
501 jsr166 1.9 public E pollLast(long timeout, TimeUnit unit)
502 dl 1.1 throws InterruptedException {
503 jsr166 1.19 long nanos = unit.toNanos(timeout);
504 jsr166 1.21 final ReentrantLock lock = this.lock;
505 dl 1.1 lock.lockInterruptibly();
506     try {
507 jsr166 1.21 E x;
508     while ( (x = unlinkLast()) == null) {
509 jsr166 1.59 if (nanos <= 0L)
510 jsr166 1.9 return null;
511     nanos = notEmpty.awaitNanos(nanos);
512 dl 1.1 }
513 jsr166 1.21 return x;
514 dl 1.1 } finally {
515     lock.unlock();
516     }
517     }
518    
519 jsr166 1.9 /**
520     * @throws NoSuchElementException {@inheritDoc}
521     */
522     public E getFirst() {
523     E x = peekFirst();
524     if (x == null) throw new NoSuchElementException();
525     return x;
526     }
527    
528     /**
529     * @throws NoSuchElementException {@inheritDoc}
530     */
531     public E getLast() {
532     E x = peekLast();
533     if (x == null) throw new NoSuchElementException();
534     return x;
535     }
536    
537     public E peekFirst() {
538 jsr166 1.21 final ReentrantLock lock = this.lock;
539 jsr166 1.9 lock.lock();
540     try {
541     return (first == null) ? null : first.item;
542     } finally {
543     lock.unlock();
544     }
545     }
546    
547     public E peekLast() {
548 jsr166 1.21 final ReentrantLock lock = this.lock;
549 jsr166 1.9 lock.lock();
550     try {
551     return (last == null) ? null : last.item;
552     } finally {
553     lock.unlock();
554     }
555     }
556    
557     public boolean removeFirstOccurrence(Object o) {
558     if (o == null) return false;
559 jsr166 1.21 final ReentrantLock lock = this.lock;
560 jsr166 1.9 lock.lock();
561 dl 1.1 try {
562 jsr166 1.9 for (Node<E> p = first; p != null; p = p.next) {
563     if (o.equals(p.item)) {
564     unlink(p);
565     return true;
566     }
567 dl 1.1 }
568 jsr166 1.9 return false;
569 dl 1.1 } finally {
570     lock.unlock();
571     }
572     }
573    
574 jsr166 1.9 public boolean removeLastOccurrence(Object o) {
575     if (o == null) return false;
576 jsr166 1.21 final ReentrantLock lock = this.lock;
577 jsr166 1.9 lock.lock();
578 dl 1.1 try {
579 jsr166 1.9 for (Node<E> p = last; p != null; p = p.prev) {
580     if (o.equals(p.item)) {
581     unlink(p);
582     return true;
583     }
584 dl 1.1 }
585 jsr166 1.9 return false;
586 dl 1.1 } finally {
587     lock.unlock();
588     }
589     }
590    
591 jsr166 1.9 // BlockingQueue methods
592 dl 1.1
593 jsr166 1.9 /**
594     * Inserts the specified element at the end of this deque unless it would
595     * violate capacity restrictions. When using a capacity-restricted deque,
596     * it is generally preferable to use method {@link #offer(Object) offer}.
597     *
598 jsr166 1.13 * <p>This method is equivalent to {@link #addLast}.
599 jsr166 1.9 *
600 jsr166 1.46 * @throws IllegalStateException if this deque is full
601 jsr166 1.9 * @throws NullPointerException if the specified element is null
602     */
603     public boolean add(E e) {
604 jsr166 1.19 addLast(e);
605     return true;
606 jsr166 1.9 }
607    
608     /**
609     * @throws NullPointerException if the specified element is null
610     */
611     public boolean offer(E e) {
612 jsr166 1.19 return offerLast(e);
613 jsr166 1.9 }
614 dl 1.1
615 jsr166 1.9 /**
616     * @throws NullPointerException {@inheritDoc}
617     * @throws InterruptedException {@inheritDoc}
618     */
619     public void put(E e) throws InterruptedException {
620 jsr166 1.19 putLast(e);
621 jsr166 1.9 }
622 dl 1.1
623 jsr166 1.9 /**
624     * @throws NullPointerException {@inheritDoc}
625     * @throws InterruptedException {@inheritDoc}
626     */
627 jsr166 1.7 public boolean offer(E e, long timeout, TimeUnit unit)
628 jsr166 1.9 throws InterruptedException {
629 jsr166 1.19 return offerLast(e, timeout, unit);
630 jsr166 1.9 }
631    
632     /**
633     * Retrieves and removes the head of the queue represented by this deque.
634     * This method differs from {@link #poll poll} only in that it throws an
635     * exception if this deque is empty.
636     *
637     * <p>This method is equivalent to {@link #removeFirst() removeFirst}.
638     *
639     * @return the head of the queue represented by this deque
640     * @throws NoSuchElementException if this deque is empty
641     */
642     public E remove() {
643 jsr166 1.19 return removeFirst();
644 jsr166 1.9 }
645    
646     public E poll() {
647 jsr166 1.19 return pollFirst();
648 jsr166 1.9 }
649    
650     public E take() throws InterruptedException {
651 jsr166 1.19 return takeFirst();
652 jsr166 1.9 }
653    
654     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
655 jsr166 1.19 return pollFirst(timeout, unit);
656 jsr166 1.9 }
657 dl 1.1
658     /**
659 jsr166 1.9 * Retrieves, but does not remove, the head of the queue represented by
660     * this deque. This method differs from {@link #peek peek} only in that
661     * it throws an exception if this deque is empty.
662     *
663     * <p>This method is equivalent to {@link #getFirst() getFirst}.
664 dl 1.1 *
665 jsr166 1.9 * @return the head of the queue represented by this deque
666     * @throws NoSuchElementException if this deque is empty
667 dl 1.1 */
668 jsr166 1.9 public E element() {
669 jsr166 1.19 return getFirst();
670 jsr166 1.9 }
671    
672     public E peek() {
673 jsr166 1.19 return peekFirst();
674 dl 1.1 }
675    
676     /**
677 jsr166 1.4 * Returns the number of additional elements that this deque can ideally
678     * (in the absence of memory or resource constraints) accept without
679 dl 1.1 * blocking. This is always equal to the initial capacity of this deque
680 jsr166 1.21 * less the current {@code size} of this deque.
681 jsr166 1.4 *
682     * <p>Note that you <em>cannot</em> always tell if an attempt to insert
683 jsr166 1.21 * an element will succeed by inspecting {@code remainingCapacity}
684 jsr166 1.4 * because it may be the case that another thread is about to
685 jsr166 1.9 * insert or remove an element.
686 dl 1.1 */
687     public int remainingCapacity() {
688 jsr166 1.21 final ReentrantLock lock = this.lock;
689 dl 1.1 lock.lock();
690     try {
691     return capacity - count;
692     } finally {
693     lock.unlock();
694     }
695     }
696    
697 jsr166 1.9 /**
698     * @throws UnsupportedOperationException {@inheritDoc}
699     * @throws ClassCastException {@inheritDoc}
700     * @throws NullPointerException {@inheritDoc}
701     * @throws IllegalArgumentException {@inheritDoc}
702     */
703     public int drainTo(Collection<? super E> c) {
704 jsr166 1.21 return drainTo(c, Integer.MAX_VALUE);
705 dl 1.1 }
706    
707 jsr166 1.9 /**
708     * @throws UnsupportedOperationException {@inheritDoc}
709     * @throws ClassCastException {@inheritDoc}
710     * @throws NullPointerException {@inheritDoc}
711     * @throws IllegalArgumentException {@inheritDoc}
712     */
713     public int drainTo(Collection<? super E> c, int maxElements) {
714     if (c == null)
715     throw new NullPointerException();
716     if (c == this)
717     throw new IllegalArgumentException();
718 jsr166 1.30 if (maxElements <= 0)
719     return 0;
720 jsr166 1.21 final ReentrantLock lock = this.lock;
721 dl 1.1 lock.lock();
722     try {
723 jsr166 1.21 int n = Math.min(maxElements, count);
724     for (int i = 0; i < n; i++) {
725     c.add(first.item); // In this order, in case add() throws.
726     unlinkFirst();
727 dl 1.1 }
728 jsr166 1.9 return n;
729     } finally {
730     lock.unlock();
731     }
732     }
733    
734     // Stack methods
735    
736     /**
737 jsr166 1.46 * @throws IllegalStateException if this deque is full
738     * @throws NullPointerException {@inheritDoc}
739 jsr166 1.9 */
740     public void push(E e) {
741 jsr166 1.19 addFirst(e);
742 jsr166 1.9 }
743    
744     /**
745     * @throws NoSuchElementException {@inheritDoc}
746     */
747     public E pop() {
748 jsr166 1.19 return removeFirst();
749 jsr166 1.9 }
750    
751     // Collection methods
752    
753 jsr166 1.11 /**
754     * Removes the first occurrence of the specified element from this deque.
755     * If the deque does not contain the element, it is unchanged.
756 jsr166 1.21 * More formally, removes the first element {@code e} such that
757     * {@code o.equals(e)} (if such an element exists).
758     * Returns {@code true} if this deque contained the specified element
759 jsr166 1.11 * (or equivalently, if this deque changed as a result of the call).
760     *
761     * <p>This method is equivalent to
762     * {@link #removeFirstOccurrence(Object) removeFirstOccurrence}.
763     *
764     * @param o element to be removed from this deque, if present
765 jsr166 1.21 * @return {@code true} if this deque changed as a result of the call
766 jsr166 1.11 */
767 jsr166 1.9 public boolean remove(Object o) {
768 jsr166 1.19 return removeFirstOccurrence(o);
769 jsr166 1.9 }
770    
771     /**
772     * Returns the number of elements in this deque.
773     *
774     * @return the number of elements in this deque
775     */
776     public int size() {
777 jsr166 1.21 final ReentrantLock lock = this.lock;
778 jsr166 1.9 lock.lock();
779     try {
780     return count;
781 dl 1.1 } finally {
782     lock.unlock();
783     }
784     }
785    
786 jsr166 1.9 /**
787 jsr166 1.21 * Returns {@code true} if this deque contains the specified element.
788     * More formally, returns {@code true} if and only if this deque contains
789     * at least one element {@code e} such that {@code o.equals(e)}.
790 jsr166 1.9 *
791     * @param o object to be checked for containment in this deque
792 jsr166 1.21 * @return {@code true} if this deque contains the specified element
793 jsr166 1.9 */
794     public boolean contains(Object o) {
795     if (o == null) return false;
796 jsr166 1.21 final ReentrantLock lock = this.lock;
797 dl 1.1 lock.lock();
798     try {
799 jsr166 1.9 for (Node<E> p = first; p != null; p = p.next)
800     if (o.equals(p.item))
801 dl 1.1 return true;
802     return false;
803     } finally {
804     lock.unlock();
805     }
806     }
807    
808 jsr166 1.21 /*
809     * TODO: Add support for more efficient bulk operations.
810     *
811     * We don't want to acquire the lock for every iteration, but we
812     * also want other threads a chance to interact with the
813     * collection, especially when count is close to capacity.
814     */
815    
816     // /**
817     // * Adds all of the elements in the specified collection to this
818     // * queue. Attempts to addAll of a queue to itself result in
819     // * {@code IllegalArgumentException}. Further, the behavior of
820     // * this operation is undefined if the specified collection is
821     // * modified while the operation is in progress.
822     // *
823     // * @param c collection containing elements to be added to this queue
824     // * @return {@code true} if this queue changed as a result of the call
825     // * @throws ClassCastException {@inheritDoc}
826     // * @throws NullPointerException {@inheritDoc}
827     // * @throws IllegalArgumentException {@inheritDoc}
828 jsr166 1.46 // * @throws IllegalStateException if this deque is full
829 jsr166 1.21 // * @see #add(Object)
830     // */
831     // public boolean addAll(Collection<? extends E> c) {
832     // if (c == null)
833     // throw new NullPointerException();
834     // if (c == this)
835     // throw new IllegalArgumentException();
836     // final ReentrantLock lock = this.lock;
837     // lock.lock();
838     // try {
839     // boolean modified = false;
840     // for (E e : c)
841     // if (linkLast(e))
842     // modified = true;
843     // return modified;
844     // } finally {
845     // lock.unlock();
846     // }
847     // }
848 dl 1.1
849 jsr166 1.9 /**
850     * Returns an array containing all of the elements in this deque, in
851     * proper sequence (from first to last element).
852     *
853     * <p>The returned array will be "safe" in that no references to it are
854     * maintained by this deque. (In other words, this method must allocate
855     * a new array). The caller is thus free to modify the returned array.
856 jsr166 1.10 *
857 jsr166 1.9 * <p>This method acts as bridge between array-based and collection-based
858     * APIs.
859     *
860     * @return an array containing all of the elements in this deque
861     */
862 jsr166 1.21 @SuppressWarnings("unchecked")
863 dl 1.1 public Object[] toArray() {
864 jsr166 1.21 final ReentrantLock lock = this.lock;
865 dl 1.1 lock.lock();
866     try {
867     Object[] a = new Object[count];
868     int k = 0;
869 jsr166 1.3 for (Node<E> p = first; p != null; p = p.next)
870 dl 1.1 a[k++] = p.item;
871     return a;
872     } finally {
873     lock.unlock();
874     }
875     }
876    
877 jsr166 1.9 /**
878     * Returns an array containing all of the elements in this deque, in
879     * proper sequence; the runtime type of the returned array is that of
880     * the specified array. If the deque fits in the specified array, it
881     * is returned therein. Otherwise, a new array is allocated with the
882     * runtime type of the specified array and the size of this deque.
883     *
884     * <p>If this deque fits in the specified array with room to spare
885     * (i.e., the array has more elements than this deque), the element in
886     * the array immediately following the end of the deque is set to
887 jsr166 1.21 * {@code null}.
888 jsr166 1.9 *
889     * <p>Like the {@link #toArray()} method, this method acts as bridge between
890     * array-based and collection-based APIs. Further, this method allows
891     * precise control over the runtime type of the output array, and may,
892     * under certain circumstances, be used to save allocation costs.
893     *
894 jsr166 1.21 * <p>Suppose {@code x} is a deque known to contain only strings.
895 jsr166 1.9 * The following code can be used to dump the deque into a newly
896 jsr166 1.21 * allocated array of {@code String}:
897 jsr166 1.9 *
898 jsr166 1.55 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
899 jsr166 1.9 *
900 jsr166 1.21 * Note that {@code toArray(new Object[0])} is identical in function to
901     * {@code toArray()}.
902 jsr166 1.9 *
903     * @param a the array into which the elements of the deque are to
904     * be stored, if it is big enough; otherwise, a new array of the
905     * same runtime type is allocated for this purpose
906     * @return an array containing all of the elements in this deque
907     * @throws ArrayStoreException if the runtime type of the specified array
908     * is not a supertype of the runtime type of every element in
909     * this deque
910     * @throws NullPointerException if the specified array is null
911     */
912 jsr166 1.21 @SuppressWarnings("unchecked")
913 dl 1.1 public <T> T[] toArray(T[] a) {
914 jsr166 1.21 final ReentrantLock lock = this.lock;
915 dl 1.1 lock.lock();
916     try {
917     if (a.length < count)
918 jsr166 1.21 a = (T[])java.lang.reflect.Array.newInstance
919     (a.getClass().getComponentType(), count);
920 dl 1.1
921     int k = 0;
922 jsr166 1.3 for (Node<E> p = first; p != null; p = p.next)
923 dl 1.1 a[k++] = (T)p.item;
924     if (a.length > k)
925     a[k] = null;
926     return a;
927     } finally {
928     lock.unlock();
929     }
930     }
931    
932     public String toString() {
933 jsr166 1.56 return Helpers.collectionToString(this);
934 dl 1.1 }
935    
936     /**
937     * Atomically removes all of the elements from this deque.
938     * The deque will be empty after this call returns.
939     */
940     public void clear() {
941 jsr166 1.21 final ReentrantLock lock = this.lock;
942 dl 1.1 lock.lock();
943     try {
944 jsr166 1.21 for (Node<E> f = first; f != null; ) {
945     f.item = null;
946     Node<E> n = f.next;
947     f.prev = null;
948     f.next = null;
949     f = n;
950     }
951 dl 1.1 first = last = null;
952     count = 0;
953     notFull.signalAll();
954     } finally {
955     lock.unlock();
956     }
957     }
958    
959     /**
960     * Returns an iterator over the elements in this deque in proper sequence.
961 jsr166 1.9 * The elements will be returned in order from first (head) to last (tail).
962 jsr166 1.26 *
963 jsr166 1.51 * <p>The returned iterator is
964     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
965 dl 1.1 *
966 jsr166 1.9 * @return an iterator over the elements in this deque in proper sequence
967 dl 1.1 */
968     public Iterator<E> iterator() {
969     return new Itr();
970     }
971    
972     /**
973 dl 1.14 * Returns an iterator over the elements in this deque in reverse
974     * sequential order. The elements will be returned in order from
975     * last (tail) to first (head).
976 jsr166 1.26 *
977 jsr166 1.51 * <p>The returned iterator is
978     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
979 jsr166 1.26 *
980     * @return an iterator over the elements in this deque in reverse order
981 dl 1.14 */
982     public Iterator<E> descendingIterator() {
983     return new DescendingItr();
984     }
985    
986     /**
987 jsr166 1.58 * Base class for LinkedBlockingDeque iterators.
988 dl 1.1 */
989 dl 1.16 private abstract class AbstractItr implements Iterator<E> {
990 jsr166 1.15 /**
991 jsr166 1.58 * The next node to return in next().
992 dl 1.14 */
993 jsr166 1.28 Node<E> next;
994 dl 1.1
995     /**
996     * nextItem holds on to item fields because once we claim that
997     * an element exists in hasNext(), we must return item read
998     * under lock (in advance()) even if it was in the process of
999     * being removed when hasNext() was called.
1000 jsr166 1.3 */
1001 dl 1.14 E nextItem;
1002 dl 1.1
1003     /**
1004     * Node returned by most recent call to next. Needed by remove.
1005     * Reset to null if this element is deleted by a call to remove.
1006     */
1007 dl 1.16 private Node<E> lastRet;
1008    
1009 jsr166 1.21 abstract Node<E> firstNode();
1010     abstract Node<E> nextNode(Node<E> n);
1011    
1012 dl 1.16 AbstractItr() {
1013 jsr166 1.21 // set to initial position
1014     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1015     lock.lock();
1016     try {
1017     next = firstNode();
1018     nextItem = (next == null) ? null : next.item;
1019     } finally {
1020     lock.unlock();
1021     }
1022 dl 1.16 }
1023 dl 1.1
1024     /**
1025 jsr166 1.25 * Returns the successor node of the given non-null, but
1026     * possibly previously deleted, node.
1027     */
1028     private Node<E> succ(Node<E> n) {
1029     // Chains of deleted nodes ending in null or self-links
1030     // are possible if multiple interior nodes are removed.
1031     for (;;) {
1032     Node<E> s = nextNode(n);
1033     if (s == null)
1034     return null;
1035     else if (s.item != null)
1036     return s;
1037     else if (s == n)
1038     return firstNode();
1039     else
1040     n = s;
1041     }
1042     }
1043    
1044     /**
1045 jsr166 1.21 * Advances next.
1046 dl 1.1 */
1047 jsr166 1.21 void advance() {
1048     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1049     lock.lock();
1050     try {
1051     // assert next != null;
1052 jsr166 1.25 next = succ(next);
1053 jsr166 1.21 nextItem = (next == null) ? null : next.item;
1054     } finally {
1055     lock.unlock();
1056     }
1057     }
1058 dl 1.1
1059     public boolean hasNext() {
1060     return next != null;
1061     }
1062    
1063     public E next() {
1064     if (next == null)
1065     throw new NoSuchElementException();
1066 dl 1.14 lastRet = next;
1067 dl 1.1 E x = nextItem;
1068     advance();
1069     return x;
1070     }
1071    
1072     public void remove() {
1073 dl 1.14 Node<E> n = lastRet;
1074 dl 1.1 if (n == null)
1075     throw new IllegalStateException();
1076 dl 1.14 lastRet = null;
1077     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1078     lock.lock();
1079     try {
1080 jsr166 1.21 if (n.item != null)
1081     unlink(n);
1082 dl 1.14 } finally {
1083     lock.unlock();
1084     }
1085     }
1086     }
1087    
1088 jsr166 1.21 /** Forward iterator */
1089     private class Itr extends AbstractItr {
1090     Node<E> firstNode() { return first; }
1091     Node<E> nextNode(Node<E> n) { return n.next; }
1092     }
1093    
1094     /** Descending iterator */
1095 dl 1.16 private class DescendingItr extends AbstractItr {
1096 jsr166 1.21 Node<E> firstNode() { return last; }
1097     Node<E> nextNode(Node<E> n) { return n.prev; }
1098 dl 1.14 }
1099    
1100 dl 1.40 /** A customized variant of Spliterators.IteratorSpliterator */
1101 dl 1.36 static final class LBDSpliterator<E> implements Spliterator<E> {
1102 dl 1.43 static final int MAX_BATCH = 1 << 25; // max batch array size;
1103 dl 1.36 final LinkedBlockingDeque<E> queue;
1104     Node<E> current; // current node; null until initialized
1105     int batch; // batch size for splits
1106     boolean exhausted; // true when no more nodes
1107     long est; // size estimate
1108 jsr166 1.37 LBDSpliterator(LinkedBlockingDeque<E> queue) {
1109 dl 1.36 this.queue = queue;
1110     this.est = queue.size();
1111     }
1112    
1113     public long estimateSize() { return est; }
1114    
1115     public Spliterator<E> trySplit() {
1116 dl 1.43 Node<E> h;
1117 dl 1.36 final LinkedBlockingDeque<E> q = this.queue;
1118 dl 1.43 int b = batch;
1119     int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
1120 jsr166 1.41 if (!exhausted &&
1121 jsr166 1.60 (((h = current) != null && h != h.next)
1122     || (h = q.first) != null)
1123     && h.next != null) {
1124 dl 1.47 Object[] a = new Object[n];
1125 dl 1.43 final ReentrantLock lock = q.lock;
1126 dl 1.36 int i = 0;
1127     Node<E> p = current;
1128     lock.lock();
1129     try {
1130 jsr166 1.60 if ((p != null && p != p.next) || (p = q.first) != null) {
1131 dl 1.36 do {
1132     if ((a[i] = p.item) != null)
1133     ++i;
1134     } while ((p = p.next) != null && i < n);
1135     }
1136     } finally {
1137     lock.unlock();
1138     }
1139     if ((current = p) == null) {
1140     est = 0L;
1141     exhausted = true;
1142     }
1143 dl 1.40 else if ((est -= i) < 0L)
1144     est = 0L;
1145 dl 1.43 if (i > 0) {
1146     batch = i;
1147     return Spliterators.spliterator
1148 jsr166 1.57 (a, 0, i, (Spliterator.ORDERED |
1149     Spliterator.NONNULL |
1150     Spliterator.CONCURRENT));
1151 dl 1.43 }
1152 dl 1.36 }
1153     return null;
1154     }
1155    
1156 dl 1.44 public void forEachRemaining(Consumer<? super E> action) {
1157 dl 1.36 if (action == null) throw new NullPointerException();
1158 jsr166 1.61 if (exhausted)
1159     return;
1160     exhausted = true;
1161     final LinkedBlockingDeque<E> q = this.queue;
1162     final ReentrantLock lock = q.lock;
1163     Node<E> p = current;
1164     current = null;
1165     do {
1166 jsr166 1.60 E e;
1167 dl 1.36 lock.lock();
1168     try {
1169 jsr166 1.61 if (p == null || (p == p.next))
1170 jsr166 1.60 p = q.first;
1171     do {
1172 jsr166 1.61 if (p == null)
1173     return;
1174 jsr166 1.60 e = p.item;
1175 jsr166 1.61 p = p.next;
1176 jsr166 1.60 } while (e == null);
1177 dl 1.36 } finally {
1178     lock.unlock();
1179     }
1180 jsr166 1.60 action.accept(e);
1181 jsr166 1.61 } while (p != null);
1182     }
1183    
1184     public boolean tryAdvance(Consumer<? super E> action) {
1185     if (action == null) throw new NullPointerException();
1186     if (exhausted)
1187     return false;
1188     final LinkedBlockingDeque<E> q = this.queue;
1189     final ReentrantLock lock = q.lock;
1190     Node<E> p = current;
1191     E e = null;
1192     lock.lock();
1193     try {
1194     if (p == null || p == p.next)
1195     p = q.first;
1196     do {
1197     if (p == null)
1198     break;
1199     e = p.item;
1200     p = p.next;
1201     } while (e == null);
1202     } finally {
1203     lock.unlock();
1204 dl 1.36 }
1205 jsr166 1.61 exhausted = ((current = p) == null);
1206     if (e == null)
1207     return false;
1208     action.accept(e);
1209     return true;
1210 dl 1.36 }
1211    
1212     public int characteristics() {
1213 jsr166 1.60 return (Spliterator.ORDERED |
1214     Spliterator.NONNULL |
1215     Spliterator.CONCURRENT);
1216 dl 1.36 }
1217     }
1218    
1219 jsr166 1.50 /**
1220     * Returns a {@link Spliterator} over the elements in this deque.
1221     *
1222 jsr166 1.51 * <p>The returned spliterator is
1223     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1224     *
1225 jsr166 1.50 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1226     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1227     *
1228     * @implNote
1229     * The {@code Spliterator} implements {@code trySplit} to permit limited
1230     * parallelism.
1231     *
1232     * @return a {@code Spliterator} over the elements in this deque
1233     * @since 1.8
1234     */
1235 dl 1.39 public Spliterator<E> spliterator() {
1236 dl 1.36 return new LBDSpliterator<E>(this);
1237     }
1238    
1239 dl 1.1 /**
1240 jsr166 1.34 * Saves this deque to a stream (that is, serializes it).
1241 dl 1.1 *
1242 jsr166 1.48 * @param s the stream
1243 jsr166 1.49 * @throws java.io.IOException if an I/O error occurs
1244 dl 1.1 * @serialData The capacity (int), followed by elements (each an
1245 jsr166 1.21 * {@code Object}) in the proper order, followed by a null
1246 dl 1.1 */
1247     private void writeObject(java.io.ObjectOutputStream s)
1248     throws java.io.IOException {
1249 jsr166 1.21 final ReentrantLock lock = this.lock;
1250 dl 1.1 lock.lock();
1251     try {
1252     // Write out capacity and any hidden stuff
1253     s.defaultWriteObject();
1254     // Write out all elements in the proper order.
1255     for (Node<E> p = first; p != null; p = p.next)
1256     s.writeObject(p.item);
1257     // Use trailing null as sentinel
1258     s.writeObject(null);
1259     } finally {
1260     lock.unlock();
1261     }
1262     }
1263    
1264     /**
1265 jsr166 1.31 * Reconstitutes this deque from a stream (that is, deserializes it).
1266 jsr166 1.48 * @param s the stream
1267 jsr166 1.49 * @throws ClassNotFoundException if the class of a serialized object
1268     * could not be found
1269     * @throws java.io.IOException if an I/O error occurs
1270 dl 1.1 */
1271     private void readObject(java.io.ObjectInputStream s)
1272     throws java.io.IOException, ClassNotFoundException {
1273     s.defaultReadObject();
1274     count = 0;
1275     first = null;
1276     last = null;
1277     // Read in all elements and place in queue
1278     for (;;) {
1279 jsr166 1.21 @SuppressWarnings("unchecked")
1280 dl 1.1 E item = (E)s.readObject();
1281     if (item == null)
1282     break;
1283     add(item);
1284     }
1285     }
1286 jsr166 1.3
1287 dl 1.1 }