ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingQueue.java
Revision: 1.67
Committed: Thu Nov 24 02:35:13 2011 UTC (12 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.66: +0 -2 lines
Log Message:
whitespace

File Contents

# Content
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 * http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 package java.util.concurrent;
8
9 import java.util.concurrent.atomic.AtomicInteger;
10 import java.util.concurrent.locks.Condition;
11 import java.util.concurrent.locks.ReentrantLock;
12 import java.util.AbstractQueue;
13 import java.util.Collection;
14 import java.util.Iterator;
15 import java.util.NoSuchElementException;
16
17 /**
18 * An optionally-bounded {@linkplain BlockingQueue blocking queue} based on
19 * linked nodes.
20 * This queue orders elements FIFO (first-in-first-out).
21 * The <em>head</em> of the queue is that element that has been on the
22 * queue the longest time.
23 * The <em>tail</em> of the queue is that element that has been on the
24 * queue the shortest time. New elements
25 * are inserted at the tail of the queue, and the queue retrieval
26 * operations obtain elements at the head of the queue.
27 * Linked queues typically have higher throughput than array-based queues but
28 * less predictable performance in most concurrent applications.
29 *
30 * <p> The optional capacity bound constructor argument serves as a
31 * way to prevent excessive queue expansion. The capacity, if unspecified,
32 * is equal to {@link Integer#MAX_VALUE}. Linked nodes are
33 * dynamically created upon each insertion unless this would bring the
34 * queue above capacity.
35 *
36 * <p>This class and its iterator implement all of the
37 * <em>optional</em> methods of the {@link Collection} and {@link
38 * Iterator} interfaces.
39 *
40 * <p>This class is a member of the
41 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
42 * Java Collections Framework</a>.
43 *
44 * @since 1.5
45 * @author Doug Lea
46 * @param <E> the type of elements held in this collection
47 *
48 */
49 public class LinkedBlockingQueue<E> extends AbstractQueue<E>
50 implements BlockingQueue<E>, java.io.Serializable {
51 private static final long serialVersionUID = -6903933977591709194L;
52
53 /*
54 * A variant of the "two lock queue" algorithm. The putLock gates
55 * entry to put (and offer), and has an associated condition for
56 * waiting puts. Similarly for the takeLock. The "count" field
57 * that they both rely on is maintained as an atomic to avoid
58 * needing to get both locks in most cases. Also, to minimize need
59 * for puts to get takeLock and vice-versa, cascading notifies are
60 * used. When a put notices that it has enabled at least one take,
61 * it signals taker. That taker in turn signals others if more
62 * items have been entered since the signal. And symmetrically for
63 * takes signalling puts. Operations such as remove(Object) and
64 * iterators acquire both locks.
65 *
66 * Visibility between writers and readers is provided as follows:
67 *
68 * Whenever an element is enqueued, the putLock is acquired and
69 * count updated. A subsequent reader guarantees visibility to the
70 * enqueued Node by either acquiring the putLock (via fullyLock)
71 * or by acquiring the takeLock, and then reading n = count.get();
72 * this gives visibility to the first n items.
73 *
74 * To implement weakly consistent iterators, it appears we need to
75 * keep all Nodes GC-reachable from a predecessor dequeued Node.
76 * That would cause two problems:
77 * - allow a rogue Iterator to cause unbounded memory retention
78 * - cause cross-generational linking of old Nodes to new Nodes if
79 * a Node was tenured while live, which generational GCs have a
80 * hard time dealing with, causing repeated major collections.
81 * However, only non-deleted Nodes need to be reachable from
82 * dequeued Nodes, and reachability does not necessarily have to
83 * be of the kind understood by the GC. We use the trick of
84 * linking a Node that has just been dequeued to itself. Such a
85 * self-link implicitly means to advance to head.next.
86 */
87
88 /**
89 * Linked list node class
90 */
91 static class Node<E> {
92 E item;
93
94 /**
95 * One of:
96 * - the real successor Node
97 * - this Node, meaning the successor is head.next
98 * - null, meaning there is no successor (this is the last node)
99 */
100 Node<E> next;
101
102 Node(E x) { item = x; }
103 }
104
105 /** The capacity bound, or Integer.MAX_VALUE if none */
106 private final int capacity;
107
108 /** Current number of elements */
109 private final AtomicInteger count = new AtomicInteger();
110
111 /**
112 * Head of linked list.
113 * Invariant: head.item == null
114 */
115 transient Node<E> head;
116
117 /**
118 * Tail of linked list.
119 * Invariant: last.next == null
120 */
121 private transient Node<E> last;
122
123 /** Lock held by take, poll, etc */
124 private final ReentrantLock takeLock = new ReentrantLock();
125
126 /** Wait queue for waiting takes */
127 private final Condition notEmpty = takeLock.newCondition();
128
129 /** Lock held by put, offer, etc */
130 private final ReentrantLock putLock = new ReentrantLock();
131
132 /** Wait queue for waiting puts */
133 private final Condition notFull = putLock.newCondition();
134
135 /**
136 * Signals a waiting take. Called only from put/offer (which do not
137 * otherwise ordinarily lock takeLock.)
138 */
139 private void signalNotEmpty() {
140 final ReentrantLock takeLock = this.takeLock;
141 takeLock.lock();
142 try {
143 notEmpty.signal();
144 } finally {
145 takeLock.unlock();
146 }
147 }
148
149 /**
150 * Signals a waiting put. Called only from take/poll.
151 */
152 private void signalNotFull() {
153 final ReentrantLock putLock = this.putLock;
154 putLock.lock();
155 try {
156 notFull.signal();
157 } finally {
158 putLock.unlock();
159 }
160 }
161
162 /**
163 * Links node at end of queue.
164 *
165 * @param node the node
166 */
167 private void enqueue(Node<E> node) {
168 // assert putLock.isHeldByCurrentThread();
169 // assert last.next == null;
170 last = last.next = node;
171 }
172
173 /**
174 * Removes a node from head of queue.
175 *
176 * @return the node
177 */
178 private E dequeue() {
179 // assert takeLock.isHeldByCurrentThread();
180 // assert head.item == null;
181 Node<E> h = head;
182 Node<E> first = h.next;
183 h.next = h; // help GC
184 head = first;
185 E x = first.item;
186 first.item = null;
187 return x;
188 }
189
190 /**
191 * Lock to prevent both puts and takes.
192 */
193 void fullyLock() {
194 putLock.lock();
195 takeLock.lock();
196 }
197
198 /**
199 * Unlock to allow both puts and takes.
200 */
201 void fullyUnlock() {
202 takeLock.unlock();
203 putLock.unlock();
204 }
205
206 // /**
207 // * Tells whether both locks are held by current thread.
208 // */
209 // boolean isFullyLocked() {
210 // return (putLock.isHeldByCurrentThread() &&
211 // takeLock.isHeldByCurrentThread());
212 // }
213
214 /**
215 * Creates a {@code LinkedBlockingQueue} with a capacity of
216 * {@link Integer#MAX_VALUE}.
217 */
218 public LinkedBlockingQueue() {
219 this(Integer.MAX_VALUE);
220 }
221
222 /**
223 * Creates a {@code LinkedBlockingQueue} with the given (fixed) capacity.
224 *
225 * @param capacity the capacity of this queue
226 * @throws IllegalArgumentException if {@code capacity} is not greater
227 * than zero
228 */
229 public LinkedBlockingQueue(int capacity) {
230 if (capacity <= 0) throw new IllegalArgumentException();
231 this.capacity = capacity;
232 last = head = new Node<E>(null);
233 }
234
235 /**
236 * Creates a {@code LinkedBlockingQueue} with a capacity of
237 * {@link Integer#MAX_VALUE}, initially containing the elements of the
238 * given collection,
239 * added in traversal order of the collection's iterator.
240 *
241 * @param c the collection of elements to initially contain
242 * @throws NullPointerException if the specified collection or any
243 * of its elements are null
244 */
245 public LinkedBlockingQueue(Collection<? extends E> c) {
246 this(Integer.MAX_VALUE);
247 final ReentrantLock putLock = this.putLock;
248 putLock.lock(); // Never contended, but necessary for visibility
249 try {
250 int n = 0;
251 for (E e : c) {
252 if (e == null)
253 throw new NullPointerException();
254 if (n == capacity)
255 throw new IllegalStateException("Queue full");
256 enqueue(new Node<E>(e));
257 ++n;
258 }
259 count.set(n);
260 } finally {
261 putLock.unlock();
262 }
263 }
264
265 // this doc comment is overridden to remove the reference to collections
266 // greater in size than Integer.MAX_VALUE
267 /**
268 * Returns the number of elements in this queue.
269 *
270 * @return the number of elements in this queue
271 */
272 public int size() {
273 return count.get();
274 }
275
276 // this doc comment is a modified copy of the inherited doc comment,
277 // without the reference to unlimited queues.
278 /**
279 * Returns the number of additional elements that this queue can ideally
280 * (in the absence of memory or resource constraints) accept without
281 * blocking. This is always equal to the initial capacity of this queue
282 * less the current {@code size} of this queue.
283 *
284 * <p>Note that you <em>cannot</em> always tell if an attempt to insert
285 * an element will succeed by inspecting {@code remainingCapacity}
286 * because it may be the case that another thread is about to
287 * insert or remove an element.
288 */
289 public int remainingCapacity() {
290 return capacity - count.get();
291 }
292
293 /**
294 * Inserts the specified element at the tail of this queue, waiting if
295 * necessary for space to become available.
296 *
297 * @throws InterruptedException {@inheritDoc}
298 * @throws NullPointerException {@inheritDoc}
299 */
300 public void put(E e) throws InterruptedException {
301 if (e == null) throw new NullPointerException();
302 // Note: convention in all put/take/etc is to preset local var
303 // holding count negative to indicate failure unless set.
304 int c = -1;
305 Node<E> node = new Node<E>(e);
306 final ReentrantLock putLock = this.putLock;
307 final AtomicInteger count = this.count;
308 putLock.lockInterruptibly();
309 try {
310 /*
311 * Note that count is used in wait guard even though it is
312 * not protected by lock. This works because count can
313 * only decrease at this point (all other puts are shut
314 * out by lock), and we (or some other waiting put) are
315 * signalled if it ever changes from capacity. Similarly
316 * for all other uses of count in other wait guards.
317 */
318 while (count.get() == capacity) {
319 notFull.await();
320 }
321 enqueue(node);
322 c = count.getAndIncrement();
323 if (c + 1 < capacity)
324 notFull.signal();
325 } finally {
326 putLock.unlock();
327 }
328 if (c == 0)
329 signalNotEmpty();
330 }
331
332 /**
333 * Inserts the specified element at the tail of this queue, waiting if
334 * necessary up to the specified wait time for space to become available.
335 *
336 * @return {@code true} if successful, or {@code false} if
337 * the specified waiting time elapses before space is available.
338 * @throws InterruptedException {@inheritDoc}
339 * @throws NullPointerException {@inheritDoc}
340 */
341 public boolean offer(E e, long timeout, TimeUnit unit)
342 throws InterruptedException {
343
344 if (e == null) throw new NullPointerException();
345 long nanos = unit.toNanos(timeout);
346 int c = -1;
347 final ReentrantLock putLock = this.putLock;
348 final AtomicInteger count = this.count;
349 putLock.lockInterruptibly();
350 try {
351 while (count.get() == capacity) {
352 if (nanos <= 0)
353 return false;
354 nanos = notFull.awaitNanos(nanos);
355 }
356 enqueue(new Node<E>(e));
357 c = count.getAndIncrement();
358 if (c + 1 < capacity)
359 notFull.signal();
360 } finally {
361 putLock.unlock();
362 }
363 if (c == 0)
364 signalNotEmpty();
365 return true;
366 }
367
368 /**
369 * Inserts the specified element at the tail of this queue if it is
370 * possible to do so immediately without exceeding the queue's capacity,
371 * returning {@code true} upon success and {@code false} if this queue
372 * is full.
373 * When using a capacity-restricted queue, this method is generally
374 * preferable to method {@link BlockingQueue#add add}, which can fail to
375 * insert an element only by throwing an exception.
376 *
377 * @throws NullPointerException if the specified element is null
378 */
379 public boolean offer(E e) {
380 if (e == null) throw new NullPointerException();
381 final AtomicInteger count = this.count;
382 if (count.get() == capacity)
383 return false;
384 int c = -1;
385 Node<E> node = new Node<E>(e);
386 final ReentrantLock putLock = this.putLock;
387 putLock.lock();
388 try {
389 if (count.get() < capacity) {
390 enqueue(node);
391 c = count.getAndIncrement();
392 if (c + 1 < capacity)
393 notFull.signal();
394 }
395 } finally {
396 putLock.unlock();
397 }
398 if (c == 0)
399 signalNotEmpty();
400 return c >= 0;
401 }
402
403 public E take() throws InterruptedException {
404 E x;
405 int c = -1;
406 final AtomicInteger count = this.count;
407 final ReentrantLock takeLock = this.takeLock;
408 takeLock.lockInterruptibly();
409 try {
410 while (count.get() == 0) {
411 notEmpty.await();
412 }
413 x = dequeue();
414 c = count.getAndDecrement();
415 if (c > 1)
416 notEmpty.signal();
417 } finally {
418 takeLock.unlock();
419 }
420 if (c == capacity)
421 signalNotFull();
422 return x;
423 }
424
425 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
426 E x = null;
427 int c = -1;
428 long nanos = unit.toNanos(timeout);
429 final AtomicInteger count = this.count;
430 final ReentrantLock takeLock = this.takeLock;
431 takeLock.lockInterruptibly();
432 try {
433 while (count.get() == 0) {
434 if (nanos <= 0)
435 return null;
436 nanos = notEmpty.awaitNanos(nanos);
437 }
438 x = dequeue();
439 c = count.getAndDecrement();
440 if (c > 1)
441 notEmpty.signal();
442 } finally {
443 takeLock.unlock();
444 }
445 if (c == capacity)
446 signalNotFull();
447 return x;
448 }
449
450 public E poll() {
451 final AtomicInteger count = this.count;
452 if (count.get() == 0)
453 return null;
454 E x = null;
455 int c = -1;
456 final ReentrantLock takeLock = this.takeLock;
457 takeLock.lock();
458 try {
459 if (count.get() > 0) {
460 x = dequeue();
461 c = count.getAndDecrement();
462 if (c > 1)
463 notEmpty.signal();
464 }
465 } finally {
466 takeLock.unlock();
467 }
468 if (c == capacity)
469 signalNotFull();
470 return x;
471 }
472
473 public E peek() {
474 if (count.get() == 0)
475 return null;
476 final ReentrantLock takeLock = this.takeLock;
477 takeLock.lock();
478 try {
479 Node<E> first = head.next;
480 if (first == null)
481 return null;
482 else
483 return first.item;
484 } finally {
485 takeLock.unlock();
486 }
487 }
488
489 /**
490 * Unlinks interior Node p with predecessor trail.
491 */
492 void unlink(Node<E> p, Node<E> trail) {
493 // assert isFullyLocked();
494 // p.next is not changed, to allow iterators that are
495 // traversing p to maintain their weak-consistency guarantee.
496 p.item = null;
497 trail.next = p.next;
498 if (last == p)
499 last = trail;
500 if (count.getAndDecrement() == capacity)
501 notFull.signal();
502 }
503
504 /**
505 * Removes a single instance of the specified element from this queue,
506 * if it is present. More formally, removes an element {@code e} such
507 * that {@code o.equals(e)}, if this queue contains one or more such
508 * elements.
509 * Returns {@code true} if this queue contained the specified element
510 * (or equivalently, if this queue changed as a result of the call).
511 *
512 * @param o element to be removed from this queue, if present
513 * @return {@code true} if this queue changed as a result of the call
514 */
515 public boolean remove(Object o) {
516 if (o == null) return false;
517 fullyLock();
518 try {
519 for (Node<E> trail = head, p = trail.next;
520 p != null;
521 trail = p, p = p.next) {
522 if (o.equals(p.item)) {
523 unlink(p, trail);
524 return true;
525 }
526 }
527 return false;
528 } finally {
529 fullyUnlock();
530 }
531 }
532
533 /**
534 * Returns {@code true} if this queue contains the specified element.
535 * More formally, returns {@code true} if and only if this queue contains
536 * at least one element {@code e} such that {@code o.equals(e)}.
537 *
538 * @param o object to be checked for containment in this queue
539 * @return {@code true} if this queue contains the specified element
540 */
541 public boolean contains(Object o) {
542 if (o == null) return false;
543 fullyLock();
544 try {
545 for (Node<E> p = head.next; p != null; p = p.next)
546 if (o.equals(p.item))
547 return true;
548 return false;
549 } finally {
550 fullyUnlock();
551 }
552 }
553
554 /**
555 * Returns an array containing all of the elements in this queue, in
556 * proper sequence.
557 *
558 * <p>The returned array will be "safe" in that no references to it are
559 * maintained by this queue. (In other words, this method must allocate
560 * a new array). The caller is thus free to modify the returned array.
561 *
562 * <p>This method acts as bridge between array-based and collection-based
563 * APIs.
564 *
565 * @return an array containing all of the elements in this queue
566 */
567 public Object[] toArray() {
568 fullyLock();
569 try {
570 int size = count.get();
571 Object[] a = new Object[size];
572 int k = 0;
573 for (Node<E> p = head.next; p != null; p = p.next)
574 a[k++] = p.item;
575 return a;
576 } finally {
577 fullyUnlock();
578 }
579 }
580
581 /**
582 * Returns an array containing all of the elements in this queue, in
583 * proper sequence; the runtime type of the returned array is that of
584 * the specified array. If the queue fits in the specified array, it
585 * is returned therein. Otherwise, a new array is allocated with the
586 * runtime type of the specified array and the size of this queue.
587 *
588 * <p>If this queue fits in the specified array with room to spare
589 * (i.e., the array has more elements than this queue), the element in
590 * the array immediately following the end of the queue is set to
591 * {@code null}.
592 *
593 * <p>Like the {@link #toArray()} method, this method acts as bridge between
594 * array-based and collection-based APIs. Further, this method allows
595 * precise control over the runtime type of the output array, and may,
596 * under certain circumstances, be used to save allocation costs.
597 *
598 * <p>Suppose {@code x} is a queue known to contain only strings.
599 * The following code can be used to dump the queue into a newly
600 * allocated array of {@code String}:
601 *
602 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
603 *
604 * Note that {@code toArray(new Object[0])} is identical in function to
605 * {@code toArray()}.
606 *
607 * @param a the array into which the elements of the queue are to
608 * be stored, if it is big enough; otherwise, a new array of the
609 * same runtime type is allocated for this purpose
610 * @return an array containing all of the elements in this queue
611 * @throws ArrayStoreException if the runtime type of the specified array
612 * is not a supertype of the runtime type of every element in
613 * this queue
614 * @throws NullPointerException if the specified array is null
615 */
616 @SuppressWarnings("unchecked")
617 public <T> T[] toArray(T[] a) {
618 fullyLock();
619 try {
620 int size = count.get();
621 if (a.length < size)
622 a = (T[])java.lang.reflect.Array.newInstance
623 (a.getClass().getComponentType(), size);
624
625 int k = 0;
626 for (Node<E> p = head.next; p != null; p = p.next)
627 a[k++] = (T)p.item;
628 if (a.length > k)
629 a[k] = null;
630 return a;
631 } finally {
632 fullyUnlock();
633 }
634 }
635
636 public String toString() {
637 fullyLock();
638 try {
639 Node<E> p = head.next;
640 if (p == null)
641 return "[]";
642
643 StringBuilder sb = new StringBuilder();
644 sb.append('[');
645 for (;;) {
646 E e = p.item;
647 sb.append(e == this ? "(this Collection)" : e);
648 p = p.next;
649 if (p == null)
650 return sb.append(']').toString();
651 sb.append(',').append(' ');
652 }
653 } finally {
654 fullyUnlock();
655 }
656 }
657
658 /**
659 * Atomically removes all of the elements from this queue.
660 * The queue will be empty after this call returns.
661 */
662 public void clear() {
663 fullyLock();
664 try {
665 for (Node<E> p, h = head; (p = h.next) != null; h = p) {
666 h.next = h;
667 p.item = null;
668 }
669 head = last;
670 // assert head.item == null && head.next == null;
671 if (count.getAndSet(0) == capacity)
672 notFull.signal();
673 } finally {
674 fullyUnlock();
675 }
676 }
677
678 /**
679 * @throws UnsupportedOperationException {@inheritDoc}
680 * @throws ClassCastException {@inheritDoc}
681 * @throws NullPointerException {@inheritDoc}
682 * @throws IllegalArgumentException {@inheritDoc}
683 */
684 public int drainTo(Collection<? super E> c) {
685 return drainTo(c, Integer.MAX_VALUE);
686 }
687
688 /**
689 * @throws UnsupportedOperationException {@inheritDoc}
690 * @throws ClassCastException {@inheritDoc}
691 * @throws NullPointerException {@inheritDoc}
692 * @throws IllegalArgumentException {@inheritDoc}
693 */
694 public int drainTo(Collection<? super E> c, int maxElements) {
695 if (c == null)
696 throw new NullPointerException();
697 if (c == this)
698 throw new IllegalArgumentException();
699 if (maxElements <= 0)
700 return 0;
701 boolean signalNotFull = false;
702 final ReentrantLock takeLock = this.takeLock;
703 takeLock.lock();
704 try {
705 int n = Math.min(maxElements, count.get());
706 // count.get provides visibility to first n Nodes
707 Node<E> h = head;
708 int i = 0;
709 try {
710 while (i < n) {
711 Node<E> p = h.next;
712 c.add(p.item);
713 p.item = null;
714 h.next = h;
715 h = p;
716 ++i;
717 }
718 return n;
719 } finally {
720 // Restore invariants even if c.add() threw
721 if (i > 0) {
722 // assert h.item == null;
723 head = h;
724 signalNotFull = (count.getAndAdd(-i) == capacity);
725 }
726 }
727 } finally {
728 takeLock.unlock();
729 if (signalNotFull)
730 signalNotFull();
731 }
732 }
733
734 /**
735 * Returns an iterator over the elements in this queue in proper sequence.
736 * The elements will be returned in order from first (head) to last (tail).
737 *
738 * <p>The returned iterator is a "weakly consistent" iterator that
739 * will never throw {@link java.util.ConcurrentModificationException
740 * ConcurrentModificationException}, and guarantees to traverse
741 * elements as they existed upon construction of the iterator, and
742 * may (but is not guaranteed to) reflect any modifications
743 * subsequent to construction.
744 *
745 * @return an iterator over the elements in this queue in proper sequence
746 */
747 public Iterator<E> iterator() {
748 return new Itr();
749 }
750
751 private class Itr implements Iterator<E> {
752 /*
753 * Basic weakly-consistent iterator. At all times hold the next
754 * item to hand out so that if hasNext() reports true, we will
755 * still have it to return even if lost race with a take etc.
756 */
757 private Node<E> current;
758 private Node<E> lastRet;
759 private E currentElement;
760
761 Itr() {
762 fullyLock();
763 try {
764 current = head.next;
765 if (current != null)
766 currentElement = current.item;
767 } finally {
768 fullyUnlock();
769 }
770 }
771
772 public boolean hasNext() {
773 return current != null;
774 }
775
776 /**
777 * Returns the next live successor of p, or null if no such.
778 *
779 * Unlike other traversal methods, iterators need to handle both:
780 * - dequeued nodes (p.next == p)
781 * - (possibly multiple) interior removed nodes (p.item == null)
782 */
783 private Node<E> nextNode(Node<E> p) {
784 for (;;) {
785 Node<E> s = p.next;
786 if (s == p)
787 return head.next;
788 if (s == null || s.item != null)
789 return s;
790 p = s;
791 }
792 }
793
794 public E next() {
795 fullyLock();
796 try {
797 if (current == null)
798 throw new NoSuchElementException();
799 E x = currentElement;
800 lastRet = current;
801 current = nextNode(current);
802 currentElement = (current == null) ? null : current.item;
803 return x;
804 } finally {
805 fullyUnlock();
806 }
807 }
808
809 public void remove() {
810 if (lastRet == null)
811 throw new IllegalStateException();
812 fullyLock();
813 try {
814 Node<E> node = lastRet;
815 lastRet = null;
816 for (Node<E> trail = head, p = trail.next;
817 p != null;
818 trail = p, p = p.next) {
819 if (p == node) {
820 unlink(p, trail);
821 break;
822 }
823 }
824 } finally {
825 fullyUnlock();
826 }
827 }
828 }
829
830 /**
831 * Saves the state to a stream (that is, serializes it).
832 *
833 * @serialData The capacity is emitted (int), followed by all of
834 * its elements (each an {@code Object}) in the proper order,
835 * followed by a null
836 * @param s the stream
837 */
838 private void writeObject(java.io.ObjectOutputStream s)
839 throws java.io.IOException {
840
841 fullyLock();
842 try {
843 // Write out any hidden stuff, plus capacity
844 s.defaultWriteObject();
845
846 // Write out all elements in the proper order.
847 for (Node<E> p = head.next; p != null; p = p.next)
848 s.writeObject(p.item);
849
850 // Use trailing null as sentinel
851 s.writeObject(null);
852 } finally {
853 fullyUnlock();
854 }
855 }
856
857 /**
858 * Reconstitutes this queue from a stream (that is, deserializes it).
859 *
860 * @param s the stream
861 */
862 private void readObject(java.io.ObjectInputStream s)
863 throws java.io.IOException, ClassNotFoundException {
864 // Read in capacity, and any hidden stuff
865 s.defaultReadObject();
866
867 count.set(0);
868 last = head = new Node<E>(null);
869
870 // Read in all elements and place in queue
871 for (;;) {
872 @SuppressWarnings("unchecked")
873 E item = (E)s.readObject();
874 if (item == null)
875 break;
876 add(item);
877 }
878 }
879 }