ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingQueue.java
Revision: 1.22
Committed: Mon Sep 15 06:24:21 2003 UTC (20 years, 9 months ago) by dholmes
Branch: MAIN
Changes since 1.21: +11 -4 lines
Log Message:
Restored overriding commenst referring to insertion at tail

File Contents

# User Rev Content
1 dl 1.2 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain. Use, modify, and
4     * redistribute this code in any way without acknowledgement.
5     */
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.21 * <p>This class implements all of the <em>optional</em> methods
32     * of the {@link Collection} and {@link Iterator} interfaces.
33     *
34 dl 1.6 * @since 1.5
35     * @author Doug Lea
36 tim 1.12 *
37 tim 1.1 **/
38 dl 1.2 public class LinkedBlockingQueue<E> extends AbstractQueue<E>
39 tim 1.1 implements BlockingQueue<E>, java.io.Serializable {
40 dl 1.18 private static final long serialVersionUID = -6903933977591709194L;
41 tim 1.1
42 dl 1.2 /*
43     * A variant of the "two lock queue" algorithm. The putLock gates
44     * entry to put (and offer), and has an associated condition for
45     * waiting puts. Similarly for the takeLock. The "count" field
46     * that they both rely on is maintained as an atomic to avoid
47     * needing to get both locks in most cases. Also, to minimize need
48     * for puts to get takeLock and vice-versa, cascading notifies are
49     * used. When a put notices that it has enabled at least one take,
50     * it signals taker. That taker in turn signals others if more
51     * items have been entered since the signal. And symmetrically for
52 tim 1.12 * takes signalling puts. Operations such as remove(Object) and
53 dl 1.2 * iterators acquire both locks.
54     */
55    
56 dl 1.6 /**
57     * Linked list node class
58     */
59 dl 1.2 static class Node<E> {
60 dl 1.6 /** The item, volatile to ensure barrier separating write and read */
61 dl 1.2 volatile E item;
62     Node<E> next;
63     Node(E x) { item = x; }
64     }
65    
66 dl 1.6 /** The capacity bound, or Integer.MAX_VALUE if none */
67 dl 1.2 private final int capacity;
68 dl 1.6
69     /** Current number of elements */
70 dl 1.19 private final AtomicInteger count = new AtomicInteger(0);
71 dl 1.2
72 dl 1.6 /** Head of linked list */
73     private transient Node<E> head;
74    
75 dholmes 1.8 /** Tail of linked list */
76 dl 1.6 private transient Node<E> last;
77 dl 1.2
78 dl 1.6 /** Lock held by take, poll, etc */
79 dl 1.5 private final ReentrantLock takeLock = new ReentrantLock();
80 dl 1.6
81     /** Wait queue for waiting takes */
82 dl 1.5 private final Condition notEmpty = takeLock.newCondition();
83 dl 1.2
84 dl 1.6 /** Lock held by put, offer, etc */
85 dl 1.5 private final ReentrantLock putLock = new ReentrantLock();
86 dl 1.6
87     /** Wait queue for waiting puts */
88 dl 1.5 private final Condition notFull = putLock.newCondition();
89 dl 1.2
90     /**
91     * Signal a waiting take. Called only from put/offer (which do not
92 dl 1.4 * otherwise ordinarily lock takeLock.)
93 dl 1.2 */
94     private void signalNotEmpty() {
95     takeLock.lock();
96     try {
97     notEmpty.signal();
98 tim 1.17 } finally {
99 dl 1.2 takeLock.unlock();
100     }
101     }
102    
103     /**
104     * Signal a waiting put. Called only from take/poll.
105     */
106     private void signalNotFull() {
107     putLock.lock();
108     try {
109     notFull.signal();
110 tim 1.17 } finally {
111 dl 1.2 putLock.unlock();
112     }
113     }
114    
115     /**
116 dholmes 1.8 * Create a node and link it at end of queue
117 dl 1.6 * @param x the item
118 dl 1.2 */
119     private void insert(E x) {
120     last = last.next = new Node<E>(x);
121     }
122    
123     /**
124     * Remove a node from head of queue,
125 dl 1.6 * @return the node
126 dl 1.2 */
127     private E extract() {
128     Node<E> first = head.next;
129     head = first;
130     E x = (E)first.item;
131     first.item = null;
132     return x;
133     }
134    
135     /**
136 tim 1.12 * Lock to prevent both puts and takes.
137 dl 1.2 */
138     private void fullyLock() {
139     putLock.lock();
140     takeLock.lock();
141 tim 1.1 }
142 dl 1.2
143     /**
144 tim 1.12 * Unlock to allow both puts and takes.
145 dl 1.2 */
146     private void fullyUnlock() {
147     takeLock.unlock();
148     putLock.unlock();
149     }
150    
151    
152     /**
153 dholmes 1.13 * Creates a <tt>LinkedBlockingQueue</tt> with a capacity of
154 dholmes 1.8 * {@link Integer#MAX_VALUE}.
155 dl 1.2 */
156     public LinkedBlockingQueue() {
157     this(Integer.MAX_VALUE);
158     }
159    
160     /**
161 tim 1.16 * Creates a <tt>LinkedBlockingQueue</tt> with the given (fixed) capacity.
162     *
163 dholmes 1.8 * @param capacity the capacity of this queue.
164     * @throws IllegalArgumentException if <tt>capacity</tt> is not greater
165 tim 1.16 * than zero.
166 dl 1.2 */
167     public LinkedBlockingQueue(int capacity) {
168 dholmes 1.8 if (capacity <= 0) throw new IllegalArgumentException();
169 dl 1.2 this.capacity = capacity;
170 dl 1.6 last = head = new Node<E>(null);
171 dl 1.2 }
172    
173     /**
174 dholmes 1.13 * Creates a <tt>LinkedBlockingQueue</tt> with a capacity of
175 dholmes 1.14 * {@link Integer#MAX_VALUE}, initially containing the elements of the
176 tim 1.12 * given collection,
177 dholmes 1.8 * added in traversal order of the collection's iterator.
178 dholmes 1.9 * @param c the collection of elements to initially contain
179     * @throws NullPointerException if <tt>c</tt> or any element within it
180     * is <tt>null</tt>
181 dl 1.2 */
182 dholmes 1.10 public LinkedBlockingQueue(Collection<? extends E> c) {
183 dl 1.2 this(Integer.MAX_VALUE);
184 tim 1.12 for (Iterator<? extends E> it = c.iterator(); it.hasNext();)
185     add(it.next());
186 dl 1.2 }
187    
188 dholmes 1.9
189 dholmes 1.8 // this doc comment is overridden to remove the reference to collections
190     // greater in size than Integer.MAX_VALUE
191 tim 1.12 /**
192 dl 1.20 * Returns the number of elements in this queue.
193     *
194     * @return the number of elements in this queue.
195 dholmes 1.8 */
196 dl 1.2 public int size() {
197     return count.get();
198 tim 1.1 }
199 dl 1.2
200 dholmes 1.8 // this doc comment is a modified copy of the inherited doc comment,
201     // without the reference to unlimited queues.
202 tim 1.12 /**
203 dholmes 1.13 * Returns the number of elements that this queue can ideally (in
204 dholmes 1.8 * the absence of memory or resource constraints) accept without
205     * blocking. This is always equal to the initial capacity of this queue
206     * less the current <tt>size</tt> of this queue.
207     * <p>Note that you <em>cannot</em> always tell if
208     * an attempt to <tt>add</tt> an element will succeed by
209     * inspecting <tt>remainingCapacity</tt> because it may be the
210     * case that a waiting consumer is ready to <tt>take</tt> an
211     * element out of an otherwise full queue.
212     */
213 dl 1.2 public int remainingCapacity() {
214     return capacity - count.get();
215     }
216    
217 dholmes 1.22 /**
218     * Adds the specified element to the tail of this queue, waiting if
219     * necessary for space to become available.
220     * @throws NullPointerException if the specified element is <tt>null</tt>.
221     */
222 dholmes 1.14 public void put(E o) throws InterruptedException {
223     if (o == null) throw new NullPointerException();
224 dl 1.2 // Note: convention in all put/take/etc is to preset
225     // local var holding count negative to indicate failure unless set.
226 tim 1.12 int c = -1;
227 dl 1.2 putLock.lockInterruptibly();
228     try {
229     /*
230     * Note that count is used in wait guard even though it is
231     * not protected by lock. This works because count can
232     * only decrease at this point (all other puts are shut
233     * out by lock), and we (or some other waiting put) are
234     * signalled if it ever changes from
235     * capacity. Similarly for all other uses of count in
236     * other wait guards.
237     */
238     try {
239 tim 1.12 while (count.get() == capacity)
240 dl 1.2 notFull.await();
241 tim 1.17 } catch (InterruptedException ie) {
242 dl 1.2 notFull.signal(); // propagate to a non-interrupted thread
243     throw ie;
244     }
245 dholmes 1.14 insert(o);
246 dl 1.2 c = count.getAndIncrement();
247 dl 1.6 if (c + 1 < capacity)
248 dl 1.2 notFull.signal();
249 tim 1.17 } finally {
250 dl 1.2 putLock.unlock();
251     }
252 tim 1.12 if (c == 0)
253 dl 1.2 signalNotEmpty();
254 tim 1.1 }
255 dl 1.2
256 dholmes 1.22 /**
257     * Inserts the specified element at the tail of this queue, waiting if
258     * necessary up to the specified wait time for space to become available.
259     * @throws NullPointerException if the specified element is <tt>null</tt>.
260     */
261 dholmes 1.14 public boolean offer(E o, long timeout, TimeUnit unit)
262 dholmes 1.8 throws InterruptedException {
263 tim 1.12
264 dholmes 1.14 if (o == null) throw new NullPointerException();
265 dl 1.2 long nanos = unit.toNanos(timeout);
266     int c = -1;
267 dholmes 1.8 putLock.lockInterruptibly();
268 dl 1.2 try {
269     for (;;) {
270     if (count.get() < capacity) {
271 dholmes 1.14 insert(o);
272 dl 1.2 c = count.getAndIncrement();
273 dl 1.6 if (c + 1 < capacity)
274 dl 1.2 notFull.signal();
275     break;
276     }
277     if (nanos <= 0)
278     return false;
279     try {
280     nanos = notFull.awaitNanos(nanos);
281 tim 1.17 } catch (InterruptedException ie) {
282 dl 1.2 notFull.signal(); // propagate to a non-interrupted thread
283     throw ie;
284     }
285     }
286 tim 1.17 } finally {
287 dl 1.2 putLock.unlock();
288     }
289 tim 1.12 if (c == 0)
290 dl 1.2 signalNotEmpty();
291     return true;
292 tim 1.1 }
293 dl 1.2
294 tim 1.12 /**
295 dholmes 1.22 * Inserts the specified element at the tail of this queue if possible,
296 dholmes 1.8 * returning immediately if this queue is full.
297     *
298 dl 1.20 * @throws NullPointerException if the specified element is <tt>null</tt>
299 dholmes 1.8 */
300 dholmes 1.14 public boolean offer(E o) {
301     if (o == null) throw new NullPointerException();
302 dl 1.2 if (count.get() == capacity)
303     return false;
304 tim 1.12 int c = -1;
305 dholmes 1.8 putLock.lock();
306 dl 1.2 try {
307     if (count.get() < capacity) {
308 dholmes 1.14 insert(o);
309 dl 1.2 c = count.getAndIncrement();
310 dl 1.6 if (c + 1 < capacity)
311 dl 1.2 notFull.signal();
312     }
313 tim 1.17 } finally {
314 dl 1.2 putLock.unlock();
315     }
316 tim 1.12 if (c == 0)
317 dl 1.2 signalNotEmpty();
318     return c >= 0;
319 tim 1.1 }
320 dl 1.2
321    
322     public E take() throws InterruptedException {
323     E x;
324     int c = -1;
325     takeLock.lockInterruptibly();
326     try {
327     try {
328 tim 1.12 while (count.get() == 0)
329 dl 1.2 notEmpty.await();
330 tim 1.17 } catch (InterruptedException ie) {
331 dl 1.2 notEmpty.signal(); // propagate to a non-interrupted thread
332     throw ie;
333     }
334    
335     x = extract();
336     c = count.getAndDecrement();
337     if (c > 1)
338     notEmpty.signal();
339 tim 1.17 } finally {
340 dl 1.2 takeLock.unlock();
341     }
342 tim 1.12 if (c == capacity)
343 dl 1.2 signalNotFull();
344     return x;
345     }
346    
347     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
348     E x = null;
349     int c = -1;
350 dholmes 1.8 long nanos = unit.toNanos(timeout);
351 dl 1.2 takeLock.lockInterruptibly();
352     try {
353     for (;;) {
354     if (count.get() > 0) {
355     x = extract();
356     c = count.getAndDecrement();
357     if (c > 1)
358     notEmpty.signal();
359     break;
360     }
361     if (nanos <= 0)
362     return null;
363     try {
364     nanos = notEmpty.awaitNanos(nanos);
365 tim 1.17 } catch (InterruptedException ie) {
366 dl 1.2 notEmpty.signal(); // propagate to a non-interrupted thread
367     throw ie;
368     }
369     }
370 tim 1.17 } finally {
371 dl 1.2 takeLock.unlock();
372     }
373 tim 1.12 if (c == capacity)
374 dl 1.2 signalNotFull();
375     return x;
376     }
377    
378     public E poll() {
379     if (count.get() == 0)
380     return null;
381     E x = null;
382 tim 1.12 int c = -1;
383 dl 1.2 takeLock.tryLock();
384     try {
385     if (count.get() > 0) {
386     x = extract();
387     c = count.getAndDecrement();
388     if (c > 1)
389     notEmpty.signal();
390     }
391 tim 1.17 } finally {
392 dl 1.2 takeLock.unlock();
393     }
394 tim 1.12 if (c == capacity)
395 dl 1.2 signalNotFull();
396     return x;
397 tim 1.1 }
398 dl 1.2
399    
400     public E peek() {
401     if (count.get() == 0)
402     return null;
403 dholmes 1.8 takeLock.lock();
404 dl 1.2 try {
405     Node<E> first = head.next;
406     if (first == null)
407     return null;
408     else
409     return first.item;
410 tim 1.17 } finally {
411 dl 1.2 takeLock.unlock();
412     }
413 tim 1.1 }
414    
415 dholmes 1.9 public boolean remove(Object o) {
416     if (o == null) return false;
417 dl 1.2 boolean removed = false;
418     fullyLock();
419     try {
420     Node<E> trail = head;
421     Node<E> p = head.next;
422     while (p != null) {
423 dholmes 1.9 if (o.equals(p.item)) {
424 dl 1.2 removed = true;
425     break;
426     }
427     trail = p;
428     p = p.next;
429     }
430     if (removed) {
431     p.item = null;
432     trail.next = p.next;
433     if (count.getAndDecrement() == capacity)
434     notFull.signalAll();
435     }
436 tim 1.17 } finally {
437 dl 1.2 fullyUnlock();
438     }
439     return removed;
440 tim 1.1 }
441 dl 1.2
442     public Object[] toArray() {
443     fullyLock();
444     try {
445     int size = count.get();
446 tim 1.12 Object[] a = new Object[size];
447 dl 1.2 int k = 0;
448 tim 1.12 for (Node<E> p = head.next; p != null; p = p.next)
449 dl 1.2 a[k++] = p.item;
450     return a;
451 tim 1.17 } finally {
452 dl 1.2 fullyUnlock();
453     }
454 tim 1.1 }
455 dl 1.2
456     public <T> T[] toArray(T[] a) {
457     fullyLock();
458     try {
459     int size = count.get();
460     if (a.length < size)
461 dl 1.4 a = (T[])java.lang.reflect.Array.newInstance
462     (a.getClass().getComponentType(), size);
463 tim 1.12
464 dl 1.2 int k = 0;
465 tim 1.12 for (Node p = head.next; p != null; p = p.next)
466 dl 1.2 a[k++] = (T)p.item;
467     return a;
468 tim 1.17 } finally {
469 dl 1.2 fullyUnlock();
470     }
471 tim 1.1 }
472 dl 1.2
473     public String toString() {
474     fullyLock();
475     try {
476     return super.toString();
477 tim 1.17 } finally {
478 dl 1.2 fullyUnlock();
479     }
480 tim 1.1 }
481 dl 1.2
482 dholmes 1.14 /**
483     * Returns an iterator over the elements in this queue in proper sequence.
484 dl 1.15 * The returned <tt>Iterator</tt> is a "weakly consistent" iterator that
485     * will never throw {@link java.util.ConcurrentModificationException},
486     * and guarantees to traverse elements as they existed upon
487     * construction of the iterator, and may (but is not guaranteed to)
488     * reflect any modifications subsequent to construction.
489 dholmes 1.14 *
490     * @return an iterator over the elements in this queue in proper sequence.
491     */
492 dl 1.2 public Iterator<E> iterator() {
493     return new Itr();
494 tim 1.1 }
495 dl 1.2
496     private class Itr implements Iterator<E> {
497 tim 1.12 /*
498 dl 1.4 * Basic weak-consistent iterator. At all times hold the next
499     * item to hand out so that if hasNext() reports true, we will
500     * still have it to return even if lost race with a take etc.
501     */
502 dl 1.2 Node<E> current;
503     Node<E> lastRet;
504 dl 1.4 E currentElement;
505 tim 1.12
506 dl 1.2 Itr() {
507     fullyLock();
508     try {
509     current = head.next;
510 dl 1.4 if (current != null)
511     currentElement = current.item;
512 tim 1.17 } finally {
513 dl 1.2 fullyUnlock();
514     }
515     }
516 tim 1.12
517     public boolean hasNext() {
518 dl 1.2 return current != null;
519     }
520    
521 tim 1.12 public E next() {
522 dl 1.2 fullyLock();
523     try {
524     if (current == null)
525     throw new NoSuchElementException();
526 dl 1.4 E x = currentElement;
527 dl 1.2 lastRet = current;
528     current = current.next;
529 dl 1.4 if (current != null)
530     currentElement = current.item;
531 dl 1.2 return x;
532 tim 1.17 } finally {
533 dl 1.2 fullyUnlock();
534     }
535 tim 1.12
536 dl 1.2 }
537    
538 tim 1.12 public void remove() {
539 dl 1.2 if (lastRet == null)
540 tim 1.12 throw new IllegalStateException();
541 dl 1.2 fullyLock();
542     try {
543     Node<E> node = lastRet;
544     lastRet = null;
545     Node<E> trail = head;
546     Node<E> p = head.next;
547     while (p != null && p != node) {
548     trail = p;
549     p = p.next;
550     }
551     if (p == node) {
552     p.item = null;
553     trail.next = p.next;
554     int c = count.getAndDecrement();
555     if (c == capacity)
556     notFull.signalAll();
557     }
558 tim 1.17 } finally {
559 dl 1.2 fullyUnlock();
560     }
561     }
562 tim 1.1 }
563 dl 1.2
564     /**
565     * Save the state to a stream (that is, serialize it).
566     *
567     * @serialData The capacity is emitted (int), followed by all of
568     * its elements (each an <tt>Object</tt>) in the proper order,
569     * followed by a null
570 dl 1.6 * @param s the stream
571 dl 1.2 */
572     private void writeObject(java.io.ObjectOutputStream s)
573     throws java.io.IOException {
574    
575 tim 1.12 fullyLock();
576 dl 1.2 try {
577     // Write out any hidden stuff, plus capacity
578     s.defaultWriteObject();
579    
580     // Write out all elements in the proper order.
581 tim 1.12 for (Node<E> p = head.next; p != null; p = p.next)
582 dl 1.2 s.writeObject(p.item);
583    
584     // Use trailing null as sentinel
585     s.writeObject(null);
586 tim 1.17 } finally {
587 dl 1.2 fullyUnlock();
588     }
589 tim 1.1 }
590    
591 dl 1.2 /**
592 dholmes 1.8 * Reconstitute this queue instance from a stream (that is,
593 dl 1.2 * deserialize it).
594 dl 1.6 * @param s the stream
595 dl 1.2 */
596     private void readObject(java.io.ObjectInputStream s)
597     throws java.io.IOException, ClassNotFoundException {
598 tim 1.12 // Read in capacity, and any hidden stuff
599     s.defaultReadObject();
600 dl 1.2
601 dl 1.19 count.set(0);
602     last = head = new Node<E>(null);
603    
604 dl 1.6 // Read in all elements and place in queue
605 dl 1.2 for (;;) {
606     E item = (E)s.readObject();
607     if (item == null)
608     break;
609     add(item);
610     }
611 tim 1.1 }
612     }