ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingDeque.java
Revision: 1.52
Committed: Tue Dec 2 05:48:29 2014 UTC (9 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.51: +1 -1 lines
Log Message:
this collection => this XXX

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