ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingDeque.java
Revision: 1.69
Committed: Wed Dec 21 21:18:17 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.68: +7 -7 lines
Log Message:
Use code shape that appears to make C2 happier

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 dl 1.1
20     /**
21     * An optionally-bounded {@linkplain BlockingDeque blocking deque} based on
22     * linked nodes.
23     *
24 jsr166 1.35 * <p>The optional capacity bound constructor argument serves as a
25 dl 1.1 * way to prevent excessive expansion. The capacity, if unspecified,
26     * is equal to {@link Integer#MAX_VALUE}. Linked nodes are
27     * dynamically created upon each insertion unless this would bring the
28     * deque above capacity.
29     *
30     * <p>Most operations run in constant time (ignoring time spent
31     * blocking). Exceptions include {@link #remove(Object) remove},
32     * {@link #removeFirstOccurrence removeFirstOccurrence}, {@link
33     * #removeLastOccurrence removeLastOccurrence}, {@link #contains
34 jsr166 1.9 * contains}, {@link #iterator iterator.remove()}, and the bulk
35 dl 1.1 * operations, all of which run in linear time.
36     *
37     * <p>This class and its iterator implement all of the
38     * <em>optional</em> methods of the {@link Collection} and {@link
39 jsr166 1.9 * Iterator} interfaces.
40     *
41     * <p>This class is a member of the
42 jsr166 1.18 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
43 jsr166 1.9 * Java Collections Framework</a>.
44 dl 1.1 *
45     * @since 1.6
46     * @author Doug Lea
47 jsr166 1.52 * @param <E> the type of elements held in this deque
48 dl 1.1 */
49     public class LinkedBlockingDeque<E>
50     extends AbstractQueue<E>
51 jsr166 1.33 implements BlockingDeque<E>, java.io.Serializable {
52 dl 1.1
53     /*
54     * Implemented as a simple doubly-linked list protected by a
55     * single lock and using conditions to manage blocking.
56 jsr166 1.21 *
57     * To implement weakly consistent iterators, it appears we need to
58     * keep all Nodes GC-reachable from a predecessor dequeued Node.
59     * That would cause two problems:
60     * - allow a rogue Iterator to cause unbounded memory retention
61     * - cause cross-generational linking of old Nodes to new Nodes if
62     * a Node was tenured while live, which generational GCs have a
63     * hard time dealing with, causing repeated major collections.
64     * However, only non-deleted Nodes need to be reachable from
65     * dequeued Nodes, and reachability does not necessarily have to
66     * be of the kind understood by the GC. We use the trick of
67     * linking a Node that has just been dequeued to itself. Such a
68     * self-link implicitly means to jump to "first" (for next links)
69     * or "last" (for prev links).
70 dl 1.1 */
71    
72 jsr166 1.9 /*
73     * We have "diamond" multiple interface/abstract class inheritance
74     * here, and that introduces ambiguities. Often we want the
75     * BlockingDeque javadoc combined with the AbstractQueue
76     * implementation, so a lot of method specs are duplicated here.
77     */
78    
79 dl 1.1 private static final long serialVersionUID = -387911632671998426L;
80    
81     /** Doubly-linked list node class */
82     static final class Node<E> {
83 jsr166 1.21 /**
84     * The item, or null if this node has been removed.
85     */
86 jsr166 1.19 E item;
87 jsr166 1.21
88     /**
89     * One of:
90     * - the real predecessor Node
91     * - this Node, meaning the predecessor is tail
92     * - null, meaning there is no predecessor
93     */
94 dl 1.1 Node<E> prev;
95 jsr166 1.21
96     /**
97     * One of:
98     * - the real successor Node
99     * - this Node, meaning the successor is head
100     * - null, meaning there is no successor
101     */
102 dl 1.1 Node<E> next;
103 jsr166 1.21
104 dl 1.23 Node(E x) {
105 dl 1.1 item = x;
106     }
107     }
108    
109 jsr166 1.21 /**
110     * Pointer to first node.
111     * Invariant: (first == null && last == null) ||
112     * (first.prev == null && first.item != null)
113     */
114     transient Node<E> first;
115    
116     /**
117     * Pointer to last node.
118     * Invariant: (first == null && last == null) ||
119     * (last.next == null && last.item != null)
120     */
121     transient Node<E> last;
122    
123 dl 1.1 /** Number of items in the deque */
124     private transient int count;
125 jsr166 1.21
126 dl 1.1 /** Maximum number of items in the deque */
127     private final int capacity;
128 jsr166 1.21
129 dl 1.1 /** Main lock guarding all access */
130 jsr166 1.21 final ReentrantLock lock = new ReentrantLock();
131    
132 dl 1.1 /** Condition for waiting takes */
133     private final Condition notEmpty = lock.newCondition();
134 jsr166 1.21
135 dl 1.1 /** Condition for waiting puts */
136     private final Condition notFull = lock.newCondition();
137    
138     /**
139 jsr166 1.21 * Creates a {@code LinkedBlockingDeque} with a capacity of
140 dl 1.1 * {@link Integer#MAX_VALUE}.
141     */
142     public LinkedBlockingDeque() {
143     this(Integer.MAX_VALUE);
144     }
145    
146     /**
147 jsr166 1.21 * Creates a {@code LinkedBlockingDeque} with the given (fixed) capacity.
148 jsr166 1.9 *
149 dl 1.1 * @param capacity the capacity of this deque
150 jsr166 1.21 * @throws IllegalArgumentException if {@code capacity} is less than 1
151 dl 1.1 */
152     public LinkedBlockingDeque(int capacity) {
153     if (capacity <= 0) throw new IllegalArgumentException();
154     this.capacity = capacity;
155     }
156    
157     /**
158 jsr166 1.21 * Creates a {@code LinkedBlockingDeque} with a capacity of
159 jsr166 1.9 * {@link Integer#MAX_VALUE}, initially containing the elements of
160     * the given collection, added in traversal order of the
161     * collection's iterator.
162     *
163 dl 1.1 * @param c the collection of elements to initially contain
164 jsr166 1.9 * @throws NullPointerException if the specified collection or any
165     * of its elements are null
166 dl 1.1 */
167     public LinkedBlockingDeque(Collection<? extends E> c) {
168     this(Integer.MAX_VALUE);
169 jsr166 1.21 final ReentrantLock lock = this.lock;
170     lock.lock(); // Never contended, but necessary for visibility
171     try {
172     for (E e : c) {
173     if (e == null)
174     throw new NullPointerException();
175 dl 1.23 if (!linkLast(new Node<E>(e)))
176 jsr166 1.21 throw new IllegalStateException("Deque full");
177     }
178     } finally {
179 jsr166 1.65 // checkInvariants();
180 jsr166 1.21 lock.unlock();
181     }
182 dl 1.1 }
183    
184    
185     // Basic linking and unlinking operations, called only while holding lock
186    
187     /**
188 dl 1.23 * Links node as first element, or returns false if full.
189 dl 1.1 */
190 dl 1.23 private boolean linkFirst(Node<E> node) {
191 jsr166 1.21 // assert lock.isHeldByCurrentThread();
192 dl 1.1 if (count >= capacity)
193     return false;
194     Node<E> f = first;
195 dl 1.23 node.next = f;
196     first = node;
197 dl 1.1 if (last == null)
198 dl 1.23 last = node;
199 dl 1.1 else
200 dl 1.23 f.prev = node;
201 jsr166 1.21 ++count;
202 dl 1.1 notEmpty.signal();
203     return true;
204     }
205    
206     /**
207 dl 1.23 * Links node as last element, or returns false if full.
208 dl 1.1 */
209 dl 1.23 private boolean linkLast(Node<E> node) {
210 jsr166 1.21 // assert lock.isHeldByCurrentThread();
211 dl 1.1 if (count >= capacity)
212     return false;
213     Node<E> l = last;
214 dl 1.23 node.prev = l;
215     last = node;
216 dl 1.1 if (first == null)
217 dl 1.23 first = node;
218 dl 1.1 else
219 dl 1.23 l.next = node;
220 jsr166 1.21 ++count;
221 dl 1.1 notEmpty.signal();
222     return true;
223     }
224    
225     /**
226 jsr166 1.3 * Removes and returns first element, or null if empty.
227 dl 1.1 */
228     private E unlinkFirst() {
229 jsr166 1.21 // assert lock.isHeldByCurrentThread();
230 dl 1.1 Node<E> f = first;
231     if (f == null)
232     return null;
233     Node<E> n = f.next;
234 jsr166 1.21 E item = f.item;
235     f.item = null;
236     f.next = f; // help GC
237 dl 1.1 first = n;
238 jsr166 1.3 if (n == null)
239 dl 1.1 last = null;
240 jsr166 1.3 else
241 dl 1.1 n.prev = null;
242     --count;
243     notFull.signal();
244 jsr166 1.21 return item;
245 dl 1.1 }
246    
247     /**
248 jsr166 1.3 * Removes and returns last element, or null if empty.
249 dl 1.1 */
250     private E unlinkLast() {
251 jsr166 1.21 // assert lock.isHeldByCurrentThread();
252 dl 1.1 Node<E> l = last;
253     if (l == null)
254     return null;
255     Node<E> p = l.prev;
256 jsr166 1.21 E item = l.item;
257     l.item = null;
258     l.prev = l; // help GC
259 dl 1.1 last = p;
260 jsr166 1.3 if (p == null)
261 dl 1.1 first = null;
262 jsr166 1.3 else
263 dl 1.1 p.next = null;
264     --count;
265     notFull.signal();
266 jsr166 1.21 return item;
267 dl 1.1 }
268    
269     /**
270 jsr166 1.21 * Unlinks x.
271 dl 1.1 */
272 jsr166 1.21 void unlink(Node<E> x) {
273     // assert lock.isHeldByCurrentThread();
274 dl 1.1 Node<E> p = x.prev;
275     Node<E> n = x.next;
276     if (p == null) {
277 jsr166 1.21 unlinkFirst();
278 dl 1.1 } else if (n == null) {
279 jsr166 1.21 unlinkLast();
280 dl 1.1 } else {
281     p.next = n;
282     n.prev = p;
283 jsr166 1.21 x.item = null;
284     // Don't mess with x's links. They may still be in use by
285     // an iterator.
286     --count;
287     notFull.signal();
288 dl 1.1 }
289     }
290    
291 jsr166 1.9 // BlockingDeque methods
292 dl 1.1
293 jsr166 1.9 /**
294 jsr166 1.46 * @throws IllegalStateException if this deque is full
295     * @throws NullPointerException {@inheritDoc}
296 jsr166 1.9 */
297     public void addFirst(E e) {
298     if (!offerFirst(e))
299     throw new IllegalStateException("Deque full");
300     }
301    
302     /**
303 jsr166 1.46 * @throws IllegalStateException if this deque is full
304 jsr166 1.9 * @throws NullPointerException {@inheritDoc}
305     */
306     public void addLast(E e) {
307     if (!offerLast(e))
308     throw new IllegalStateException("Deque full");
309     }
310    
311     /**
312     * @throws NullPointerException {@inheritDoc}
313     */
314 jsr166 1.6 public boolean offerFirst(E e) {
315     if (e == null) throw new NullPointerException();
316 dl 1.23 Node<E> node = new Node<E>(e);
317 jsr166 1.21 final ReentrantLock lock = this.lock;
318 dl 1.1 lock.lock();
319     try {
320 dl 1.23 return linkFirst(node);
321 dl 1.1 } finally {
322 jsr166 1.65 // checkInvariants();
323 dl 1.1 lock.unlock();
324     }
325     }
326    
327 jsr166 1.9 /**
328     * @throws NullPointerException {@inheritDoc}
329     */
330 jsr166 1.6 public boolean offerLast(E e) {
331     if (e == null) throw new NullPointerException();
332 dl 1.23 Node<E> node = new Node<E>(e);
333 jsr166 1.21 final ReentrantLock lock = this.lock;
334 dl 1.1 lock.lock();
335     try {
336 dl 1.23 return linkLast(node);
337 dl 1.1 } finally {
338 jsr166 1.65 // checkInvariants();
339 dl 1.1 lock.unlock();
340     }
341     }
342    
343 jsr166 1.9 /**
344     * @throws NullPointerException {@inheritDoc}
345     * @throws InterruptedException {@inheritDoc}
346     */
347     public void putFirst(E e) throws InterruptedException {
348     if (e == null) throw new NullPointerException();
349 dl 1.23 Node<E> node = new Node<E>(e);
350 jsr166 1.21 final ReentrantLock lock = this.lock;
351 dl 1.1 lock.lock();
352     try {
353 dl 1.23 while (!linkFirst(node))
354 jsr166 1.9 notFull.await();
355 dl 1.1 } finally {
356 jsr166 1.65 // checkInvariants();
357 dl 1.1 lock.unlock();
358     }
359     }
360    
361 jsr166 1.9 /**
362     * @throws NullPointerException {@inheritDoc}
363     * @throws InterruptedException {@inheritDoc}
364     */
365     public void putLast(E e) throws InterruptedException {
366     if (e == null) throw new NullPointerException();
367 dl 1.23 Node<E> node = new Node<E>(e);
368 jsr166 1.21 final ReentrantLock lock = this.lock;
369 dl 1.1 lock.lock();
370     try {
371 dl 1.23 while (!linkLast(node))
372 jsr166 1.9 notFull.await();
373 dl 1.1 } finally {
374 jsr166 1.65 // checkInvariants();
375 dl 1.1 lock.unlock();
376     }
377     }
378    
379 jsr166 1.9 /**
380     * @throws NullPointerException {@inheritDoc}
381     * @throws InterruptedException {@inheritDoc}
382     */
383     public boolean offerFirst(E e, long timeout, TimeUnit unit)
384     throws InterruptedException {
385     if (e == null) throw new NullPointerException();
386 dl 1.23 Node<E> node = new Node<E>(e);
387 jsr166 1.19 long nanos = unit.toNanos(timeout);
388 jsr166 1.21 final ReentrantLock lock = this.lock;
389 jsr166 1.9 lock.lockInterruptibly();
390 dl 1.1 try {
391 dl 1.23 while (!linkFirst(node)) {
392 jsr166 1.59 if (nanos <= 0L)
393 jsr166 1.9 return false;
394     nanos = notFull.awaitNanos(nanos);
395     }
396 jsr166 1.21 return true;
397 dl 1.1 } finally {
398 jsr166 1.65 // checkInvariants();
399 dl 1.1 lock.unlock();
400     }
401     }
402    
403 jsr166 1.9 /**
404     * @throws NullPointerException {@inheritDoc}
405     * @throws InterruptedException {@inheritDoc}
406     */
407     public boolean offerLast(E e, long timeout, TimeUnit unit)
408     throws InterruptedException {
409     if (e == null) throw new NullPointerException();
410 dl 1.23 Node<E> node = new Node<E>(e);
411 jsr166 1.19 long nanos = unit.toNanos(timeout);
412 jsr166 1.21 final ReentrantLock lock = this.lock;
413 jsr166 1.9 lock.lockInterruptibly();
414 dl 1.1 try {
415 dl 1.23 while (!linkLast(node)) {
416 jsr166 1.59 if (nanos <= 0L)
417 jsr166 1.9 return false;
418     nanos = notFull.awaitNanos(nanos);
419     }
420 jsr166 1.21 return true;
421 dl 1.1 } finally {
422 jsr166 1.65 // checkInvariants();
423 dl 1.1 lock.unlock();
424     }
425     }
426    
427 jsr166 1.9 /**
428     * @throws NoSuchElementException {@inheritDoc}
429     */
430     public E removeFirst() {
431     E x = pollFirst();
432 dl 1.1 if (x == null) throw new NoSuchElementException();
433     return x;
434     }
435    
436 jsr166 1.9 /**
437     * @throws NoSuchElementException {@inheritDoc}
438     */
439     public E removeLast() {
440     E x = pollLast();
441 dl 1.1 if (x == null) throw new NoSuchElementException();
442     return x;
443     }
444    
445 jsr166 1.9 public E pollFirst() {
446 jsr166 1.21 final ReentrantLock lock = this.lock;
447 dl 1.1 lock.lock();
448     try {
449 jsr166 1.9 return unlinkFirst();
450 dl 1.1 } finally {
451 jsr166 1.65 // checkInvariants();
452 dl 1.1 lock.unlock();
453     }
454     }
455    
456 jsr166 1.9 public E pollLast() {
457 jsr166 1.21 final ReentrantLock lock = this.lock;
458 dl 1.1 lock.lock();
459     try {
460 jsr166 1.9 return unlinkLast();
461 dl 1.1 } finally {
462 jsr166 1.65 // checkInvariants();
463 dl 1.1 lock.unlock();
464     }
465     }
466    
467     public E takeFirst() throws InterruptedException {
468 jsr166 1.21 final ReentrantLock lock = this.lock;
469 dl 1.1 lock.lock();
470     try {
471     E x;
472     while ( (x = unlinkFirst()) == null)
473     notEmpty.await();
474     return x;
475     } finally {
476 jsr166 1.65 // checkInvariants();
477 dl 1.1 lock.unlock();
478     }
479     }
480    
481     public E takeLast() throws InterruptedException {
482 jsr166 1.21 final ReentrantLock lock = this.lock;
483 dl 1.1 lock.lock();
484     try {
485     E x;
486     while ( (x = unlinkLast()) == null)
487     notEmpty.await();
488     return x;
489     } finally {
490 jsr166 1.65 // checkInvariants();
491 dl 1.1 lock.unlock();
492     }
493     }
494    
495 jsr166 1.9 public E pollFirst(long timeout, TimeUnit unit)
496 dl 1.1 throws InterruptedException {
497 jsr166 1.19 long nanos = unit.toNanos(timeout);
498 jsr166 1.21 final ReentrantLock lock = this.lock;
499 dl 1.1 lock.lockInterruptibly();
500     try {
501 jsr166 1.21 E x;
502     while ( (x = unlinkFirst()) == null) {
503 jsr166 1.59 if (nanos <= 0L)
504 jsr166 1.9 return null;
505     nanos = notEmpty.awaitNanos(nanos);
506 dl 1.1 }
507 jsr166 1.21 return x;
508 dl 1.1 } finally {
509 jsr166 1.65 // checkInvariants();
510 dl 1.1 lock.unlock();
511     }
512     }
513 jsr166 1.3
514 jsr166 1.9 public E pollLast(long timeout, TimeUnit unit)
515 dl 1.1 throws InterruptedException {
516 jsr166 1.19 long nanos = unit.toNanos(timeout);
517 jsr166 1.21 final ReentrantLock lock = this.lock;
518 dl 1.1 lock.lockInterruptibly();
519     try {
520 jsr166 1.21 E x;
521     while ( (x = unlinkLast()) == null) {
522 jsr166 1.59 if (nanos <= 0L)
523 jsr166 1.9 return null;
524     nanos = notEmpty.awaitNanos(nanos);
525 dl 1.1 }
526 jsr166 1.21 return x;
527 dl 1.1 } finally {
528 jsr166 1.65 // checkInvariants();
529 dl 1.1 lock.unlock();
530     }
531     }
532    
533 jsr166 1.9 /**
534     * @throws NoSuchElementException {@inheritDoc}
535     */
536     public E getFirst() {
537     E x = peekFirst();
538     if (x == null) throw new NoSuchElementException();
539     return x;
540     }
541    
542     /**
543     * @throws NoSuchElementException {@inheritDoc}
544     */
545     public E getLast() {
546     E x = peekLast();
547     if (x == null) throw new NoSuchElementException();
548     return x;
549     }
550    
551     public E peekFirst() {
552 jsr166 1.21 final ReentrantLock lock = this.lock;
553 jsr166 1.9 lock.lock();
554     try {
555     return (first == null) ? null : first.item;
556     } finally {
557 jsr166 1.65 // checkInvariants();
558 jsr166 1.9 lock.unlock();
559     }
560     }
561    
562     public E peekLast() {
563 jsr166 1.21 final ReentrantLock lock = this.lock;
564 jsr166 1.9 lock.lock();
565     try {
566     return (last == null) ? null : last.item;
567     } finally {
568 jsr166 1.65 // checkInvariants();
569 jsr166 1.9 lock.unlock();
570     }
571     }
572    
573     public boolean removeFirstOccurrence(Object o) {
574     if (o == null) return false;
575 jsr166 1.21 final ReentrantLock lock = this.lock;
576 jsr166 1.9 lock.lock();
577 dl 1.1 try {
578 jsr166 1.9 for (Node<E> p = first; p != null; p = p.next) {
579     if (o.equals(p.item)) {
580     unlink(p);
581     return true;
582     }
583 dl 1.1 }
584 jsr166 1.9 return false;
585 dl 1.1 } finally {
586 jsr166 1.65 // checkInvariants();
587 dl 1.1 lock.unlock();
588     }
589     }
590    
591 jsr166 1.9 public boolean removeLastOccurrence(Object o) {
592     if (o == null) return false;
593 jsr166 1.21 final ReentrantLock lock = this.lock;
594 jsr166 1.9 lock.lock();
595 dl 1.1 try {
596 jsr166 1.9 for (Node<E> p = last; p != null; p = p.prev) {
597     if (o.equals(p.item)) {
598     unlink(p);
599     return true;
600     }
601 dl 1.1 }
602 jsr166 1.9 return false;
603 dl 1.1 } finally {
604 jsr166 1.65 // checkInvariants();
605 dl 1.1 lock.unlock();
606     }
607     }
608    
609 jsr166 1.9 // BlockingQueue methods
610 dl 1.1
611 jsr166 1.9 /**
612     * Inserts the specified element at the end of this deque unless it would
613     * violate capacity restrictions. When using a capacity-restricted deque,
614     * it is generally preferable to use method {@link #offer(Object) offer}.
615     *
616 jsr166 1.13 * <p>This method is equivalent to {@link #addLast}.
617 jsr166 1.9 *
618 jsr166 1.46 * @throws IllegalStateException if this deque is full
619 jsr166 1.9 * @throws NullPointerException if the specified element is null
620     */
621     public boolean add(E e) {
622 jsr166 1.19 addLast(e);
623     return true;
624 jsr166 1.9 }
625    
626     /**
627     * @throws NullPointerException if the specified element is null
628     */
629     public boolean offer(E e) {
630 jsr166 1.19 return offerLast(e);
631 jsr166 1.9 }
632 dl 1.1
633 jsr166 1.9 /**
634     * @throws NullPointerException {@inheritDoc}
635     * @throws InterruptedException {@inheritDoc}
636     */
637     public void put(E e) throws InterruptedException {
638 jsr166 1.19 putLast(e);
639 jsr166 1.9 }
640 dl 1.1
641 jsr166 1.9 /**
642     * @throws NullPointerException {@inheritDoc}
643     * @throws InterruptedException {@inheritDoc}
644     */
645 jsr166 1.7 public boolean offer(E e, long timeout, TimeUnit unit)
646 jsr166 1.9 throws InterruptedException {
647 jsr166 1.19 return offerLast(e, timeout, unit);
648 jsr166 1.9 }
649    
650     /**
651     * Retrieves and removes the head of the queue represented by this deque.
652     * This method differs from {@link #poll poll} only in that it throws an
653     * exception if this deque is empty.
654     *
655     * <p>This method is equivalent to {@link #removeFirst() removeFirst}.
656     *
657     * @return the head of the queue represented by this deque
658     * @throws NoSuchElementException if this deque is empty
659     */
660     public E remove() {
661 jsr166 1.19 return removeFirst();
662 jsr166 1.9 }
663    
664     public E poll() {
665 jsr166 1.19 return pollFirst();
666 jsr166 1.9 }
667    
668     public E take() throws InterruptedException {
669 jsr166 1.19 return takeFirst();
670 jsr166 1.9 }
671    
672     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
673 jsr166 1.19 return pollFirst(timeout, unit);
674 jsr166 1.9 }
675 dl 1.1
676     /**
677 jsr166 1.9 * Retrieves, but does not remove, the head of the queue represented by
678     * this deque. This method differs from {@link #peek peek} only in that
679     * it throws an exception if this deque is empty.
680     *
681     * <p>This method is equivalent to {@link #getFirst() getFirst}.
682 dl 1.1 *
683 jsr166 1.9 * @return the head of the queue represented by this deque
684     * @throws NoSuchElementException if this deque is empty
685 dl 1.1 */
686 jsr166 1.9 public E element() {
687 jsr166 1.19 return getFirst();
688 jsr166 1.9 }
689    
690     public E peek() {
691 jsr166 1.19 return peekFirst();
692 dl 1.1 }
693    
694     /**
695 jsr166 1.4 * Returns the number of additional elements that this deque can ideally
696     * (in the absence of memory or resource constraints) accept without
697 dl 1.1 * blocking. This is always equal to the initial capacity of this deque
698 jsr166 1.21 * less the current {@code size} of this deque.
699 jsr166 1.4 *
700     * <p>Note that you <em>cannot</em> always tell if an attempt to insert
701 jsr166 1.21 * an element will succeed by inspecting {@code remainingCapacity}
702 jsr166 1.4 * because it may be the case that another thread is about to
703 jsr166 1.9 * insert or remove an element.
704 dl 1.1 */
705     public int remainingCapacity() {
706 jsr166 1.21 final ReentrantLock lock = this.lock;
707 dl 1.1 lock.lock();
708     try {
709     return capacity - count;
710     } finally {
711 jsr166 1.65 // checkInvariants();
712 dl 1.1 lock.unlock();
713     }
714     }
715    
716 jsr166 1.9 /**
717     * @throws UnsupportedOperationException {@inheritDoc}
718     * @throws ClassCastException {@inheritDoc}
719     * @throws NullPointerException {@inheritDoc}
720     * @throws IllegalArgumentException {@inheritDoc}
721     */
722     public int drainTo(Collection<? super E> c) {
723 jsr166 1.21 return drainTo(c, Integer.MAX_VALUE);
724 dl 1.1 }
725    
726 jsr166 1.9 /**
727     * @throws UnsupportedOperationException {@inheritDoc}
728     * @throws ClassCastException {@inheritDoc}
729     * @throws NullPointerException {@inheritDoc}
730     * @throws IllegalArgumentException {@inheritDoc}
731     */
732     public int drainTo(Collection<? super E> c, int maxElements) {
733 jsr166 1.67 Objects.requireNonNull(c);
734 jsr166 1.9 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 jsr166 1.67 * Used for any element traversal that is not entirely under lock.
985     * Such traversals must handle both:
986     * - dequeued nodes (p.next == p)
987     * - (possibly multiple) interior removed nodes (p.item == null)
988     */
989     Node<E> succ(Node<E> p) {
990     return (p == (p = p.next)) ? first : p;
991     }
992    
993     /**
994 dl 1.1 * Returns an iterator over the elements in this deque in proper sequence.
995 jsr166 1.9 * The elements will be returned in order from first (head) to last (tail).
996 jsr166 1.26 *
997 jsr166 1.51 * <p>The returned iterator is
998     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
999 dl 1.1 *
1000 jsr166 1.9 * @return an iterator over the elements in this deque in proper sequence
1001 dl 1.1 */
1002     public Iterator<E> iterator() {
1003     return new Itr();
1004     }
1005    
1006     /**
1007 dl 1.14 * Returns an iterator over the elements in this deque in reverse
1008     * sequential order. The elements will be returned in order from
1009     * last (tail) to first (head).
1010 jsr166 1.26 *
1011 jsr166 1.51 * <p>The returned iterator is
1012     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1013 jsr166 1.26 *
1014     * @return an iterator over the elements in this deque in reverse order
1015 dl 1.14 */
1016     public Iterator<E> descendingIterator() {
1017     return new DescendingItr();
1018     }
1019    
1020     /**
1021 jsr166 1.58 * Base class for LinkedBlockingDeque iterators.
1022 dl 1.1 */
1023 dl 1.16 private abstract class AbstractItr implements Iterator<E> {
1024 jsr166 1.15 /**
1025 jsr166 1.58 * The next node to return in next().
1026 dl 1.14 */
1027 jsr166 1.28 Node<E> next;
1028 dl 1.1
1029     /**
1030     * nextItem holds on to item fields because once we claim that
1031     * an element exists in hasNext(), we must return item read
1032 jsr166 1.67 * under lock even if it was in the process of being removed
1033     * when hasNext() was called.
1034 jsr166 1.3 */
1035 dl 1.14 E nextItem;
1036 dl 1.1
1037     /**
1038     * Node returned by most recent call to next. Needed by remove.
1039     * Reset to null if this element is deleted by a call to remove.
1040     */
1041 dl 1.16 private Node<E> lastRet;
1042    
1043 jsr166 1.21 abstract Node<E> firstNode();
1044     abstract Node<E> nextNode(Node<E> n);
1045    
1046 jsr166 1.66 private Node<E> succ(Node<E> p) {
1047     return (p == (p = nextNode(p))) ? firstNode() : p;
1048     }
1049    
1050 dl 1.16 AbstractItr() {
1051 jsr166 1.21 // set to initial position
1052     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1053     lock.lock();
1054     try {
1055 jsr166 1.66 if ((next = firstNode()) != null)
1056     nextItem = next.item;
1057 jsr166 1.21 } finally {
1058 jsr166 1.65 // checkInvariants();
1059 jsr166 1.21 lock.unlock();
1060     }
1061 dl 1.16 }
1062 dl 1.1
1063 jsr166 1.67 public boolean hasNext() {
1064     return next != null;
1065     }
1066    
1067     public E next() {
1068     Node<E> p;
1069     if ((p = next) == null)
1070     throw new NoSuchElementException();
1071     lastRet = p;
1072 jsr166 1.69 E x = nextItem;
1073 jsr166 1.21 final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1074     lock.lock();
1075     try {
1076 jsr166 1.69 E e = null;
1077     for (p = nextNode(p); p != null && (e = p.item) == null; )
1078     p = succ(p);
1079     next = p;
1080     nextItem = e;
1081 jsr166 1.21 } finally {
1082 jsr166 1.65 // checkInvariants();
1083 jsr166 1.21 lock.unlock();
1084     }
1085 jsr166 1.69 return x;
1086 jsr166 1.21 }
1087 dl 1.1
1088 jsr166 1.67 public void forEachRemaining(Consumer<? super E> action) {
1089     // A variant of forEachFrom
1090     Objects.requireNonNull(action);
1091     Node<E> p;
1092     if ((p = next) == null) return;
1093 dl 1.14 lastRet = next;
1094 jsr166 1.67 next = null;
1095     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1096     final int batchSize = 32;
1097     Object[] es = null;
1098     int n, len = 1;
1099     do {
1100     lock.lock();
1101     try {
1102     if (es == null) {
1103     p = nextNode(p);
1104     for (Node<E> q = p; q != null; q = succ(q))
1105     if (q.item != null && ++len == batchSize)
1106     break;
1107     es = new Object[len];
1108     es[0] = nextItem;
1109     nextItem = null;
1110     n = 1;
1111     } else
1112     n = 0;
1113     for (; p != null && n < len; p = succ(p))
1114     if ((es[n] = p.item) != null) {
1115     lastRet = p;
1116     n++;
1117     }
1118     } finally {
1119     // checkInvariants();
1120     lock.unlock();
1121     }
1122     for (int i = 0; i < n; i++) {
1123     @SuppressWarnings("unchecked") E e = (E) es[i];
1124     action.accept(e);
1125     }
1126     } while (n > 0 && p != null);
1127 dl 1.1 }
1128    
1129     public void remove() {
1130 dl 1.14 Node<E> n = lastRet;
1131 dl 1.1 if (n == null)
1132     throw new IllegalStateException();
1133 dl 1.14 lastRet = null;
1134     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1135     lock.lock();
1136     try {
1137 jsr166 1.21 if (n.item != null)
1138     unlink(n);
1139 dl 1.14 } finally {
1140 jsr166 1.65 // checkInvariants();
1141 dl 1.14 lock.unlock();
1142     }
1143     }
1144     }
1145    
1146 jsr166 1.21 /** Forward iterator */
1147     private class Itr extends AbstractItr {
1148 jsr166 1.68 Itr() {} // prevent access constructor creation
1149 jsr166 1.21 Node<E> firstNode() { return first; }
1150     Node<E> nextNode(Node<E> n) { return n.next; }
1151     }
1152    
1153     /** Descending iterator */
1154 dl 1.16 private class DescendingItr extends AbstractItr {
1155 jsr166 1.68 DescendingItr() {} // prevent access constructor creation
1156 jsr166 1.21 Node<E> firstNode() { return last; }
1157     Node<E> nextNode(Node<E> n) { return n.prev; }
1158 dl 1.14 }
1159    
1160 jsr166 1.66 /**
1161     * A customized variant of Spliterators.IteratorSpliterator.
1162     * Keep this class in sync with (very similar) LBQSpliterator.
1163     */
1164 jsr166 1.64 private final class LBDSpliterator implements Spliterator<E> {
1165 dl 1.43 static final int MAX_BATCH = 1 << 25; // max batch array size;
1166 dl 1.36 Node<E> current; // current node; null until initialized
1167     int batch; // batch size for splits
1168     boolean exhausted; // true when no more nodes
1169 jsr166 1.66 long est = size(); // size estimate
1170    
1171     LBDSpliterator() {}
1172 jsr166 1.64
1173 dl 1.36 public long estimateSize() { return est; }
1174    
1175     public Spliterator<E> trySplit() {
1176 dl 1.43 Node<E> h;
1177     int b = batch;
1178     int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
1179 jsr166 1.41 if (!exhausted &&
1180 jsr166 1.66 ((h = current) != null || (h = first) != null)
1181 jsr166 1.60 && h.next != null) {
1182 dl 1.47 Object[] a = new Object[n];
1183 jsr166 1.64 final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1184 dl 1.36 int i = 0;
1185     Node<E> p = current;
1186     lock.lock();
1187     try {
1188 jsr166 1.66 if (p != null || (p = first) != null)
1189     for (; p != null && i < n; p = succ(p))
1190     if ((a[i] = p.item) != null)
1191     i++;
1192 dl 1.36 } finally {
1193 jsr166 1.65 // checkInvariants();
1194 dl 1.36 lock.unlock();
1195     }
1196     if ((current = p) == null) {
1197     est = 0L;
1198     exhausted = true;
1199     }
1200 dl 1.40 else if ((est -= i) < 0L)
1201     est = 0L;
1202 dl 1.43 if (i > 0) {
1203     batch = i;
1204     return Spliterators.spliterator
1205 jsr166 1.57 (a, 0, i, (Spliterator.ORDERED |
1206     Spliterator.NONNULL |
1207     Spliterator.CONCURRENT));
1208 dl 1.43 }
1209 dl 1.36 }
1210     return null;
1211     }
1212    
1213 jsr166 1.66 public boolean tryAdvance(Consumer<? super E> action) {
1214 jsr166 1.67 Objects.requireNonNull(action);
1215 jsr166 1.66 if (!exhausted) {
1216     final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1217     Node<E> p = current;
1218 jsr166 1.62 E e = null;
1219 dl 1.36 lock.lock();
1220     try {
1221 jsr166 1.66 if (p != null || (p = first) != null)
1222     do {
1223     e = p.item;
1224     p = succ(p);
1225     } while (e == null && p != null);
1226 dl 1.36 } finally {
1227 jsr166 1.65 // checkInvariants();
1228 dl 1.36 lock.unlock();
1229     }
1230 jsr166 1.66 exhausted = ((current = p) == null);
1231     if (e != null) {
1232 jsr166 1.62 action.accept(e);
1233 jsr166 1.66 return true;
1234 jsr166 1.62 }
1235 dl 1.36 }
1236 jsr166 1.66 return false;
1237 dl 1.36 }
1238    
1239 jsr166 1.67 public void forEachRemaining(Consumer<? super E> action) {
1240     Objects.requireNonNull(action);
1241     if (!exhausted) {
1242     exhausted = true;
1243     Node<E> p = current;
1244     current = null;
1245     forEachFrom(action, p);
1246     }
1247     }
1248    
1249 dl 1.36 public int characteristics() {
1250 jsr166 1.60 return (Spliterator.ORDERED |
1251     Spliterator.NONNULL |
1252     Spliterator.CONCURRENT);
1253 dl 1.36 }
1254     }
1255    
1256 jsr166 1.50 /**
1257     * Returns a {@link Spliterator} over the elements in this deque.
1258     *
1259 jsr166 1.51 * <p>The returned spliterator is
1260     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1261     *
1262 jsr166 1.50 * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
1263     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
1264     *
1265     * @implNote
1266     * The {@code Spliterator} implements {@code trySplit} to permit limited
1267     * parallelism.
1268     *
1269     * @return a {@code Spliterator} over the elements in this deque
1270     * @since 1.8
1271     */
1272 dl 1.39 public Spliterator<E> spliterator() {
1273 jsr166 1.64 return new LBDSpliterator();
1274 dl 1.36 }
1275    
1276 dl 1.1 /**
1277 jsr166 1.67 * @throws NullPointerException {@inheritDoc}
1278     */
1279     public void forEach(Consumer<? super E> action) {
1280     Objects.requireNonNull(action);
1281     forEachFrom(action, null);
1282     }
1283    
1284     /**
1285     * Runs action on each element found during a traversal starting at p.
1286     * If p is null, traversal starts at head.
1287     */
1288     void forEachFrom(Consumer<? super E> action, Node<E> p) {
1289     // Extract batches of elements while holding the lock; then
1290     // run the action on the elements while not
1291     final ReentrantLock lock = this.lock;
1292     final int batchSize = 32; // max number of elements per batch
1293     Object[] es = null; // container for batch of elements
1294     int n, len = 0;
1295     do {
1296     lock.lock();
1297     try {
1298     if (es == null) {
1299     if (p == null) p = first;
1300     for (Node<E> q = p; q != null; q = succ(q))
1301     if (q.item != null && ++len == batchSize)
1302     break;
1303     es = new Object[len];
1304     }
1305     for (n = 0; p != null && n < len; p = succ(p))
1306     if ((es[n] = p.item) != null)
1307     n++;
1308     } finally {
1309     // checkInvariants();
1310     lock.unlock();
1311     }
1312     for (int i = 0; i < n; i++) {
1313     @SuppressWarnings("unchecked") E e = (E) es[i];
1314     action.accept(e);
1315     }
1316     } while (n > 0 && p != null);
1317     }
1318    
1319     /**
1320 jsr166 1.34 * Saves this deque to a stream (that is, serializes it).
1321 dl 1.1 *
1322 jsr166 1.48 * @param s the stream
1323 jsr166 1.49 * @throws java.io.IOException if an I/O error occurs
1324 dl 1.1 * @serialData The capacity (int), followed by elements (each an
1325 jsr166 1.21 * {@code Object}) in the proper order, followed by a null
1326 dl 1.1 */
1327     private void writeObject(java.io.ObjectOutputStream s)
1328     throws java.io.IOException {
1329 jsr166 1.21 final ReentrantLock lock = this.lock;
1330 dl 1.1 lock.lock();
1331     try {
1332     // Write out capacity and any hidden stuff
1333     s.defaultWriteObject();
1334     // Write out all elements in the proper order.
1335     for (Node<E> p = first; p != null; p = p.next)
1336     s.writeObject(p.item);
1337     // Use trailing null as sentinel
1338     s.writeObject(null);
1339     } finally {
1340 jsr166 1.65 // checkInvariants();
1341 dl 1.1 lock.unlock();
1342     }
1343     }
1344    
1345     /**
1346 jsr166 1.31 * Reconstitutes this deque from a stream (that is, deserializes it).
1347 jsr166 1.48 * @param s the stream
1348 jsr166 1.49 * @throws ClassNotFoundException if the class of a serialized object
1349     * could not be found
1350     * @throws java.io.IOException if an I/O error occurs
1351 dl 1.1 */
1352     private void readObject(java.io.ObjectInputStream s)
1353     throws java.io.IOException, ClassNotFoundException {
1354     s.defaultReadObject();
1355     count = 0;
1356     first = null;
1357     last = null;
1358     // Read in all elements and place in queue
1359     for (;;) {
1360 jsr166 1.67 @SuppressWarnings("unchecked") E item = (E)s.readObject();
1361 dl 1.1 if (item == null)
1362     break;
1363     add(item);
1364     }
1365     }
1366 jsr166 1.3
1367 jsr166 1.65 void checkInvariants() {
1368     // assert lock.isHeldByCurrentThread();
1369     // Nodes may get self-linked or lose their item, but only
1370     // after being unlinked and becoming unreachable from first.
1371     for (Node<E> p = first; p != null; p = p.next) {
1372     // assert p.next != p;
1373     // assert p.item != null;
1374     }
1375     }
1376    
1377 dl 1.1 }