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, 3 months ago) by dl
Branch: MAIN
Changes since 1.49: +3 -1 lines
Log Message:
Unlink head node to help GC

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/licenses/publicdomain
5 */
6
7 package java.util.concurrent;
8 import java.util.concurrent.atomic.*;
9 import java.util.concurrent.locks.*;
10 import java.util.*;
11
12 /**
13 * An optionally-bounded {@linkplain BlockingQueue blocking queue} based on
14 * linked nodes.
15 * This queue orders elements FIFO (first-in-first-out).
16 * The <em>head</em> of the queue is that element that has been on the
17 * queue the longest time.
18 * The <em>tail</em> of the queue is that element that has been on the
19 * 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 * Linked queues typically have higher throughput than array-based queues but
23 * less predictable performance in most concurrent applications.
24 *
25 * <p> The optional capacity bound constructor argument serves as a
26 * way to prevent excessive queue expansion. The capacity, if unspecified,
27 * is equal to {@link Integer#MAX_VALUE}. Linked nodes are
28 * dynamically created upon each insertion unless this would bring the
29 * queue above capacity.
30 *
31 * <p>This class and its iterator implement all of the
32 * <em>optional</em> methods of the {@link Collection} and {@link
33 * Iterator} interfaces.
34 *
35 * <p>This class is a member of the
36 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
37 * Java Collections Framework</a>.
38 *
39 * @since 1.5
40 * @author Doug Lea
41 * @param <E> the type of elements held in this collection
42 *
43 */
44 public class LinkedBlockingQueue<E> extends AbstractQueue<E>
45 implements BlockingQueue<E>, java.io.Serializable {
46 private static final long serialVersionUID = -6903933977591709194L;
47
48 /*
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 * takes signalling puts. Operations such as remove(Object) and
59 * iterators acquire both locks.
60 */
61
62 /**
63 * Linked list node class
64 */
65 static class Node<E> {
66 /** The item, volatile to ensure barrier separating write and read */
67 volatile E item;
68 Node<E> next;
69 Node(E x) { item = x; }
70 }
71
72 /** The capacity bound, or Integer.MAX_VALUE if none */
73 private final int capacity;
74
75 /** Current number of elements */
76 private final AtomicInteger count = new AtomicInteger(0);
77
78 /** Head of linked list */
79 private transient Node<E> head;
80
81 /** Tail of linked list */
82 private transient Node<E> last;
83
84 /** Lock held by take, poll, etc */
85 private final ReentrantLock takeLock = new ReentrantLock();
86
87 /** Wait queue for waiting takes */
88 private final Condition notEmpty = takeLock.newCondition();
89
90 /** Lock held by put, offer, etc */
91 private final ReentrantLock putLock = new ReentrantLock();
92
93 /** Wait queue for waiting puts */
94 private final Condition notFull = putLock.newCondition();
95
96 /**
97 * Signals a waiting take. Called only from put/offer (which do not
98 * otherwise ordinarily lock takeLock.)
99 */
100 private void signalNotEmpty() {
101 final ReentrantLock takeLock = this.takeLock;
102 takeLock.lock();
103 try {
104 notEmpty.signal();
105 } finally {
106 takeLock.unlock();
107 }
108 }
109
110 /**
111 * Signals a waiting put. Called only from take/poll.
112 */
113 private void signalNotFull() {
114 final ReentrantLock putLock = this.putLock;
115 putLock.lock();
116 try {
117 notFull.signal();
118 } finally {
119 putLock.unlock();
120 }
121 }
122
123 /**
124 * Creates a node and links it at end of queue.
125 * @param x the item
126 */
127 private void insert(E x) {
128 last = last.next = new Node<E>(x);
129 }
130
131 /**
132 * Removes a node from head of queue,
133 * @return the node
134 */
135 private E extract() {
136 Node<E> h = head;
137 Node<E> first = h.next;
138 h.next = null; // help GC
139 head = first;
140 E x = first.item;
141 first.item = null;
142 return x;
143 }
144
145 /**
146 * Lock to prevent both puts and takes.
147 */
148 private void fullyLock() {
149 putLock.lock();
150 takeLock.lock();
151 }
152
153 /**
154 * Unlock to allow both puts and takes.
155 */
156 private void fullyUnlock() {
157 takeLock.unlock();
158 putLock.unlock();
159 }
160
161
162 /**
163 * Creates a <tt>LinkedBlockingQueue</tt> with a capacity of
164 * {@link Integer#MAX_VALUE}.
165 */
166 public LinkedBlockingQueue() {
167 this(Integer.MAX_VALUE);
168 }
169
170 /**
171 * Creates a <tt>LinkedBlockingQueue</tt> with the given (fixed) capacity.
172 *
173 * @param capacity the capacity of this queue
174 * @throws IllegalArgumentException if <tt>capacity</tt> is not greater
175 * than zero
176 */
177 public LinkedBlockingQueue(int capacity) {
178 if (capacity <= 0) throw new IllegalArgumentException();
179 this.capacity = capacity;
180 last = head = new Node<E>(null);
181 }
182
183 /**
184 * Creates a <tt>LinkedBlockingQueue</tt> with a capacity of
185 * {@link Integer#MAX_VALUE}, initially containing the elements of the
186 * given collection,
187 * added in traversal order of the collection's iterator.
188 *
189 * @param c the collection of elements to initially contain
190 * @throws NullPointerException if the specified collection or any
191 * of its elements are null
192 */
193 public LinkedBlockingQueue(Collection<? extends E> c) {
194 this(Integer.MAX_VALUE);
195 for (E e : c)
196 add(e);
197 }
198
199
200 // this doc comment is overridden to remove the reference to collections
201 // greater in size than Integer.MAX_VALUE
202 /**
203 * Returns the number of elements in this queue.
204 *
205 * @return the number of elements in this queue
206 */
207 public int size() {
208 return count.get();
209 }
210
211 // this doc comment is a modified copy of the inherited doc comment,
212 // without the reference to unlimited queues.
213 /**
214 * Returns the number of additional elements that this queue can ideally
215 * (in the absence of memory or resource constraints) accept without
216 * blocking. This is always equal to the initial capacity of this queue
217 * less the current <tt>size</tt> of this queue.
218 *
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 * insert or remove an element.
223 */
224 public int remainingCapacity() {
225 return capacity - count.get();
226 }
227
228 /**
229 * Inserts the specified element at the tail of this queue, waiting if
230 * necessary for space to become available.
231 *
232 * @throws InterruptedException {@inheritDoc}
233 * @throws NullPointerException {@inheritDoc}
234 */
235 public void put(E e) throws InterruptedException {
236 if (e == null) throw new NullPointerException();
237 // Note: convention in all put/take/etc is to preset
238 // local var holding count negative to indicate failure unless set.
239 int c = -1;
240 final ReentrantLock putLock = this.putLock;
241 final AtomicInteger count = this.count;
242 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 while (count.get() == capacity)
255 notFull.await();
256 } catch (InterruptedException ie) {
257 notFull.signal(); // propagate to a non-interrupted thread
258 throw ie;
259 }
260 insert(e);
261 c = count.getAndIncrement();
262 if (c + 1 < capacity)
263 notFull.signal();
264 } finally {
265 putLock.unlock();
266 }
267 if (c == 0)
268 signalNotEmpty();
269 }
270
271 /**
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 *
275 * @return <tt>true</tt> if successful, or <tt>false</tt> if
276 * the specified waiting time elapses before space is available.
277 * @throws InterruptedException {@inheritDoc}
278 * @throws NullPointerException {@inheritDoc}
279 */
280 public boolean offer(E e, long timeout, TimeUnit unit)
281 throws InterruptedException {
282
283 if (e == null) throw new NullPointerException();
284 long nanos = unit.toNanos(timeout);
285 int c = -1;
286 final ReentrantLock putLock = this.putLock;
287 final AtomicInteger count = this.count;
288 putLock.lockInterruptibly();
289 try {
290 for (;;) {
291 if (count.get() < capacity) {
292 insert(e);
293 c = count.getAndIncrement();
294 if (c + 1 < capacity)
295 notFull.signal();
296 break;
297 }
298 if (nanos <= 0)
299 return false;
300 try {
301 nanos = notFull.awaitNanos(nanos);
302 } catch (InterruptedException ie) {
303 notFull.signal(); // propagate to a non-interrupted thread
304 throw ie;
305 }
306 }
307 } finally {
308 putLock.unlock();
309 }
310 if (c == 0)
311 signalNotEmpty();
312 return true;
313 }
314
315 /**
316 * 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 *
324 * @throws NullPointerException if the specified element is null
325 */
326 public boolean offer(E e) {
327 if (e == null) throw new NullPointerException();
328 final AtomicInteger count = this.count;
329 if (count.get() == capacity)
330 return false;
331 int c = -1;
332 final ReentrantLock putLock = this.putLock;
333 putLock.lock();
334 try {
335 if (count.get() < capacity) {
336 insert(e);
337 c = count.getAndIncrement();
338 if (c + 1 < capacity)
339 notFull.signal();
340 }
341 } finally {
342 putLock.unlock();
343 }
344 if (c == 0)
345 signalNotEmpty();
346 return c >= 0;
347 }
348
349
350 public E take() throws InterruptedException {
351 E x;
352 int c = -1;
353 final AtomicInteger count = this.count;
354 final ReentrantLock takeLock = this.takeLock;
355 takeLock.lockInterruptibly();
356 try {
357 try {
358 while (count.get() == 0)
359 notEmpty.await();
360 } catch (InterruptedException ie) {
361 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 } finally {
370 takeLock.unlock();
371 }
372 if (c == capacity)
373 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 long nanos = unit.toNanos(timeout);
381 final AtomicInteger count = this.count;
382 final ReentrantLock takeLock = this.takeLock;
383 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 } catch (InterruptedException ie) {
398 notEmpty.signal(); // propagate to a non-interrupted thread
399 throw ie;
400 }
401 }
402 } finally {
403 takeLock.unlock();
404 }
405 if (c == capacity)
406 signalNotFull();
407 return x;
408 }
409
410 public E poll() {
411 final AtomicInteger count = this.count;
412 if (count.get() == 0)
413 return null;
414 E x = null;
415 int c = -1;
416 final ReentrantLock takeLock = this.takeLock;
417 takeLock.lock();
418 try {
419 if (count.get() > 0) {
420 x = extract();
421 c = count.getAndDecrement();
422 if (c > 1)
423 notEmpty.signal();
424 }
425 } finally {
426 takeLock.unlock();
427 }
428 if (c == capacity)
429 signalNotFull();
430 return x;
431 }
432
433
434 public E peek() {
435 if (count.get() == 0)
436 return null;
437 final ReentrantLock takeLock = this.takeLock;
438 takeLock.lock();
439 try {
440 Node<E> first = head.next;
441 if (first == null)
442 return null;
443 else
444 return first.item;
445 } finally {
446 takeLock.unlock();
447 }
448 }
449
450 /**
451 * 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 */
461 public boolean remove(Object o) {
462 if (o == null) return false;
463 boolean removed = false;
464 fullyLock();
465 try {
466 Node<E> trail = head;
467 Node<E> p = head.next;
468 while (p != null) {
469 if (o.equals(p.item)) {
470 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 if (last == p)
480 last = trail;
481 if (count.getAndDecrement() == capacity)
482 notFull.signalAll();
483 }
484 } finally {
485 fullyUnlock();
486 }
487 return removed;
488 }
489
490 /**
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 *
498 * <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 public Object[] toArray() {
504 fullyLock();
505 try {
506 int size = count.get();
507 Object[] a = new Object[size];
508 int k = 0;
509 for (Node<E> p = head.next; p != null; p = p.next)
510 a[k++] = p.item;
511 return a;
512 } finally {
513 fullyUnlock();
514 }
515 }
516
517 /**
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 public <T> T[] toArray(T[] a) {
554 fullyLock();
555 try {
556 int size = count.get();
557 if (a.length < size)
558 a = (T[])java.lang.reflect.Array.newInstance
559 (a.getClass().getComponentType(), size);
560
561 int k = 0;
562 for (Node p = head.next; p != null; p = p.next)
563 a[k++] = (T)p.item;
564 if (a.length > k)
565 a[k] = null;
566 return a;
567 } finally {
568 fullyUnlock();
569 }
570 }
571
572 public String toString() {
573 fullyLock();
574 try {
575 return super.toString();
576 } finally {
577 fullyUnlock();
578 }
579 }
580
581 /**
582 * Atomically removes all of the elements from this queue.
583 * The queue will be empty after this call returns.
584 */
585 public void clear() {
586 fullyLock();
587 try {
588 head.next = null;
589 assert head.item == null;
590 last = head;
591 if (count.getAndSet(0) == capacity)
592 notFull.signalAll();
593 } finally {
594 fullyUnlock();
595 }
596 }
597
598 /**
599 * @throws UnsupportedOperationException {@inheritDoc}
600 * @throws ClassCastException {@inheritDoc}
601 * @throws NullPointerException {@inheritDoc}
602 * @throws IllegalArgumentException {@inheritDoc}
603 */
604 public int drainTo(Collection<? super E> c) {
605 if (c == null)
606 throw new NullPointerException();
607 if (c == this)
608 throw new IllegalArgumentException();
609 Node<E> first;
610 fullyLock();
611 try {
612 first = head.next;
613 head.next = null;
614 assert head.item == null;
615 last = head;
616 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 for (Node<E> p = first; p != null; p = p.next) {
624 c.add(p.item);
625 p.item = null;
626 ++n;
627 }
628 return n;
629 }
630
631 /**
632 * @throws UnsupportedOperationException {@inheritDoc}
633 * @throws ClassCastException {@inheritDoc}
634 * @throws NullPointerException {@inheritDoc}
635 * @throws IllegalArgumentException {@inheritDoc}
636 */
637 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 Node<E> p = head.next;
646 while (p != null && n < maxElements) {
647 c.add(p.item);
648 p.item = null;
649 p = p.next;
650 ++n;
651 }
652 if (n != 0) {
653 head.next = p;
654 assert head.item == null;
655 if (p == null)
656 last = head;
657 if (count.getAndAdd(-n) == capacity)
658 notFull.signalAll();
659 }
660 return n;
661 } finally {
662 fullyUnlock();
663 }
664 }
665
666 /**
667 * Returns an iterator over the elements in this queue in proper sequence.
668 * The returned <tt>Iterator</tt> is a "weakly consistent" iterator that
669 * will never throw {@link ConcurrentModificationException},
670 * 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 *
674 * @return an iterator over the elements in this queue in proper sequence
675 */
676 public Iterator<E> iterator() {
677 return new Itr();
678 }
679
680 private class Itr implements Iterator<E> {
681 /*
682 * 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 private Node<E> current;
687 private Node<E> lastRet;
688 private E currentElement;
689
690 Itr() {
691 final ReentrantLock putLock = LinkedBlockingQueue.this.putLock;
692 final ReentrantLock takeLock = LinkedBlockingQueue.this.takeLock;
693 putLock.lock();
694 takeLock.lock();
695 try {
696 current = head.next;
697 if (current != null)
698 currentElement = current.item;
699 } finally {
700 takeLock.unlock();
701 putLock.unlock();
702 }
703 }
704
705 public boolean hasNext() {
706 return current != null;
707 }
708
709 public E next() {
710 final ReentrantLock putLock = LinkedBlockingQueue.this.putLock;
711 final ReentrantLock takeLock = LinkedBlockingQueue.this.takeLock;
712 putLock.lock();
713 takeLock.lock();
714 try {
715 if (current == null)
716 throw new NoSuchElementException();
717 E x = currentElement;
718 lastRet = current;
719 current = current.next;
720 if (current != null)
721 currentElement = current.item;
722 return x;
723 } finally {
724 takeLock.unlock();
725 putLock.unlock();
726 }
727 }
728
729 public void remove() {
730 if (lastRet == null)
731 throw new IllegalStateException();
732 final ReentrantLock putLock = LinkedBlockingQueue.this.putLock;
733 final ReentrantLock takeLock = LinkedBlockingQueue.this.takeLock;
734 putLock.lock();
735 takeLock.lock();
736 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 if (last == p)
749 last = trail;
750 int c = count.getAndDecrement();
751 if (c == capacity)
752 notFull.signalAll();
753 }
754 } finally {
755 takeLock.unlock();
756 putLock.unlock();
757 }
758 }
759 }
760
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 * @param s the stream
768 */
769 private void writeObject(java.io.ObjectOutputStream s)
770 throws java.io.IOException {
771
772 fullyLock();
773 try {
774 // Write out any hidden stuff, plus capacity
775 s.defaultWriteObject();
776
777 // Write out all elements in the proper order.
778 for (Node<E> p = head.next; p != null; p = p.next)
779 s.writeObject(p.item);
780
781 // Use trailing null as sentinel
782 s.writeObject(null);
783 } finally {
784 fullyUnlock();
785 }
786 }
787
788 /**
789 * Reconstitute this queue instance from a stream (that is,
790 * deserialize it).
791 * @param s the stream
792 */
793 private void readObject(java.io.ObjectInputStream s)
794 throws java.io.IOException, ClassNotFoundException {
795 // Read in capacity, and any hidden stuff
796 s.defaultReadObject();
797
798 count.set(0);
799 last = head = new Node<E>(null);
800
801 // Read in all elements and place in queue
802 for (;;) {
803 E item = (E)s.readObject();
804 if (item == null)
805 break;
806 add(item);
807 }
808 }
809 }