ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingQueue.java
Revision: 1.50
Committed: Thu Feb 12 01:00:43 2009 UTC (15 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.49: +3 -1 lines
Log Message:
Unlink head node to help GC

File Contents

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