ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingDeque.java
Revision: 1.43
Committed: Mon Mar 18 12:40:30 2013 UTC (11 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.42: +13 -10 lines
Log Message:
Mesh Map and Spliterator methods with lambda

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