ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingDeque.java
Revision: 1.66
Committed: Sun Dec 11 19:59:51 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.65: +69 -69 lines
Log Message:
8171051: LinkedBlockingQueue spliterator needs to support node self-linking

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 jsr166 1.65 // checkInvariants();
179 jsr166 1.21 lock.unlock();
180     }
181 dl 1.1 }
182    
183    
184     // Basic linking and unlinking operations, called only while holding lock
185    
186     /**
187 dl 1.23 * Links node as first element, or returns false if full.
188 dl 1.1 */
189 dl 1.23 private boolean linkFirst(Node<E> node) {
190 jsr166 1.21 // assert lock.isHeldByCurrentThread();
191 dl 1.1 if (count >= capacity)
192     return false;
193     Node<E> f = first;
194 dl 1.23 node.next = f;
195     first = node;
196 dl 1.1 if (last == null)
197 dl 1.23 last = node;
198 dl 1.1 else
199 dl 1.23 f.prev = node;
200 jsr166 1.21 ++count;
201 dl 1.1 notEmpty.signal();
202     return true;
203     }
204    
205     /**
206 dl 1.23 * Links node as last element, or returns false if full.
207 dl 1.1 */
208 dl 1.23 private boolean linkLast(Node<E> node) {
209 jsr166 1.21 // assert lock.isHeldByCurrentThread();
210 dl 1.1 if (count >= capacity)
211     return false;
212     Node<E> l = last;
213 dl 1.23 node.prev = l;
214     last = node;
215 dl 1.1 if (first == null)
216 dl 1.23 first = node;
217 dl 1.1 else
218 dl 1.23 l.next = node;
219 jsr166 1.21 ++count;
220 dl 1.1 notEmpty.signal();
221     return true;
222     }
223    
224     /**
225 jsr166 1.3 * Removes and returns first element, or null if empty.
226 dl 1.1 */
227     private E unlinkFirst() {
228 jsr166 1.21 // assert lock.isHeldByCurrentThread();
229 dl 1.1 Node<E> f = first;
230     if (f == null)
231     return null;
232     Node<E> n = f.next;
233 jsr166 1.21 E item = f.item;
234     f.item = null;
235     f.next = f; // help GC
236 dl 1.1 first = n;
237 jsr166 1.3 if (n == null)
238 dl 1.1 last = null;
239 jsr166 1.3 else
240 dl 1.1 n.prev = null;
241     --count;
242     notFull.signal();
243 jsr166 1.21 return item;
244 dl 1.1 }
245    
246     /**
247 jsr166 1.3 * Removes and returns last element, or null if empty.
248 dl 1.1 */
249     private E unlinkLast() {
250 jsr166 1.21 // assert lock.isHeldByCurrentThread();
251 dl 1.1 Node<E> l = last;
252     if (l == null)
253     return null;
254     Node<E> p = l.prev;
255 jsr166 1.21 E item = l.item;
256     l.item = null;
257     l.prev = l; // help GC
258 dl 1.1 last = p;
259 jsr166 1.3 if (p == null)
260 dl 1.1 first = null;
261 jsr166 1.3 else
262 dl 1.1 p.next = null;
263     --count;
264     notFull.signal();
265 jsr166 1.21 return item;
266 dl 1.1 }
267    
268     /**
269 jsr166 1.21 * Unlinks x.
270 dl 1.1 */
271 jsr166 1.21 void unlink(Node<E> x) {
272     // assert lock.isHeldByCurrentThread();
273 dl 1.1 Node<E> p = x.prev;
274     Node<E> n = x.next;
275     if (p == null) {
276 jsr166 1.21 unlinkFirst();
277 dl 1.1 } else if (n == null) {
278 jsr166 1.21 unlinkLast();
279 dl 1.1 } else {
280     p.next = n;
281     n.prev = p;
282 jsr166 1.21 x.item = null;
283     // Don't mess with x's links. They may still be in use by
284     // an iterator.
285     --count;
286     notFull.signal();
287 dl 1.1 }
288     }
289    
290 jsr166 1.9 // BlockingDeque methods
291 dl 1.1
292 jsr166 1.9 /**
293 jsr166 1.46 * @throws IllegalStateException if this deque is full
294     * @throws NullPointerException {@inheritDoc}
295 jsr166 1.9 */
296     public void addFirst(E e) {
297     if (!offerFirst(e))
298     throw new IllegalStateException("Deque full");
299     }
300    
301     /**
302 jsr166 1.46 * @throws IllegalStateException if this deque is full
303 jsr166 1.9 * @throws NullPointerException {@inheritDoc}
304     */
305     public void addLast(E e) {
306     if (!offerLast(e))
307     throw new IllegalStateException("Deque full");
308     }
309    
310     /**
311     * @throws NullPointerException {@inheritDoc}
312     */
313 jsr166 1.6 public boolean offerFirst(E e) {
314     if (e == null) throw new NullPointerException();
315 dl 1.23 Node<E> node = new Node<E>(e);
316 jsr166 1.21 final ReentrantLock lock = this.lock;
317 dl 1.1 lock.lock();
318     try {
319 dl 1.23 return linkFirst(node);
320 dl 1.1 } finally {
321 jsr166 1.65 // checkInvariants();
322 dl 1.1 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 jsr166 1.65 // checkInvariants();
338 dl 1.1 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 jsr166 1.65 // checkInvariants();
356 dl 1.1 lock.unlock();
357     }
358     }
359    
360 jsr166 1.9 /**
361     * @throws NullPointerException {@inheritDoc}
362     * @throws InterruptedException {@inheritDoc}
363     */
364     public void putLast(E e) throws InterruptedException {
365     if (e == null) throw new NullPointerException();
366 dl 1.23 Node<E> node = new Node<E>(e);
367 jsr166 1.21 final ReentrantLock lock = this.lock;
368 dl 1.1 lock.lock();
369     try {
370 dl 1.23 while (!linkLast(node))
371 jsr166 1.9 notFull.await();
372 dl 1.1 } finally {
373 jsr166 1.65 // checkInvariants();
374 dl 1.1 lock.unlock();
375     }
376     }
377    
378 jsr166 1.9 /**
379     * @throws NullPointerException {@inheritDoc}
380     * @throws InterruptedException {@inheritDoc}
381     */
382     public boolean offerFirst(E e, long timeout, TimeUnit unit)
383     throws InterruptedException {
384     if (e == null) throw new NullPointerException();
385 dl 1.23 Node<E> node = new Node<E>(e);
386 jsr166 1.19 long nanos = unit.toNanos(timeout);
387 jsr166 1.21 final ReentrantLock lock = this.lock;
388 jsr166 1.9 lock.lockInterruptibly();
389 dl 1.1 try {
390 dl 1.23 while (!linkFirst(node)) {
391 jsr166 1.59 if (nanos <= 0L)
392 jsr166 1.9 return false;
393     nanos = notFull.awaitNanos(nanos);
394     }
395 jsr166 1.21 return true;
396 dl 1.1 } finally {
397 jsr166 1.65 // checkInvariants();
398 dl 1.1 lock.unlock();
399     }
400     }
401    
402 jsr166 1.9 /**
403     * @throws NullPointerException {@inheritDoc}
404     * @throws InterruptedException {@inheritDoc}
405     */
406     public boolean offerLast(E e, long timeout, TimeUnit unit)
407     throws InterruptedException {
408     if (e == null) throw new NullPointerException();
409 dl 1.23 Node<E> node = new Node<E>(e);
410 jsr166 1.19 long nanos = unit.toNanos(timeout);
411 jsr166 1.21 final ReentrantLock lock = this.lock;
412 jsr166 1.9 lock.lockInterruptibly();
413 dl 1.1 try {
414 dl 1.23 while (!linkLast(node)) {
415 jsr166 1.59 if (nanos <= 0L)
416 jsr166 1.9 return false;
417     nanos = notFull.awaitNanos(nanos);
418     }
419 jsr166 1.21 return true;
420 dl 1.1 } finally {
421 jsr166 1.65 // checkInvariants();
422 dl 1.1 lock.unlock();
423     }
424     }
425    
426 jsr166 1.9 /**
427     * @throws NoSuchElementException {@inheritDoc}
428     */
429     public E removeFirst() {
430     E x = pollFirst();
431 dl 1.1 if (x == null) throw new NoSuchElementException();
432     return x;
433     }
434    
435 jsr166 1.9 /**
436     * @throws NoSuchElementException {@inheritDoc}
437     */
438     public E removeLast() {
439     E x = pollLast();
440 dl 1.1 if (x == null) throw new NoSuchElementException();
441     return x;
442     }
443    
444 jsr166 1.9 public E pollFirst() {
445 jsr166 1.21 final ReentrantLock lock = this.lock;
446 dl 1.1 lock.lock();
447     try {
448 jsr166 1.9 return unlinkFirst();
449 dl 1.1 } finally {
450 jsr166 1.65 // checkInvariants();
451 dl 1.1 lock.unlock();
452     }
453     }
454    
455 jsr166 1.9 public E pollLast() {
456 jsr166 1.21 final ReentrantLock lock = this.lock;
457 dl 1.1 lock.lock();
458     try {
459 jsr166 1.9 return unlinkLast();
460 dl 1.1 } finally {
461 jsr166 1.65 // checkInvariants();
462 dl 1.1 lock.unlock();
463     }
464     }
465    
466     public E takeFirst() throws InterruptedException {
467 jsr166 1.21 final ReentrantLock lock = this.lock;
468 dl 1.1 lock.lock();
469     try {
470     E x;
471     while ( (x = unlinkFirst()) == null)
472     notEmpty.await();
473     return x;
474     } finally {
475 jsr166 1.65 // checkInvariants();
476 dl 1.1 lock.unlock();
477     }
478     }
479    
480     public E takeLast() throws InterruptedException {
481 jsr166 1.21 final ReentrantLock lock = this.lock;
482 dl 1.1 lock.lock();
483     try {
484     E x;
485     while ( (x = unlinkLast()) == null)
486     notEmpty.await();
487     return x;
488     } finally {
489 jsr166 1.65 // checkInvariants();
490 dl 1.1 lock.unlock();
491     }
492     }
493    
494 jsr166 1.9 public E pollFirst(long timeout, TimeUnit unit)
495 dl 1.1 throws InterruptedException {
496 jsr166 1.19 long nanos = unit.toNanos(timeout);
497 jsr166 1.21 final ReentrantLock lock = this.lock;
498 dl 1.1 lock.lockInterruptibly();
499     try {
500 jsr166 1.21 E x;
501     while ( (x = unlinkFirst()) == null) {
502 jsr166 1.59 if (nanos <= 0L)
503 jsr166 1.9 return null;
504     nanos = notEmpty.awaitNanos(nanos);
505 dl 1.1 }
506 jsr166 1.21 return x;
507 dl 1.1 } finally {
508 jsr166 1.65 // checkInvariants();
509 dl 1.1 lock.unlock();
510     }
511     }
512 jsr166 1.3
513 jsr166 1.9 public E pollLast(long timeout, TimeUnit unit)
514 dl 1.1 throws InterruptedException {
515 jsr166 1.19 long nanos = unit.toNanos(timeout);
516 jsr166 1.21 final ReentrantLock lock = this.lock;
517 dl 1.1 lock.lockInterruptibly();
518     try {
519 jsr166 1.21 E x;
520     while ( (x = unlinkLast()) == null) {
521 jsr166 1.59 if (nanos <= 0L)
522 jsr166 1.9 return null;
523     nanos = notEmpty.awaitNanos(nanos);
524 dl 1.1 }
525 jsr166 1.21 return x;
526 dl 1.1 } finally {
527 jsr166 1.65 // checkInvariants();
528 dl 1.1 lock.unlock();
529     }
530     }
531    
532 jsr166 1.9 /**
533     * @throws NoSuchElementException {@inheritDoc}
534     */
535     public E getFirst() {
536     E x = peekFirst();
537     if (x == null) throw new NoSuchElementException();
538     return x;
539     }
540    
541     /**
542     * @throws NoSuchElementException {@inheritDoc}
543     */
544     public E getLast() {
545     E x = peekLast();
546     if (x == null) throw new NoSuchElementException();
547     return x;
548     }
549    
550     public E peekFirst() {
551 jsr166 1.21 final ReentrantLock lock = this.lock;
552 jsr166 1.9 lock.lock();
553     try {
554     return (first == null) ? null : first.item;
555     } finally {
556 jsr166 1.65 // checkInvariants();
557 jsr166 1.9 lock.unlock();
558     }
559     }
560    
561     public E peekLast() {
562 jsr166 1.21 final ReentrantLock lock = this.lock;
563 jsr166 1.9 lock.lock();
564     try {
565     return (last == null) ? null : last.item;
566     } finally {
567 jsr166 1.65 // checkInvariants();
568 jsr166 1.9 lock.unlock();
569     }
570     }
571    
572     public boolean removeFirstOccurrence(Object o) {
573     if (o == null) return false;
574 jsr166 1.21 final ReentrantLock lock = this.lock;
575 jsr166 1.9 lock.lock();
576 dl 1.1 try {
577 jsr166 1.9 for (Node<E> p = first; p != null; p = p.next) {
578     if (o.equals(p.item)) {
579     unlink(p);
580     return true;
581     }
582 dl 1.1 }
583 jsr166 1.9 return false;
584 dl 1.1 } finally {
585 jsr166 1.65 // checkInvariants();
586 dl 1.1 lock.unlock();
587     }
588     }
589    
590 jsr166 1.9 public boolean removeLastOccurrence(Object o) {
591     if (o == null) return false;
592 jsr166 1.21 final ReentrantLock lock = this.lock;
593 jsr166 1.9 lock.lock();
594 dl 1.1 try {
595 jsr166 1.9 for (Node<E> p = last; p != null; p = p.prev) {
596     if (o.equals(p.item)) {
597     unlink(p);
598     return true;
599     }
600 dl 1.1 }
601 jsr166 1.9 return false;
602 dl 1.1 } finally {
603 jsr166 1.65 // checkInvariants();
604 dl 1.1 lock.unlock();
605     }
606     }
607    
608 jsr166 1.9 // BlockingQueue methods
609 dl 1.1
610 jsr166 1.9 /**
611     * Inserts the specified element at the end of this deque unless it would
612     * violate capacity restrictions. When using a capacity-restricted deque,
613     * it is generally preferable to use method {@link #offer(Object) offer}.
614     *
615 jsr166 1.13 * <p>This method is equivalent to {@link #addLast}.
616 jsr166 1.9 *
617 jsr166 1.46 * @throws IllegalStateException if this deque is full
618 jsr166 1.9 * @throws NullPointerException if the specified element is null
619     */
620     public boolean add(E e) {
621 jsr166 1.19 addLast(e);
622     return true;
623 jsr166 1.9 }
624    
625     /**
626     * @throws NullPointerException if the specified element is null
627     */
628     public boolean offer(E e) {
629 jsr166 1.19 return offerLast(e);
630 jsr166 1.9 }
631 dl 1.1
632 jsr166 1.9 /**
633     * @throws NullPointerException {@inheritDoc}
634     * @throws InterruptedException {@inheritDoc}
635     */
636     public void put(E e) throws InterruptedException {
637 jsr166 1.19 putLast(e);
638 jsr166 1.9 }
639 dl 1.1
640 jsr166 1.9 /**
641     * @throws NullPointerException {@inheritDoc}
642     * @throws InterruptedException {@inheritDoc}
643     */
644 jsr166 1.7 public boolean offer(E e, long timeout, TimeUnit unit)
645 jsr166 1.9 throws InterruptedException {
646 jsr166 1.19 return offerLast(e, timeout, unit);
647 jsr166 1.9 }
648    
649     /**
650     * Retrieves and removes the head of the queue represented by this deque.
651     * This method differs from {@link #poll poll} only in that it throws an
652     * exception if this deque is empty.
653     *
654     * <p>This method is equivalent to {@link #removeFirst() removeFirst}.
655     *
656     * @return the head of the queue represented by this deque
657     * @throws NoSuchElementException if this deque is empty
658     */
659     public E remove() {
660 jsr166 1.19 return removeFirst();
661 jsr166 1.9 }
662    
663     public E poll() {
664 jsr166 1.19 return pollFirst();
665 jsr166 1.9 }
666    
667     public E take() throws InterruptedException {
668 jsr166 1.19 return takeFirst();
669 jsr166 1.9 }
670    
671     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
672 jsr166 1.19 return pollFirst(timeout, unit);
673 jsr166 1.9 }
674 dl 1.1
675     /**
676 jsr166 1.9 * Retrieves, but does not remove, the head of the queue represented by
677     * this deque. This method differs from {@link #peek peek} only in that
678     * it throws an exception if this deque is empty.
679     *
680     * <p>This method is equivalent to {@link #getFirst() getFirst}.
681 dl 1.1 *
682 jsr166 1.9 * @return the head of the queue represented by this deque
683     * @throws NoSuchElementException if this deque is empty
684 dl 1.1 */
685 jsr166 1.9 public E element() {
686 jsr166 1.19 return getFirst();
687 jsr166 1.9 }
688    
689     public E peek() {
690 jsr166 1.19 return peekFirst();
691 dl 1.1 }
692    
693     /**
694 jsr166 1.4 * Returns the number of additional elements that this deque can ideally
695     * (in the absence of memory or resource constraints) accept without
696 dl 1.1 * blocking. This is always equal to the initial capacity of this deque
697 jsr166 1.21 * less the current {@code size} of this deque.
698 jsr166 1.4 *
699     * <p>Note that you <em>cannot</em> always tell if an attempt to insert
700 jsr166 1.21 * an element will succeed by inspecting {@code remainingCapacity}
701 jsr166 1.4 * because it may be the case that another thread is about to
702 jsr166 1.9 * insert or remove an element.
703 dl 1.1 */
704     public int remainingCapacity() {
705 jsr166 1.21 final ReentrantLock lock = this.lock;
706 dl 1.1 lock.lock();
707     try {
708     return capacity - count;
709     } finally {
710 jsr166 1.65 // checkInvariants();
711 dl 1.1 lock.unlock();
712     }
713     }
714    
715 jsr166 1.9 /**
716     * @throws UnsupportedOperationException {@inheritDoc}
717     * @throws ClassCastException {@inheritDoc}
718     * @throws NullPointerException {@inheritDoc}
719     * @throws IllegalArgumentException {@inheritDoc}
720     */
721     public int drainTo(Collection<? super E> c) {
722 jsr166 1.21 return drainTo(c, Integer.MAX_VALUE);
723 dl 1.1 }
724    
725 jsr166 1.9 /**
726     * @throws UnsupportedOperationException {@inheritDoc}
727     * @throws ClassCastException {@inheritDoc}
728     * @throws NullPointerException {@inheritDoc}
729     * @throws IllegalArgumentException {@inheritDoc}
730     */
731     public int drainTo(Collection<? super E> c, int maxElements) {
732     if (c == null)
733     throw new NullPointerException();
734     if (c == this)
735     throw new IllegalArgumentException();
736 jsr166 1.30 if (maxElements <= 0)
737     return 0;
738 jsr166 1.21 final ReentrantLock lock = this.lock;
739 dl 1.1 lock.lock();
740     try {
741 jsr166 1.21 int n = Math.min(maxElements, count);
742     for (int i = 0; i < n; i++) {
743     c.add(first.item); // In this order, in case add() throws.
744     unlinkFirst();
745 dl 1.1 }
746 jsr166 1.9 return n;
747     } finally {
748 jsr166 1.65 // checkInvariants();
749 jsr166 1.9 lock.unlock();
750     }
751     }
752    
753     // Stack methods
754    
755     /**
756 jsr166 1.46 * @throws IllegalStateException if this deque is full
757     * @throws NullPointerException {@inheritDoc}
758 jsr166 1.9 */
759     public void push(E e) {
760 jsr166 1.19 addFirst(e);
761 jsr166 1.9 }
762    
763     /**
764     * @throws NoSuchElementException {@inheritDoc}
765     */
766     public E pop() {
767 jsr166 1.19 return removeFirst();
768 jsr166 1.9 }
769    
770     // Collection methods
771    
772 jsr166 1.11 /**
773     * Removes the first occurrence of the specified element from this deque.
774     * If the deque does not contain the element, it is unchanged.
775 jsr166 1.21 * More formally, removes the first element {@code e} such that
776     * {@code o.equals(e)} (if such an element exists).
777     * Returns {@code true} if this deque contained the specified element
778 jsr166 1.11 * (or equivalently, if this deque changed as a result of the call).
779     *
780     * <p>This method is equivalent to
781     * {@link #removeFirstOccurrence(Object) removeFirstOccurrence}.
782     *
783     * @param o element to be removed from this deque, if present
784 jsr166 1.21 * @return {@code true} if this deque changed as a result of the call
785 jsr166 1.11 */
786 jsr166 1.9 public boolean remove(Object o) {
787 jsr166 1.19 return removeFirstOccurrence(o);
788 jsr166 1.9 }
789    
790     /**
791     * Returns the number of elements in this deque.
792     *
793     * @return the number of elements in this deque
794     */
795     public int size() {
796 jsr166 1.21 final ReentrantLock lock = this.lock;
797 jsr166 1.9 lock.lock();
798     try {
799     return count;
800 dl 1.1 } finally {
801 jsr166 1.65 // checkInvariants();
802 dl 1.1 lock.unlock();
803     }
804     }
805    
806 jsr166 1.9 /**
807 jsr166 1.21 * Returns {@code true} if this deque contains the specified element.
808     * More formally, returns {@code true} if and only if this deque contains
809     * at least one element {@code e} such that {@code o.equals(e)}.
810 jsr166 1.9 *
811     * @param o object to be checked for containment in this deque
812 jsr166 1.21 * @return {@code true} if this deque contains the specified element
813 jsr166 1.9 */
814     public boolean contains(Object o) {
815     if (o == null) return false;
816 jsr166 1.21 final ReentrantLock lock = this.lock;
817 dl 1.1 lock.lock();
818     try {
819 jsr166 1.9 for (Node<E> p = first; p != null; p = p.next)
820     if (o.equals(p.item))
821 dl 1.1 return true;
822     return false;
823     } finally {
824 jsr166 1.65 // checkInvariants();
825 dl 1.1 lock.unlock();
826     }
827     }
828    
829 jsr166 1.21 /*
830     * TODO: Add support for more efficient bulk operations.
831     *
832     * We don't want to acquire the lock for every iteration, but we
833     * also want other threads a chance to interact with the
834     * collection, especially when count is close to capacity.
835     */
836    
837     // /**
838     // * Adds all of the elements in the specified collection to this
839     // * queue. Attempts to addAll of a queue to itself result in
840     // * {@code IllegalArgumentException}. Further, the behavior of
841     // * this operation is undefined if the specified collection is
842     // * modified while the operation is in progress.
843     // *
844     // * @param c collection containing elements to be added to this queue
845     // * @return {@code true} if this queue changed as a result of the call
846     // * @throws ClassCastException {@inheritDoc}
847     // * @throws NullPointerException {@inheritDoc}
848     // * @throws IllegalArgumentException {@inheritDoc}
849 jsr166 1.46 // * @throws IllegalStateException if this deque is full
850 jsr166 1.21 // * @see #add(Object)
851     // */
852     // public boolean addAll(Collection<? extends E> c) {
853     // if (c == null)
854     // throw new NullPointerException();
855     // if (c == this)
856     // throw new IllegalArgumentException();
857     // final ReentrantLock lock = this.lock;
858     // lock.lock();
859     // try {
860     // boolean modified = false;
861     // for (E e : c)
862     // if (linkLast(e))
863     // modified = true;
864     // return modified;
865     // } finally {
866     // lock.unlock();
867     // }
868     // }
869 dl 1.1
870 jsr166 1.9 /**
871     * Returns an array containing all of the elements in this deque, in
872     * proper sequence (from first to last element).
873     *
874     * <p>The returned array will be "safe" in that no references to it are
875     * maintained by this deque. (In other words, this method must allocate
876     * a new array). The caller is thus free to modify the returned array.
877 jsr166 1.10 *
878 jsr166 1.9 * <p>This method acts as bridge between array-based and collection-based
879     * APIs.
880     *
881     * @return an array containing all of the elements in this deque
882     */
883 jsr166 1.21 @SuppressWarnings("unchecked")
884 dl 1.1 public Object[] toArray() {
885 jsr166 1.21 final ReentrantLock lock = this.lock;
886 dl 1.1 lock.lock();
887     try {
888     Object[] a = new Object[count];
889     int k = 0;
890 jsr166 1.3 for (Node<E> p = first; p != null; p = p.next)
891 dl 1.1 a[k++] = p.item;
892     return a;
893     } finally {
894 jsr166 1.65 // checkInvariants();
895 dl 1.1 lock.unlock();
896     }
897     }
898    
899 jsr166 1.9 /**
900     * Returns an array containing all of the elements in this deque, in
901     * proper sequence; the runtime type of the returned array is that of
902     * the specified array. If the deque fits in the specified array, it
903     * is returned therein. Otherwise, a new array is allocated with the
904     * runtime type of the specified array and the size of this deque.
905     *
906     * <p>If this deque fits in the specified array with room to spare
907     * (i.e., the array has more elements than this deque), the element in
908     * the array immediately following the end of the deque is set to
909 jsr166 1.21 * {@code null}.
910 jsr166 1.9 *
911     * <p>Like the {@link #toArray()} method, this method acts as bridge between
912     * array-based and collection-based APIs. Further, this method allows
913     * precise control over the runtime type of the output array, and may,
914     * under certain circumstances, be used to save allocation costs.
915     *
916 jsr166 1.21 * <p>Suppose {@code x} is a deque known to contain only strings.
917 jsr166 1.9 * The following code can be used to dump the deque into a newly
918 jsr166 1.21 * allocated array of {@code String}:
919 jsr166 1.9 *
920 jsr166 1.55 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
921 jsr166 1.9 *
922 jsr166 1.21 * Note that {@code toArray(new Object[0])} is identical in function to
923     * {@code toArray()}.
924 jsr166 1.9 *
925     * @param a the array into which the elements of the deque are to
926     * be stored, if it is big enough; otherwise, a new array of the
927     * same runtime type is allocated for this purpose
928     * @return an array containing all of the elements in this deque
929     * @throws ArrayStoreException if the runtime type of the specified array
930     * is not a supertype of the runtime type of every element in
931     * this deque
932     * @throws NullPointerException if the specified array is null
933     */
934 jsr166 1.21 @SuppressWarnings("unchecked")
935 dl 1.1 public <T> T[] toArray(T[] a) {
936 jsr166 1.21 final ReentrantLock lock = this.lock;
937 dl 1.1 lock.lock();
938     try {
939     if (a.length < count)
940 jsr166 1.21 a = (T[])java.lang.reflect.Array.newInstance
941     (a.getClass().getComponentType(), count);
942 dl 1.1
943     int k = 0;
944 jsr166 1.3 for (Node<E> p = first; p != null; p = p.next)
945 dl 1.1 a[k++] = (T)p.item;
946     if (a.length > k)
947     a[k] = null;
948     return a;
949     } finally {
950 jsr166 1.65 // checkInvariants();
951 dl 1.1 lock.unlock();
952     }
953     }
954    
955     public String toString() {
956 jsr166 1.56 return Helpers.collectionToString(this);
957 dl 1.1 }
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 jsr166 1.65 // checkInvariants();
979 dl 1.1 lock.unlock();
980     }
981     }
982    
983     /**
984     * Returns an iterator over the elements in this deque in proper sequence.
985 jsr166 1.9 * The elements will be returned in order from first (head) to last (tail).
986 jsr166 1.26 *
987 jsr166 1.51 * <p>The returned iterator is
988     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
989 dl 1.1 *
990 jsr166 1.9 * @return an iterator over the elements in this deque in proper sequence
991 dl 1.1 */
992     public Iterator<E> iterator() {
993     return new Itr();
994     }
995    
996     /**
997 dl 1.14 * Returns an iterator over the elements in this deque in reverse
998     * sequential order. The elements will be returned in order from
999     * last (tail) to first (head).
1000 jsr166 1.26 *
1001 jsr166 1.51 * <p>The returned iterator is
1002     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1003 jsr166 1.26 *
1004     * @return an iterator over the elements in this deque in reverse order
1005 dl 1.14 */
1006     public Iterator<E> descendingIterator() {
1007     return new DescendingItr();
1008     }
1009    
1010     /**
1011 jsr166 1.58 * Base class for LinkedBlockingDeque iterators.
1012 dl 1.1 */
1013 dl 1.16 private abstract class AbstractItr implements Iterator<E> {
1014 jsr166 1.15 /**
1015 jsr166 1.58 * The next node to return in next().
1016 dl 1.14 */
1017 jsr166 1.28 Node<E> next;
1018 dl 1.1
1019     /**
1020     * nextItem holds on to item fields because once we claim that
1021     * an element exists in hasNext(), we must return item read
1022     * under lock (in advance()) even if it was in the process of
1023     * being removed when hasNext() was called.
1024 jsr166 1.3 */
1025 dl 1.14 E nextItem;
1026 dl 1.1
1027     /**
1028     * Node returned by most recent call to next. Needed by remove.
1029     * Reset to null if this element is deleted by a call to remove.
1030     */
1031 dl 1.16 private Node<E> lastRet;
1032    
1033 jsr166 1.21 abstract Node<E> firstNode();
1034     abstract Node<E> nextNode(Node<E> n);
1035    
1036 jsr166 1.66 private Node<E> succ(Node<E> p) {
1037     return (p == (p = nextNode(p))) ? firstNode() : p;
1038     }
1039    
1040 dl 1.16 AbstractItr() {
1041 jsr166 1.21 // set to initial position
1042     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1043     lock.lock();
1044     try {
1045 jsr166 1.66 if ((next = firstNode()) != null)
1046     nextItem = next.item;
1047 jsr166 1.21 } finally {
1048 jsr166 1.65 // checkInvariants();
1049 jsr166 1.21 lock.unlock();
1050     }
1051 dl 1.16 }
1052 dl 1.1
1053     /**
1054 jsr166 1.21 * Advances next.
1055 dl 1.1 */
1056 jsr166 1.21 void advance() {
1057 jsr166 1.66 // assert next != null;
1058 jsr166 1.21 final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1059     lock.lock();
1060     try {
1061 jsr166 1.66 // Chains of deleted nodes ending in null or self-links
1062     // are possible if multiple interior nodes are removed.
1063     for (next = nextNode(next);; next = succ(next)) {
1064     if (next == null) {
1065     nextItem = null;
1066     break;
1067     } else if ((nextItem = next.item) != null)
1068     break;
1069     }
1070 jsr166 1.21 } finally {
1071 jsr166 1.65 // checkInvariants();
1072 jsr166 1.21 lock.unlock();
1073     }
1074     }
1075 dl 1.1
1076     public boolean hasNext() {
1077     return next != null;
1078     }
1079    
1080     public E next() {
1081     if (next == null)
1082     throw new NoSuchElementException();
1083 dl 1.14 lastRet = next;
1084 dl 1.1 E x = nextItem;
1085     advance();
1086     return x;
1087     }
1088    
1089     public void remove() {
1090 dl 1.14 Node<E> n = lastRet;
1091 dl 1.1 if (n == null)
1092     throw new IllegalStateException();
1093 dl 1.14 lastRet = null;
1094     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1095     lock.lock();
1096     try {
1097 jsr166 1.21 if (n.item != null)
1098     unlink(n);
1099 dl 1.14 } finally {
1100 jsr166 1.65 // checkInvariants();
1101 dl 1.14 lock.unlock();
1102     }
1103     }
1104     }
1105    
1106 jsr166 1.21 /** Forward iterator */
1107     private class Itr extends AbstractItr {
1108     Node<E> firstNode() { return first; }
1109     Node<E> nextNode(Node<E> n) { return n.next; }
1110     }
1111    
1112     /** Descending iterator */
1113 dl 1.16 private class DescendingItr extends AbstractItr {
1114 jsr166 1.21 Node<E> firstNode() { return last; }
1115     Node<E> nextNode(Node<E> n) { return n.prev; }
1116 dl 1.14 }
1117    
1118 jsr166 1.66 /**
1119     * A customized variant of Spliterators.IteratorSpliterator.
1120     * Keep this class in sync with (very similar) LBQSpliterator.
1121     */
1122 jsr166 1.64 private final class LBDSpliterator implements Spliterator<E> {
1123 dl 1.43 static final int MAX_BATCH = 1 << 25; // max batch array size;
1124 dl 1.36 Node<E> current; // current node; null until initialized
1125     int batch; // batch size for splits
1126     boolean exhausted; // true when no more nodes
1127 jsr166 1.66 long est = size(); // size estimate
1128    
1129     LBDSpliterator() {}
1130 jsr166 1.64
1131 jsr166 1.66 private Node<E> succ(Node<E> p) {
1132     return (p == (p = p.next)) ? first : p;
1133     }
1134 dl 1.36
1135     public long estimateSize() { return est; }
1136    
1137     public Spliterator<E> trySplit() {
1138 dl 1.43 Node<E> h;
1139     int b = batch;
1140     int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
1141 jsr166 1.41 if (!exhausted &&
1142 jsr166 1.66 ((h = current) != null || (h = first) != null)
1143 jsr166 1.60 && h.next != null) {
1144 dl 1.47 Object[] a = new Object[n];
1145 jsr166 1.64 final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1146 dl 1.36 int i = 0;
1147     Node<E> p = current;
1148     lock.lock();
1149     try {
1150 jsr166 1.66 if (p != null || (p = first) != null)
1151     for (; p != null && i < n; p = succ(p))
1152     if ((a[i] = p.item) != null)
1153     i++;
1154 dl 1.36 } finally {
1155 jsr166 1.65 // checkInvariants();
1156 dl 1.36 lock.unlock();
1157     }
1158     if ((current = p) == null) {
1159     est = 0L;
1160     exhausted = true;
1161     }
1162 dl 1.40 else if ((est -= i) < 0L)
1163     est = 0L;
1164 dl 1.43 if (i > 0) {
1165     batch = i;
1166     return Spliterators.spliterator
1167 jsr166 1.57 (a, 0, i, (Spliterator.ORDERED |
1168     Spliterator.NONNULL |
1169     Spliterator.CONCURRENT));
1170 dl 1.43 }
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 jsr166 1.66 if (!exhausted) {
1178     exhausted = true;
1179     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1180     Node<E> p = current;
1181     current = null;
1182     do {
1183     E e = null;
1184     lock.lock();
1185     try {
1186     if (p != null || (p = first) != null)
1187     do {
1188     e = p.item;
1189     p = succ(p);
1190     } while (e == null && p != null);
1191     } finally {
1192     // checkInvariants();
1193     lock.unlock();
1194     }
1195     if (e != null)
1196     action.accept(e);
1197     } while (p != null);
1198     }
1199     }
1200    
1201     public boolean tryAdvance(Consumer<? super E> action) {
1202     if (action == null) throw new NullPointerException();
1203     if (!exhausted) {
1204     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1205     Node<E> p = current;
1206 jsr166 1.62 E e = null;
1207 dl 1.36 lock.lock();
1208     try {
1209 jsr166 1.66 if (p != null || (p = first) != null)
1210     do {
1211     e = p.item;
1212     p = succ(p);
1213     } while (e == null && p != null);
1214 dl 1.36 } finally {
1215 jsr166 1.65 // checkInvariants();
1216 dl 1.36 lock.unlock();
1217     }
1218 jsr166 1.66 exhausted = ((current = p) == null);
1219     if (e != null) {
1220 jsr166 1.62 action.accept(e);
1221 jsr166 1.66 return true;
1222 jsr166 1.62 }
1223 dl 1.36 }
1224 jsr166 1.66 return false;
1225 dl 1.36 }
1226    
1227     public int characteristics() {
1228 jsr166 1.60 return (Spliterator.ORDERED |
1229     Spliterator.NONNULL |
1230     Spliterator.CONCURRENT);
1231 dl 1.36 }
1232     }
1233    
1234 jsr166 1.50 /**
1235     * Returns a {@link Spliterator} over the elements in this deque.
1236     *
1237 jsr166 1.51 * <p>The returned spliterator is
1238     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1239     *
1240 jsr166 1.50 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1241     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1242     *
1243     * @implNote
1244     * The {@code Spliterator} implements {@code trySplit} to permit limited
1245     * parallelism.
1246     *
1247     * @return a {@code Spliterator} over the elements in this deque
1248     * @since 1.8
1249     */
1250 dl 1.39 public Spliterator<E> spliterator() {
1251 jsr166 1.64 return new LBDSpliterator();
1252 dl 1.36 }
1253    
1254 dl 1.1 /**
1255 jsr166 1.34 * Saves this deque to a stream (that is, serializes it).
1256 dl 1.1 *
1257 jsr166 1.48 * @param s the stream
1258 jsr166 1.49 * @throws java.io.IOException if an I/O error occurs
1259 dl 1.1 * @serialData The capacity (int), followed by elements (each an
1260 jsr166 1.21 * {@code Object}) in the proper order, followed by a null
1261 dl 1.1 */
1262     private void writeObject(java.io.ObjectOutputStream s)
1263     throws java.io.IOException {
1264 jsr166 1.21 final ReentrantLock lock = this.lock;
1265 dl 1.1 lock.lock();
1266     try {
1267     // Write out capacity and any hidden stuff
1268     s.defaultWriteObject();
1269     // Write out all elements in the proper order.
1270     for (Node<E> p = first; p != null; p = p.next)
1271     s.writeObject(p.item);
1272     // Use trailing null as sentinel
1273     s.writeObject(null);
1274     } finally {
1275 jsr166 1.65 // checkInvariants();
1276 dl 1.1 lock.unlock();
1277     }
1278     }
1279    
1280     /**
1281 jsr166 1.31 * Reconstitutes this deque from a stream (that is, deserializes it).
1282 jsr166 1.48 * @param s the stream
1283 jsr166 1.49 * @throws ClassNotFoundException if the class of a serialized object
1284     * could not be found
1285     * @throws java.io.IOException if an I/O error occurs
1286 dl 1.1 */
1287     private void readObject(java.io.ObjectInputStream s)
1288     throws java.io.IOException, ClassNotFoundException {
1289     s.defaultReadObject();
1290     count = 0;
1291     first = null;
1292     last = null;
1293     // Read in all elements and place in queue
1294     for (;;) {
1295 jsr166 1.21 @SuppressWarnings("unchecked")
1296 dl 1.1 E item = (E)s.readObject();
1297     if (item == null)
1298     break;
1299     add(item);
1300     }
1301     }
1302 jsr166 1.3
1303 jsr166 1.65 void checkInvariants() {
1304     // assert lock.isHeldByCurrentThread();
1305     // Nodes may get self-linked or lose their item, but only
1306     // after being unlinked and becoming unreachable from first.
1307     for (Node<E> p = first; p != null; p = p.next) {
1308     // assert p.next != p;
1309     // assert p.item != null;
1310     }
1311     }
1312    
1313 dl 1.1 }