ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingDeque.java
Revision: 1.74
Committed: Tue Dec 27 02:26:23 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.73: +141 -52 lines
Log Message:
optimized bulk add and remove implementations

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.67 import java.util.Objects;
14 jsr166 1.53 import java.util.Spliterator;
15     import java.util.Spliterators;
16 jsr166 1.21 import java.util.concurrent.locks.Condition;
17     import java.util.concurrent.locks.ReentrantLock;
18 jsr166 1.53 import java.util.function.Consumer;
19 jsr166 1.74 import java.util.function.Predicate;
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.74 addAll(c);
171 dl 1.1 }
172    
173    
174     // Basic linking and unlinking operations, called only while holding lock
175    
176     /**
177 dl 1.23 * Links node as first element, or returns false if full.
178 dl 1.1 */
179 dl 1.23 private boolean linkFirst(Node<E> node) {
180 jsr166 1.21 // assert lock.isHeldByCurrentThread();
181 dl 1.1 if (count >= capacity)
182     return false;
183     Node<E> f = first;
184 dl 1.23 node.next = f;
185     first = node;
186 dl 1.1 if (last == null)
187 dl 1.23 last = node;
188 dl 1.1 else
189 dl 1.23 f.prev = node;
190 jsr166 1.21 ++count;
191 dl 1.1 notEmpty.signal();
192     return true;
193     }
194    
195     /**
196 dl 1.23 * Links node as last element, or returns false if full.
197 dl 1.1 */
198 dl 1.23 private boolean linkLast(Node<E> node) {
199 jsr166 1.21 // assert lock.isHeldByCurrentThread();
200 dl 1.1 if (count >= capacity)
201     return false;
202     Node<E> l = last;
203 dl 1.23 node.prev = l;
204     last = node;
205 dl 1.1 if (first == null)
206 dl 1.23 first = node;
207 dl 1.1 else
208 dl 1.23 l.next = node;
209 jsr166 1.21 ++count;
210 dl 1.1 notEmpty.signal();
211     return true;
212     }
213    
214     /**
215 jsr166 1.3 * Removes and returns first element, or null if empty.
216 dl 1.1 */
217     private E unlinkFirst() {
218 jsr166 1.21 // assert lock.isHeldByCurrentThread();
219 dl 1.1 Node<E> f = first;
220     if (f == null)
221     return null;
222     Node<E> n = f.next;
223 jsr166 1.21 E item = f.item;
224     f.item = null;
225     f.next = f; // help GC
226 dl 1.1 first = n;
227 jsr166 1.3 if (n == null)
228 dl 1.1 last = null;
229 jsr166 1.3 else
230 dl 1.1 n.prev = null;
231     --count;
232     notFull.signal();
233 jsr166 1.21 return item;
234 dl 1.1 }
235    
236     /**
237 jsr166 1.3 * Removes and returns last element, or null if empty.
238 dl 1.1 */
239     private E unlinkLast() {
240 jsr166 1.21 // assert lock.isHeldByCurrentThread();
241 dl 1.1 Node<E> l = last;
242     if (l == null)
243     return null;
244     Node<E> p = l.prev;
245 jsr166 1.21 E item = l.item;
246     l.item = null;
247     l.prev = l; // help GC
248 dl 1.1 last = p;
249 jsr166 1.3 if (p == null)
250 dl 1.1 first = null;
251 jsr166 1.3 else
252 dl 1.1 p.next = null;
253     --count;
254     notFull.signal();
255 jsr166 1.21 return item;
256 dl 1.1 }
257    
258     /**
259 jsr166 1.21 * Unlinks x.
260 dl 1.1 */
261 jsr166 1.21 void unlink(Node<E> x) {
262     // assert lock.isHeldByCurrentThread();
263 dl 1.1 Node<E> p = x.prev;
264     Node<E> n = x.next;
265     if (p == null) {
266 jsr166 1.21 unlinkFirst();
267 dl 1.1 } else if (n == null) {
268 jsr166 1.21 unlinkLast();
269 dl 1.1 } else {
270     p.next = n;
271     n.prev = p;
272 jsr166 1.21 x.item = null;
273     // Don't mess with x's links. They may still be in use by
274     // an iterator.
275     --count;
276     notFull.signal();
277 dl 1.1 }
278     }
279    
280 jsr166 1.9 // BlockingDeque methods
281 dl 1.1
282 jsr166 1.9 /**
283 jsr166 1.46 * @throws IllegalStateException if this deque is full
284     * @throws NullPointerException {@inheritDoc}
285 jsr166 1.9 */
286     public void addFirst(E e) {
287     if (!offerFirst(e))
288     throw new IllegalStateException("Deque full");
289     }
290    
291     /**
292 jsr166 1.46 * @throws IllegalStateException if this deque is full
293 jsr166 1.9 * @throws NullPointerException {@inheritDoc}
294     */
295     public void addLast(E e) {
296     if (!offerLast(e))
297     throw new IllegalStateException("Deque full");
298     }
299    
300     /**
301     * @throws NullPointerException {@inheritDoc}
302     */
303 jsr166 1.6 public boolean offerFirst(E e) {
304     if (e == null) throw new NullPointerException();
305 dl 1.23 Node<E> node = new Node<E>(e);
306 jsr166 1.21 final ReentrantLock lock = this.lock;
307 dl 1.1 lock.lock();
308     try {
309 dl 1.23 return linkFirst(node);
310 dl 1.1 } finally {
311 jsr166 1.65 // checkInvariants();
312 dl 1.1 lock.unlock();
313     }
314     }
315    
316 jsr166 1.9 /**
317     * @throws NullPointerException {@inheritDoc}
318     */
319 jsr166 1.6 public boolean offerLast(E e) {
320     if (e == null) throw new NullPointerException();
321 dl 1.23 Node<E> node = new Node<E>(e);
322 jsr166 1.21 final ReentrantLock lock = this.lock;
323 dl 1.1 lock.lock();
324     try {
325 dl 1.23 return linkLast(node);
326 dl 1.1 } finally {
327 jsr166 1.65 // checkInvariants();
328 dl 1.1 lock.unlock();
329     }
330     }
331    
332 jsr166 1.9 /**
333     * @throws NullPointerException {@inheritDoc}
334     * @throws InterruptedException {@inheritDoc}
335     */
336     public void putFirst(E e) throws InterruptedException {
337     if (e == null) throw new NullPointerException();
338 dl 1.23 Node<E> node = new Node<E>(e);
339 jsr166 1.21 final ReentrantLock lock = this.lock;
340 dl 1.1 lock.lock();
341     try {
342 dl 1.23 while (!linkFirst(node))
343 jsr166 1.9 notFull.await();
344 dl 1.1 } finally {
345 jsr166 1.65 // checkInvariants();
346 dl 1.1 lock.unlock();
347     }
348     }
349    
350 jsr166 1.9 /**
351     * @throws NullPointerException {@inheritDoc}
352     * @throws InterruptedException {@inheritDoc}
353     */
354     public void putLast(E e) throws InterruptedException {
355     if (e == null) throw new NullPointerException();
356 dl 1.23 Node<E> node = new Node<E>(e);
357 jsr166 1.21 final ReentrantLock lock = this.lock;
358 dl 1.1 lock.lock();
359     try {
360 dl 1.23 while (!linkLast(node))
361 jsr166 1.9 notFull.await();
362 dl 1.1 } finally {
363 jsr166 1.65 // checkInvariants();
364 dl 1.1 lock.unlock();
365     }
366     }
367    
368 jsr166 1.9 /**
369     * @throws NullPointerException {@inheritDoc}
370     * @throws InterruptedException {@inheritDoc}
371     */
372     public boolean offerFirst(E e, long timeout, TimeUnit unit)
373     throws InterruptedException {
374     if (e == null) throw new NullPointerException();
375 dl 1.23 Node<E> node = new Node<E>(e);
376 jsr166 1.19 long nanos = unit.toNanos(timeout);
377 jsr166 1.21 final ReentrantLock lock = this.lock;
378 jsr166 1.9 lock.lockInterruptibly();
379 dl 1.1 try {
380 dl 1.23 while (!linkFirst(node)) {
381 jsr166 1.59 if (nanos <= 0L)
382 jsr166 1.9 return false;
383     nanos = notFull.awaitNanos(nanos);
384     }
385 jsr166 1.21 return true;
386 dl 1.1 } finally {
387 jsr166 1.65 // checkInvariants();
388 dl 1.1 lock.unlock();
389     }
390     }
391    
392 jsr166 1.9 /**
393     * @throws NullPointerException {@inheritDoc}
394     * @throws InterruptedException {@inheritDoc}
395     */
396     public boolean offerLast(E e, long timeout, TimeUnit unit)
397     throws InterruptedException {
398     if (e == null) throw new NullPointerException();
399 dl 1.23 Node<E> node = new Node<E>(e);
400 jsr166 1.19 long nanos = unit.toNanos(timeout);
401 jsr166 1.21 final ReentrantLock lock = this.lock;
402 jsr166 1.9 lock.lockInterruptibly();
403 dl 1.1 try {
404 dl 1.23 while (!linkLast(node)) {
405 jsr166 1.59 if (nanos <= 0L)
406 jsr166 1.9 return false;
407     nanos = notFull.awaitNanos(nanos);
408     }
409 jsr166 1.21 return true;
410 dl 1.1 } finally {
411 jsr166 1.65 // checkInvariants();
412 dl 1.1 lock.unlock();
413     }
414     }
415    
416 jsr166 1.9 /**
417     * @throws NoSuchElementException {@inheritDoc}
418     */
419     public E removeFirst() {
420     E x = pollFirst();
421 dl 1.1 if (x == null) throw new NoSuchElementException();
422     return x;
423     }
424    
425 jsr166 1.9 /**
426     * @throws NoSuchElementException {@inheritDoc}
427     */
428     public E removeLast() {
429     E x = pollLast();
430 dl 1.1 if (x == null) throw new NoSuchElementException();
431     return x;
432     }
433    
434 jsr166 1.9 public E pollFirst() {
435 jsr166 1.21 final ReentrantLock lock = this.lock;
436 dl 1.1 lock.lock();
437     try {
438 jsr166 1.9 return unlinkFirst();
439 dl 1.1 } finally {
440 jsr166 1.65 // checkInvariants();
441 dl 1.1 lock.unlock();
442     }
443     }
444    
445 jsr166 1.9 public E pollLast() {
446 jsr166 1.21 final ReentrantLock lock = this.lock;
447 dl 1.1 lock.lock();
448     try {
449 jsr166 1.9 return unlinkLast();
450 dl 1.1 } finally {
451 jsr166 1.65 // checkInvariants();
452 dl 1.1 lock.unlock();
453     }
454     }
455    
456     public E takeFirst() throws InterruptedException {
457 jsr166 1.21 final ReentrantLock lock = this.lock;
458 dl 1.1 lock.lock();
459     try {
460     E x;
461     while ( (x = unlinkFirst()) == null)
462     notEmpty.await();
463     return x;
464     } finally {
465 jsr166 1.65 // checkInvariants();
466 dl 1.1 lock.unlock();
467     }
468     }
469    
470     public E takeLast() throws InterruptedException {
471 jsr166 1.21 final ReentrantLock lock = this.lock;
472 dl 1.1 lock.lock();
473     try {
474     E x;
475     while ( (x = unlinkLast()) == null)
476     notEmpty.await();
477     return x;
478     } finally {
479 jsr166 1.65 // checkInvariants();
480 dl 1.1 lock.unlock();
481     }
482     }
483    
484 jsr166 1.9 public E pollFirst(long timeout, TimeUnit unit)
485 dl 1.1 throws InterruptedException {
486 jsr166 1.19 long nanos = unit.toNanos(timeout);
487 jsr166 1.21 final ReentrantLock lock = this.lock;
488 dl 1.1 lock.lockInterruptibly();
489     try {
490 jsr166 1.21 E x;
491     while ( (x = unlinkFirst()) == null) {
492 jsr166 1.59 if (nanos <= 0L)
493 jsr166 1.9 return null;
494     nanos = notEmpty.awaitNanos(nanos);
495 dl 1.1 }
496 jsr166 1.21 return x;
497 dl 1.1 } finally {
498 jsr166 1.65 // checkInvariants();
499 dl 1.1 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 jsr166 1.59 if (nanos <= 0L)
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 jsr166 1.65 // checkInvariants();
518 dl 1.1 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 jsr166 1.65 // checkInvariants();
547 jsr166 1.9 lock.unlock();
548     }
549     }
550    
551     public E peekLast() {
552 jsr166 1.21 final ReentrantLock lock = this.lock;
553 jsr166 1.9 lock.lock();
554     try {
555     return (last == null) ? null : last.item;
556     } finally {
557 jsr166 1.65 // checkInvariants();
558 jsr166 1.9 lock.unlock();
559     }
560     }
561    
562     public boolean removeFirstOccurrence(Object o) {
563     if (o == null) return false;
564 jsr166 1.21 final ReentrantLock lock = this.lock;
565 jsr166 1.9 lock.lock();
566 dl 1.1 try {
567 jsr166 1.9 for (Node<E> p = first; p != null; p = p.next) {
568     if (o.equals(p.item)) {
569     unlink(p);
570     return true;
571     }
572 dl 1.1 }
573 jsr166 1.9 return false;
574 dl 1.1 } finally {
575 jsr166 1.65 // checkInvariants();
576 dl 1.1 lock.unlock();
577     }
578     }
579    
580 jsr166 1.9 public boolean removeLastOccurrence(Object o) {
581     if (o == null) return false;
582 jsr166 1.21 final ReentrantLock lock = this.lock;
583 jsr166 1.9 lock.lock();
584 dl 1.1 try {
585 jsr166 1.9 for (Node<E> p = last; p != null; p = p.prev) {
586     if (o.equals(p.item)) {
587     unlink(p);
588     return true;
589     }
590 dl 1.1 }
591 jsr166 1.9 return false;
592 dl 1.1 } finally {
593 jsr166 1.65 // checkInvariants();
594 dl 1.1 lock.unlock();
595     }
596     }
597    
598 jsr166 1.9 // BlockingQueue methods
599 dl 1.1
600 jsr166 1.9 /**
601     * Inserts the specified element at the end of this deque unless it would
602     * violate capacity restrictions. When using a capacity-restricted deque,
603     * it is generally preferable to use method {@link #offer(Object) offer}.
604     *
605 jsr166 1.13 * <p>This method is equivalent to {@link #addLast}.
606 jsr166 1.9 *
607 jsr166 1.46 * @throws IllegalStateException if this deque is full
608 jsr166 1.9 * @throws NullPointerException if the specified element is null
609     */
610     public boolean add(E e) {
611 jsr166 1.19 addLast(e);
612     return true;
613 jsr166 1.9 }
614    
615     /**
616     * @throws NullPointerException if the specified element is null
617     */
618     public boolean offer(E e) {
619 jsr166 1.19 return offerLast(e);
620 jsr166 1.9 }
621 dl 1.1
622 jsr166 1.9 /**
623     * @throws NullPointerException {@inheritDoc}
624     * @throws InterruptedException {@inheritDoc}
625     */
626     public void put(E e) throws InterruptedException {
627 jsr166 1.19 putLast(e);
628 jsr166 1.9 }
629 dl 1.1
630 jsr166 1.9 /**
631     * @throws NullPointerException {@inheritDoc}
632     * @throws InterruptedException {@inheritDoc}
633     */
634 jsr166 1.7 public boolean offer(E e, long timeout, TimeUnit unit)
635 jsr166 1.9 throws InterruptedException {
636 jsr166 1.19 return offerLast(e, timeout, unit);
637 jsr166 1.9 }
638    
639     /**
640     * Retrieves and removes the head of the queue represented by this deque.
641     * This method differs from {@link #poll poll} only in that it throws an
642     * exception if this deque is empty.
643     *
644     * <p>This method is equivalent to {@link #removeFirst() removeFirst}.
645     *
646     * @return the head of the queue represented by this deque
647     * @throws NoSuchElementException if this deque is empty
648     */
649     public E remove() {
650 jsr166 1.19 return removeFirst();
651 jsr166 1.9 }
652    
653     public E poll() {
654 jsr166 1.19 return pollFirst();
655 jsr166 1.9 }
656    
657     public E take() throws InterruptedException {
658 jsr166 1.19 return takeFirst();
659 jsr166 1.9 }
660    
661     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
662 jsr166 1.19 return pollFirst(timeout, unit);
663 jsr166 1.9 }
664 dl 1.1
665     /**
666 jsr166 1.9 * Retrieves, but does not remove, the head of the queue represented by
667     * this deque. This method differs from {@link #peek peek} only in that
668     * it throws an exception if this deque is empty.
669     *
670     * <p>This method is equivalent to {@link #getFirst() getFirst}.
671 dl 1.1 *
672 jsr166 1.9 * @return the head of the queue represented by this deque
673     * @throws NoSuchElementException if this deque is empty
674 dl 1.1 */
675 jsr166 1.9 public E element() {
676 jsr166 1.19 return getFirst();
677 jsr166 1.9 }
678    
679     public E peek() {
680 jsr166 1.19 return peekFirst();
681 dl 1.1 }
682    
683     /**
684 jsr166 1.4 * Returns the number of additional elements that this deque can ideally
685     * (in the absence of memory or resource constraints) accept without
686 dl 1.1 * blocking. This is always equal to the initial capacity of this deque
687 jsr166 1.21 * less the current {@code size} of this deque.
688 jsr166 1.4 *
689     * <p>Note that you <em>cannot</em> always tell if an attempt to insert
690 jsr166 1.21 * an element will succeed by inspecting {@code remainingCapacity}
691 jsr166 1.4 * because it may be the case that another thread is about to
692 jsr166 1.9 * insert or remove an element.
693 dl 1.1 */
694     public int remainingCapacity() {
695 jsr166 1.21 final ReentrantLock lock = this.lock;
696 dl 1.1 lock.lock();
697     try {
698     return capacity - count;
699     } finally {
700 jsr166 1.65 // checkInvariants();
701 dl 1.1 lock.unlock();
702     }
703     }
704    
705 jsr166 1.9 /**
706     * @throws UnsupportedOperationException {@inheritDoc}
707     * @throws ClassCastException {@inheritDoc}
708     * @throws NullPointerException {@inheritDoc}
709     * @throws IllegalArgumentException {@inheritDoc}
710     */
711     public int drainTo(Collection<? super E> c) {
712 jsr166 1.21 return drainTo(c, Integer.MAX_VALUE);
713 dl 1.1 }
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, int maxElements) {
722 jsr166 1.67 Objects.requireNonNull(c);
723 jsr166 1.9 if (c == this)
724     throw new IllegalArgumentException();
725 jsr166 1.30 if (maxElements <= 0)
726     return 0;
727 jsr166 1.21 final ReentrantLock lock = this.lock;
728 dl 1.1 lock.lock();
729     try {
730 jsr166 1.21 int n = Math.min(maxElements, count);
731     for (int i = 0; i < n; i++) {
732     c.add(first.item); // In this order, in case add() throws.
733     unlinkFirst();
734 dl 1.1 }
735 jsr166 1.9 return n;
736     } finally {
737 jsr166 1.65 // checkInvariants();
738 jsr166 1.9 lock.unlock();
739     }
740     }
741    
742     // Stack methods
743    
744     /**
745 jsr166 1.46 * @throws IllegalStateException if this deque is full
746     * @throws NullPointerException {@inheritDoc}
747 jsr166 1.9 */
748     public void push(E e) {
749 jsr166 1.19 addFirst(e);
750 jsr166 1.9 }
751    
752     /**
753     * @throws NoSuchElementException {@inheritDoc}
754     */
755     public E pop() {
756 jsr166 1.19 return removeFirst();
757 jsr166 1.9 }
758    
759     // Collection methods
760    
761 jsr166 1.11 /**
762     * Removes the first occurrence of the specified element from this deque.
763     * If the deque does not contain the element, it is unchanged.
764 jsr166 1.21 * More formally, removes the first element {@code e} such that
765     * {@code o.equals(e)} (if such an element exists).
766     * Returns {@code true} if this deque contained the specified element
767 jsr166 1.11 * (or equivalently, if this deque changed as a result of the call).
768     *
769     * <p>This method is equivalent to
770     * {@link #removeFirstOccurrence(Object) removeFirstOccurrence}.
771     *
772     * @param o element to be removed from this deque, if present
773 jsr166 1.21 * @return {@code true} if this deque changed as a result of the call
774 jsr166 1.11 */
775 jsr166 1.9 public boolean remove(Object o) {
776 jsr166 1.19 return removeFirstOccurrence(o);
777 jsr166 1.9 }
778    
779     /**
780     * Returns the number of elements in this deque.
781     *
782     * @return the number of elements in this deque
783     */
784     public int size() {
785 jsr166 1.21 final ReentrantLock lock = this.lock;
786 jsr166 1.9 lock.lock();
787     try {
788     return count;
789 dl 1.1 } finally {
790 jsr166 1.65 // checkInvariants();
791 dl 1.1 lock.unlock();
792     }
793     }
794    
795 jsr166 1.9 /**
796 jsr166 1.21 * Returns {@code true} if this deque contains the specified element.
797     * More formally, returns {@code true} if and only if this deque contains
798     * at least one element {@code e} such that {@code o.equals(e)}.
799 jsr166 1.9 *
800     * @param o object to be checked for containment in this deque
801 jsr166 1.21 * @return {@code true} if this deque contains the specified element
802 jsr166 1.9 */
803     public boolean contains(Object o) {
804     if (o == null) return false;
805 jsr166 1.21 final ReentrantLock lock = this.lock;
806 dl 1.1 lock.lock();
807     try {
808 jsr166 1.9 for (Node<E> p = first; p != null; p = p.next)
809     if (o.equals(p.item))
810 dl 1.1 return true;
811     return false;
812     } finally {
813 jsr166 1.65 // checkInvariants();
814 dl 1.1 lock.unlock();
815     }
816     }
817    
818 jsr166 1.74 /**
819     * Appends all of the elements in the specified collection to the end of
820     * this deque, in the order that they are returned by the specified
821     * collection's iterator. Attempts to {@code addAll} of a deque to
822     * itself result in {@code IllegalArgumentException}.
823 jsr166 1.21 *
824 jsr166 1.74 * @param c the elements to be inserted into this deque
825     * @return {@code true} if this deque changed as a result of the call
826     * @throws NullPointerException if the specified collection or any
827     * of its elements are null
828     * @throws IllegalArgumentException if the collection is this deque
829     * @throws IllegalStateException if this deque is full
830     * @see #add(Object)
831     */
832     public boolean addAll(Collection<? extends E> c) {
833     if (c == this)
834     // As historically specified in AbstractQueue#addAll
835     throw new IllegalArgumentException();
836    
837     // Copy c into a private chain of Nodes
838     Node<E> beg = null, end = null;
839     int n = 0;
840     for (E e : c) {
841     Objects.requireNonNull(e);
842     n++;
843     Node<E> newNode = new Node<E>(e);
844     if (beg == null)
845     beg = end = newNode;
846     else {
847     end.next = newNode;
848     newNode.prev = end;
849     end = newNode;
850     }
851     }
852     if (beg == null)
853     return false;
854    
855     // Atomically append the chain at the end
856     final ReentrantLock lock = this.lock;
857     lock.lock();
858     try {
859     if (count + n <= capacity) {
860     beg.prev = last;
861     if (first == null)
862     first = beg;
863     else
864     last.next = beg;
865     last = end;
866     count += n;
867     notEmpty.signalAll();
868     return true;
869     }
870     } finally {
871     // checkInvariants();
872     lock.unlock();
873     }
874     // Fall back to historic non-atomic implementation, failing
875     // with IllegalStateException when the capacity is exceeded.
876     return super.addAll(c);
877     }
878 dl 1.1
879 jsr166 1.9 /**
880     * Returns an array containing all of the elements in this deque, in
881     * proper sequence (from first to last element).
882     *
883     * <p>The returned array will be "safe" in that no references to it are
884     * maintained by this deque. (In other words, this method must allocate
885     * a new array). The caller is thus free to modify the returned array.
886 jsr166 1.10 *
887 jsr166 1.9 * <p>This method acts as bridge between array-based and collection-based
888     * APIs.
889     *
890     * @return an array containing all of the elements in this deque
891     */
892 jsr166 1.21 @SuppressWarnings("unchecked")
893 dl 1.1 public Object[] toArray() {
894 jsr166 1.21 final ReentrantLock lock = this.lock;
895 dl 1.1 lock.lock();
896     try {
897     Object[] a = new Object[count];
898     int k = 0;
899 jsr166 1.3 for (Node<E> p = first; p != null; p = p.next)
900 dl 1.1 a[k++] = p.item;
901     return a;
902     } finally {
903 jsr166 1.65 // checkInvariants();
904 dl 1.1 lock.unlock();
905     }
906     }
907    
908 jsr166 1.9 /**
909     * Returns an array containing all of the elements in this deque, in
910     * proper sequence; the runtime type of the returned array is that of
911     * the specified array. If the deque fits in the specified array, it
912     * is returned therein. Otherwise, a new array is allocated with the
913     * runtime type of the specified array and the size of this deque.
914     *
915     * <p>If this deque fits in the specified array with room to spare
916     * (i.e., the array has more elements than this deque), the element in
917     * the array immediately following the end of the deque is set to
918 jsr166 1.21 * {@code null}.
919 jsr166 1.9 *
920     * <p>Like the {@link #toArray()} method, this method acts as bridge between
921     * array-based and collection-based APIs. Further, this method allows
922     * precise control over the runtime type of the output array, and may,
923     * under certain circumstances, be used to save allocation costs.
924     *
925 jsr166 1.21 * <p>Suppose {@code x} is a deque known to contain only strings.
926 jsr166 1.9 * The following code can be used to dump the deque into a newly
927 jsr166 1.21 * allocated array of {@code String}:
928 jsr166 1.9 *
929 jsr166 1.55 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
930 jsr166 1.9 *
931 jsr166 1.21 * Note that {@code toArray(new Object[0])} is identical in function to
932     * {@code toArray()}.
933 jsr166 1.9 *
934     * @param a the array into which the elements of the deque are to
935     * be stored, if it is big enough; otherwise, a new array of the
936     * same runtime type is allocated for this purpose
937     * @return an array containing all of the elements in this deque
938     * @throws ArrayStoreException if the runtime type of the specified array
939     * is not a supertype of the runtime type of every element in
940     * this deque
941     * @throws NullPointerException if the specified array is null
942     */
943 jsr166 1.21 @SuppressWarnings("unchecked")
944 dl 1.1 public <T> T[] toArray(T[] a) {
945 jsr166 1.21 final ReentrantLock lock = this.lock;
946 dl 1.1 lock.lock();
947     try {
948     if (a.length < count)
949 jsr166 1.21 a = (T[])java.lang.reflect.Array.newInstance
950     (a.getClass().getComponentType(), count);
951 dl 1.1
952     int k = 0;
953 jsr166 1.3 for (Node<E> p = first; p != null; p = p.next)
954 dl 1.1 a[k++] = (T)p.item;
955     if (a.length > k)
956     a[k] = null;
957     return a;
958     } finally {
959 jsr166 1.65 // checkInvariants();
960 dl 1.1 lock.unlock();
961     }
962     }
963    
964     public String toString() {
965 jsr166 1.56 return Helpers.collectionToString(this);
966 dl 1.1 }
967    
968     /**
969     * Atomically removes all of the elements from this deque.
970     * The deque will be empty after this call returns.
971     */
972     public void clear() {
973 jsr166 1.21 final ReentrantLock lock = this.lock;
974 dl 1.1 lock.lock();
975     try {
976 jsr166 1.21 for (Node<E> f = first; f != null; ) {
977     f.item = null;
978     Node<E> n = f.next;
979     f.prev = null;
980     f.next = null;
981     f = n;
982     }
983 dl 1.1 first = last = null;
984     count = 0;
985     notFull.signalAll();
986     } finally {
987 jsr166 1.65 // checkInvariants();
988 dl 1.1 lock.unlock();
989     }
990     }
991    
992     /**
993 jsr166 1.67 * Used for any element traversal that is not entirely under lock.
994     * Such traversals must handle both:
995     * - dequeued nodes (p.next == p)
996     * - (possibly multiple) interior removed nodes (p.item == null)
997     */
998     Node<E> succ(Node<E> p) {
999     return (p == (p = p.next)) ? first : p;
1000     }
1001    
1002     /**
1003 dl 1.1 * Returns an iterator over the elements in this deque in proper sequence.
1004 jsr166 1.9 * The elements will be returned in order from first (head) to last (tail).
1005 jsr166 1.26 *
1006 jsr166 1.51 * <p>The returned iterator is
1007     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1008 dl 1.1 *
1009 jsr166 1.9 * @return an iterator over the elements in this deque in proper sequence
1010 dl 1.1 */
1011     public Iterator<E> iterator() {
1012     return new Itr();
1013     }
1014    
1015     /**
1016 dl 1.14 * Returns an iterator over the elements in this deque in reverse
1017     * sequential order. The elements will be returned in order from
1018     * last (tail) to first (head).
1019 jsr166 1.26 *
1020 jsr166 1.51 * <p>The returned iterator is
1021     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1022 jsr166 1.26 *
1023     * @return an iterator over the elements in this deque in reverse order
1024 dl 1.14 */
1025     public Iterator<E> descendingIterator() {
1026     return new DescendingItr();
1027     }
1028    
1029     /**
1030 jsr166 1.58 * Base class for LinkedBlockingDeque iterators.
1031 dl 1.1 */
1032 dl 1.16 private abstract class AbstractItr implements Iterator<E> {
1033 jsr166 1.15 /**
1034 jsr166 1.58 * The next node to return in next().
1035 dl 1.14 */
1036 jsr166 1.28 Node<E> next;
1037 dl 1.1
1038     /**
1039     * nextItem holds on to item fields because once we claim that
1040     * an element exists in hasNext(), we must return item read
1041 jsr166 1.67 * under lock even if it was in the process of being removed
1042     * when hasNext() was called.
1043 jsr166 1.3 */
1044 dl 1.14 E nextItem;
1045 dl 1.1
1046     /**
1047     * Node returned by most recent call to next. Needed by remove.
1048     * Reset to null if this element is deleted by a call to remove.
1049     */
1050 dl 1.16 private Node<E> lastRet;
1051    
1052 jsr166 1.21 abstract Node<E> firstNode();
1053     abstract Node<E> nextNode(Node<E> n);
1054    
1055 jsr166 1.66 private Node<E> succ(Node<E> p) {
1056     return (p == (p = nextNode(p))) ? firstNode() : p;
1057     }
1058    
1059 dl 1.16 AbstractItr() {
1060 jsr166 1.21 // set to initial position
1061     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1062     lock.lock();
1063     try {
1064 jsr166 1.66 if ((next = firstNode()) != null)
1065     nextItem = next.item;
1066 jsr166 1.21 } finally {
1067 jsr166 1.65 // checkInvariants();
1068 jsr166 1.21 lock.unlock();
1069     }
1070 dl 1.16 }
1071 dl 1.1
1072 jsr166 1.67 public boolean hasNext() {
1073     return next != null;
1074     }
1075    
1076     public E next() {
1077     Node<E> p;
1078     if ((p = next) == null)
1079     throw new NoSuchElementException();
1080     lastRet = p;
1081 jsr166 1.69 E x = nextItem;
1082 jsr166 1.21 final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1083     lock.lock();
1084     try {
1085 jsr166 1.69 E e = null;
1086     for (p = nextNode(p); p != null && (e = p.item) == null; )
1087     p = succ(p);
1088     next = p;
1089     nextItem = e;
1090 jsr166 1.21 } finally {
1091 jsr166 1.65 // checkInvariants();
1092 jsr166 1.21 lock.unlock();
1093     }
1094 jsr166 1.69 return x;
1095 jsr166 1.21 }
1096 dl 1.1
1097 jsr166 1.67 public void forEachRemaining(Consumer<? super E> action) {
1098     // A variant of forEachFrom
1099     Objects.requireNonNull(action);
1100     Node<E> p;
1101     if ((p = next) == null) return;
1102 jsr166 1.71 lastRet = p;
1103 jsr166 1.67 next = null;
1104     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1105     final int batchSize = 32;
1106     Object[] es = null;
1107     int n, len = 1;
1108     do {
1109     lock.lock();
1110     try {
1111     if (es == null) {
1112     p = nextNode(p);
1113     for (Node<E> q = p; q != null; q = succ(q))
1114     if (q.item != null && ++len == batchSize)
1115     break;
1116     es = new Object[len];
1117     es[0] = nextItem;
1118     nextItem = null;
1119     n = 1;
1120     } else
1121     n = 0;
1122     for (; p != null && n < len; p = succ(p))
1123     if ((es[n] = p.item) != null) {
1124     lastRet = p;
1125     n++;
1126     }
1127     } finally {
1128     // checkInvariants();
1129     lock.unlock();
1130     }
1131     for (int i = 0; i < n; i++) {
1132     @SuppressWarnings("unchecked") E e = (E) es[i];
1133     action.accept(e);
1134     }
1135     } while (n > 0 && p != null);
1136 dl 1.1 }
1137    
1138     public void remove() {
1139 dl 1.14 Node<E> n = lastRet;
1140 dl 1.1 if (n == null)
1141     throw new IllegalStateException();
1142 dl 1.14 lastRet = null;
1143     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1144     lock.lock();
1145     try {
1146 jsr166 1.21 if (n.item != null)
1147     unlink(n);
1148 dl 1.14 } finally {
1149 jsr166 1.65 // checkInvariants();
1150 dl 1.14 lock.unlock();
1151     }
1152     }
1153     }
1154    
1155 jsr166 1.21 /** Forward iterator */
1156     private class Itr extends AbstractItr {
1157 jsr166 1.68 Itr() {} // prevent access constructor creation
1158 jsr166 1.21 Node<E> firstNode() { return first; }
1159     Node<E> nextNode(Node<E> n) { return n.next; }
1160     }
1161    
1162     /** Descending iterator */
1163 dl 1.16 private class DescendingItr extends AbstractItr {
1164 jsr166 1.68 DescendingItr() {} // prevent access constructor creation
1165 jsr166 1.21 Node<E> firstNode() { return last; }
1166     Node<E> nextNode(Node<E> n) { return n.prev; }
1167 dl 1.14 }
1168    
1169 jsr166 1.66 /**
1170     * A customized variant of Spliterators.IteratorSpliterator.
1171     * Keep this class in sync with (very similar) LBQSpliterator.
1172     */
1173 jsr166 1.64 private final class LBDSpliterator implements Spliterator<E> {
1174 dl 1.43 static final int MAX_BATCH = 1 << 25; // max batch array size;
1175 dl 1.36 Node<E> current; // current node; null until initialized
1176     int batch; // batch size for splits
1177     boolean exhausted; // true when no more nodes
1178 jsr166 1.66 long est = size(); // size estimate
1179    
1180     LBDSpliterator() {}
1181 jsr166 1.64
1182 dl 1.36 public long estimateSize() { return est; }
1183    
1184     public Spliterator<E> trySplit() {
1185 dl 1.43 Node<E> h;
1186 jsr166 1.41 if (!exhausted &&
1187 jsr166 1.66 ((h = current) != null || (h = first) != null)
1188 jsr166 1.60 && h.next != null) {
1189 jsr166 1.73 int n = batch = Math.min(batch + 1, MAX_BATCH);
1190 dl 1.47 Object[] a = new Object[n];
1191 jsr166 1.64 final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1192 dl 1.36 int i = 0;
1193     Node<E> p = current;
1194     lock.lock();
1195     try {
1196 jsr166 1.66 if (p != null || (p = first) != null)
1197     for (; p != null && i < n; p = succ(p))
1198     if ((a[i] = p.item) != null)
1199     i++;
1200 dl 1.36 } finally {
1201 jsr166 1.65 // checkInvariants();
1202 dl 1.36 lock.unlock();
1203     }
1204     if ((current = p) == null) {
1205     est = 0L;
1206     exhausted = true;
1207     }
1208 dl 1.40 else if ((est -= i) < 0L)
1209     est = 0L;
1210 jsr166 1.73 if (i > 0)
1211 dl 1.43 return Spliterators.spliterator
1212 jsr166 1.57 (a, 0, i, (Spliterator.ORDERED |
1213     Spliterator.NONNULL |
1214     Spliterator.CONCURRENT));
1215 dl 1.36 }
1216     return null;
1217     }
1218    
1219 jsr166 1.66 public boolean tryAdvance(Consumer<? super E> action) {
1220 jsr166 1.67 Objects.requireNonNull(action);
1221 jsr166 1.66 if (!exhausted) {
1222 jsr166 1.70 E e = null;
1223 jsr166 1.66 final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1224 dl 1.36 lock.lock();
1225     try {
1226 jsr166 1.71 Node<E> p;
1227     if ((p = current) != null || (p = first) != null)
1228 jsr166 1.66 do {
1229     e = p.item;
1230     p = succ(p);
1231     } while (e == null && p != null);
1232 jsr166 1.72 if ((current = p) == null)
1233     exhausted = true;
1234 dl 1.36 } finally {
1235 jsr166 1.65 // checkInvariants();
1236 dl 1.36 lock.unlock();
1237     }
1238 jsr166 1.66 if (e != null) {
1239 jsr166 1.62 action.accept(e);
1240 jsr166 1.66 return true;
1241 jsr166 1.62 }
1242 dl 1.36 }
1243 jsr166 1.66 return false;
1244 dl 1.36 }
1245    
1246 jsr166 1.67 public void forEachRemaining(Consumer<? super E> action) {
1247     Objects.requireNonNull(action);
1248     if (!exhausted) {
1249     exhausted = true;
1250     Node<E> p = current;
1251     current = null;
1252     forEachFrom(action, p);
1253     }
1254     }
1255    
1256 dl 1.36 public int characteristics() {
1257 jsr166 1.60 return (Spliterator.ORDERED |
1258     Spliterator.NONNULL |
1259     Spliterator.CONCURRENT);
1260 dl 1.36 }
1261     }
1262    
1263 jsr166 1.50 /**
1264     * Returns a {@link Spliterator} over the elements in this deque.
1265     *
1266 jsr166 1.51 * <p>The returned spliterator is
1267     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1268     *
1269 jsr166 1.50 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1270     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1271     *
1272     * @implNote
1273     * The {@code Spliterator} implements {@code trySplit} to permit limited
1274     * parallelism.
1275     *
1276     * @return a {@code Spliterator} over the elements in this deque
1277     * @since 1.8
1278     */
1279 dl 1.39 public Spliterator<E> spliterator() {
1280 jsr166 1.64 return new LBDSpliterator();
1281 dl 1.36 }
1282    
1283 dl 1.1 /**
1284 jsr166 1.67 * @throws NullPointerException {@inheritDoc}
1285     */
1286     public void forEach(Consumer<? super E> action) {
1287     Objects.requireNonNull(action);
1288     forEachFrom(action, null);
1289     }
1290    
1291     /**
1292     * Runs action on each element found during a traversal starting at p.
1293     * If p is null, traversal starts at head.
1294     */
1295     void forEachFrom(Consumer<? super E> action, Node<E> p) {
1296     // Extract batches of elements while holding the lock; then
1297     // run the action on the elements while not
1298     final ReentrantLock lock = this.lock;
1299     final int batchSize = 32; // max number of elements per batch
1300     Object[] es = null; // container for batch of elements
1301     int n, len = 0;
1302     do {
1303     lock.lock();
1304     try {
1305     if (es == null) {
1306     if (p == null) p = first;
1307     for (Node<E> q = p; q != null; q = succ(q))
1308     if (q.item != null && ++len == batchSize)
1309     break;
1310     es = new Object[len];
1311     }
1312     for (n = 0; p != null && n < len; p = succ(p))
1313     if ((es[n] = p.item) != null)
1314     n++;
1315     } finally {
1316     // checkInvariants();
1317     lock.unlock();
1318     }
1319     for (int i = 0; i < n; i++) {
1320     @SuppressWarnings("unchecked") E e = (E) es[i];
1321     action.accept(e);
1322     }
1323     } while (n > 0 && p != null);
1324     }
1325    
1326     /**
1327 jsr166 1.74 * @throws NullPointerException {@inheritDoc}
1328     */
1329     public boolean removeIf(Predicate<? super E> filter) {
1330     Objects.requireNonNull(filter);
1331     return bulkRemove(filter);
1332     }
1333    
1334     /**
1335     * @throws NullPointerException {@inheritDoc}
1336     */
1337     public boolean removeAll(Collection<?> c) {
1338     Objects.requireNonNull(c);
1339     return bulkRemove(e -> c.contains(e));
1340     }
1341    
1342     /**
1343     * @throws NullPointerException {@inheritDoc}
1344     */
1345     public boolean retainAll(Collection<?> c) {
1346     Objects.requireNonNull(c);
1347     return bulkRemove(e -> !c.contains(e));
1348     }
1349    
1350     /** Implementation of bulk remove methods. */
1351     @SuppressWarnings("unchecked")
1352     private boolean bulkRemove(Predicate<? super E> filter) {
1353     boolean removed = false;
1354     Node<E> p = null;
1355     final ReentrantLock lock = this.lock;
1356     Node<E>[] nodes = null;
1357     int n, len = 0;
1358     do {
1359     // 1. Extract batch of up to 64 elements while holding the lock.
1360     long deathRow = 0; // "bitset" of size 64
1361     lock.lock();
1362     try {
1363     if (nodes == null) {
1364     if (p == null) p = first;
1365     for (Node<E> q = p; q != null; q = succ(q))
1366     if (q.item != null && ++len == 64)
1367     break;
1368     nodes = (Node<E>[]) new Node<?>[len];
1369     }
1370     for (n = 0; p != null && n < len; p = succ(p))
1371     nodes[n++] = p;
1372     } finally {
1373     // checkInvariants();
1374     lock.unlock();
1375     }
1376    
1377     // 2. Run the filter on the elements while lock is free.
1378     for (int i = 0; i < n; i++) {
1379     final E e;
1380     if ((e = nodes[i].item) != null && filter.test(e))
1381     deathRow |= 1L << i;
1382     }
1383    
1384     // 3. Remove any filtered elements while holding the lock.
1385     if (deathRow != 0) {
1386     lock.lock();
1387     try {
1388     for (int i = 0; i < n; i++) {
1389     final Node<E> q;
1390     if ((deathRow & (1L << i)) != 0L
1391     && (q = nodes[i]).item != null) {
1392     q.item = null;
1393     unlink(q);
1394     removed = true;
1395     }
1396     }
1397     } finally {
1398     // checkInvariants();
1399     lock.unlock();
1400     }
1401     }
1402     } while (n > 0 && p != null);
1403     return removed;
1404     }
1405    
1406     /**
1407 jsr166 1.34 * Saves this deque to a stream (that is, serializes it).
1408 dl 1.1 *
1409 jsr166 1.48 * @param s the stream
1410 jsr166 1.49 * @throws java.io.IOException if an I/O error occurs
1411 dl 1.1 * @serialData The capacity (int), followed by elements (each an
1412 jsr166 1.21 * {@code Object}) in the proper order, followed by a null
1413 dl 1.1 */
1414     private void writeObject(java.io.ObjectOutputStream s)
1415     throws java.io.IOException {
1416 jsr166 1.21 final ReentrantLock lock = this.lock;
1417 dl 1.1 lock.lock();
1418     try {
1419     // Write out capacity and any hidden stuff
1420     s.defaultWriteObject();
1421     // Write out all elements in the proper order.
1422     for (Node<E> p = first; p != null; p = p.next)
1423     s.writeObject(p.item);
1424     // Use trailing null as sentinel
1425     s.writeObject(null);
1426     } finally {
1427 jsr166 1.65 // checkInvariants();
1428 dl 1.1 lock.unlock();
1429     }
1430     }
1431    
1432     /**
1433 jsr166 1.31 * Reconstitutes this deque from a stream (that is, deserializes it).
1434 jsr166 1.48 * @param s the stream
1435 jsr166 1.49 * @throws ClassNotFoundException if the class of a serialized object
1436     * could not be found
1437     * @throws java.io.IOException if an I/O error occurs
1438 dl 1.1 */
1439     private void readObject(java.io.ObjectInputStream s)
1440     throws java.io.IOException, ClassNotFoundException {
1441     s.defaultReadObject();
1442     count = 0;
1443     first = null;
1444     last = null;
1445     // Read in all elements and place in queue
1446     for (;;) {
1447 jsr166 1.67 @SuppressWarnings("unchecked") E item = (E)s.readObject();
1448 dl 1.1 if (item == null)
1449     break;
1450     add(item);
1451     }
1452     }
1453 jsr166 1.3
1454 jsr166 1.65 void checkInvariants() {
1455     // assert lock.isHeldByCurrentThread();
1456     // Nodes may get self-linked or lose their item, but only
1457     // after being unlinked and becoming unreachable from first.
1458     for (Node<E> p = first; p != null; p = p.next) {
1459     // assert p.next != p;
1460     // assert p.item != null;
1461     }
1462     }
1463    
1464 dl 1.1 }