ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/LinkedTransferQueue.java
Revision: 1.40
Committed: Sat Aug 1 20:26:50 2009 UTC (14 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.39: +23 -11 lines
Log Message:
yet another rewrite of transfer method specs

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/licenses/publicdomain
5     */
6    
7     package jsr166y;
8 jsr166 1.26
9 dl 1.1 import java.util.concurrent.*;
10 jsr166 1.26
11     import java.util.AbstractQueue;
12     import java.util.Collection;
13 jsr166 1.35 import java.util.ConcurrentModificationException;
14 jsr166 1.26 import java.util.Iterator;
15     import java.util.NoSuchElementException;
16 jsr166 1.35 import java.util.Queue;
17 jsr166 1.26 import java.util.concurrent.locks.LockSupport;
18     import java.util.concurrent.atomic.AtomicReference;
19 dl 1.1
20     /**
21     * An unbounded {@linkplain TransferQueue} based on linked nodes.
22     * This queue orders elements FIFO (first-in-first-out) with respect
23     * to any given producer. The <em>head</em> of the queue is that
24     * element that has been on the queue the longest time for some
25     * producer. The <em>tail</em> of the queue is that element that has
26     * been on the queue the shortest time for some producer.
27     *
28 jsr166 1.11 * <p>Beware that, unlike in most collections, the {@code size}
29 dl 1.1 * method is <em>NOT</em> a constant-time operation. Because of the
30     * asynchronous nature of these queues, determining the current number
31     * of elements requires a traversal of the elements.
32     *
33     * <p>This class and its iterator implement all of the
34     * <em>optional</em> methods of the {@link Collection} and {@link
35     * Iterator} interfaces.
36     *
37     * <p>Memory consistency effects: As with other concurrent
38     * collections, actions in a thread prior to placing an object into a
39     * {@code LinkedTransferQueue}
40     * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
41     * actions subsequent to the access or removal of that element from
42     * the {@code LinkedTransferQueue} in another thread.
43     *
44     * <p>This class is a member of the
45     * <a href="{@docRoot}/../technotes/guides/collections/index.html">
46     * Java Collections Framework</a>.
47     *
48 dl 1.3 * @since 1.7
49 dl 1.1 * @author Doug Lea
50     * @param <E> the type of elements held in this collection
51     */
52     public class LinkedTransferQueue<E> extends AbstractQueue<E>
53     implements TransferQueue<E>, java.io.Serializable {
54     private static final long serialVersionUID = -3223113410248163686L;
55    
56     /*
57     * This class extends the approach used in FIFO-mode
58     * SynchronousQueues. See the internal documentation, as well as
59     * the PPoPP 2006 paper "Scalable Synchronous Queues" by Scherer,
60     * Lea & Scott
61     * (http://www.cs.rice.edu/~wns1/papers/2006-PPoPP-SQ.pdf)
62     *
63 dl 1.9 * The main extension is to provide different Wait modes for the
64     * main "xfer" method that puts or takes items. These don't
65     * impact the basic dual-queue logic, but instead control whether
66     * or how threads block upon insertion of request or data nodes
67     * into the dual queue. It also uses slightly different
68     * conventions for tracking whether nodes are off-list or
69     * cancelled.
70 dl 1.1 */
71    
72     // Wait modes for xfer method
73     static final int NOWAIT = 0;
74     static final int TIMEOUT = 1;
75     static final int WAIT = 2;
76    
77     /** The number of CPUs, for spin control */
78     static final int NCPUS = Runtime.getRuntime().availableProcessors();
79    
80     /**
81     * The number of times to spin before blocking in timed waits.
82     * The value is empirically derived -- it works well across a
83     * variety of processors and OSes. Empirically, the best value
84     * seems not to vary with number of CPUs (beyond 2) so is just
85     * a constant.
86     */
87 jsr166 1.22 static final int maxTimedSpins = (NCPUS < 2) ? 0 : 32;
88 dl 1.1
89     /**
90     * The number of times to spin before blocking in untimed waits.
91     * This is greater than timed value because untimed waits spin
92     * faster since they don't need to check times on each spin.
93     */
94     static final int maxUntimedSpins = maxTimedSpins * 16;
95    
96     /**
97     * The number of nanoseconds for which it is faster to spin
98     * rather than to use timed park. A rough estimate suffices.
99     */
100     static final long spinForTimeoutThreshold = 1000L;
101    
102 jsr166 1.5 /**
103 dl 1.9 * Node class for LinkedTransferQueue. Opportunistically
104     * subclasses from AtomicReference to represent item. Uses Object,
105     * not E, to allow setting item to "this" after use, to avoid
106     * garbage retention. Similarly, setting the next field to this is
107     * used as sentinel that node is off list.
108 dl 1.1 */
109 jsr166 1.25 static final class Node<E> extends AtomicReference<Object> {
110     volatile Node<E> next;
111 dl 1.1 volatile Thread waiter; // to control park/unpark
112     final boolean isData;
113 jsr166 1.25
114     Node(E item, boolean isData) {
115 dl 1.1 super(item);
116     this.isData = isData;
117     }
118    
119 jsr166 1.32 // Unsafe mechanics
120    
121     private static final sun.misc.Unsafe UNSAFE = getUnsafe();
122     private static final long nextOffset =
123     objectFieldOffset(UNSAFE, "next", Node.class);
124    
125 jsr166 1.25 final boolean casNext(Node<E> cmp, Node<E> val) {
126 jsr166 1.31 return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);
127 dl 1.1 }
128 dl 1.15
129     final void clearNext() {
130 jsr166 1.31 UNSAFE.putOrderedObject(this, nextOffset, this);
131     }
132    
133     /**
134     * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
135     * Replace with a simple call to Unsafe.getUnsafe when integrating
136     * into a jdk.
137     *
138     * @return a sun.misc.Unsafe
139     */
140     private static sun.misc.Unsafe getUnsafe() {
141     try {
142     return sun.misc.Unsafe.getUnsafe();
143     } catch (SecurityException se) {
144     try {
145     return java.security.AccessController.doPrivileged
146     (new java.security
147     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
148     public sun.misc.Unsafe run() throws Exception {
149     java.lang.reflect.Field f = sun.misc
150     .Unsafe.class.getDeclaredField("theUnsafe");
151     f.setAccessible(true);
152     return (sun.misc.Unsafe) f.get(null);
153     }});
154     } catch (java.security.PrivilegedActionException e) {
155     throw new RuntimeException("Could not initialize intrinsics",
156     e.getCause());
157     }
158     }
159 dl 1.15 }
160    
161 jsr166 1.24 private static final long serialVersionUID = -3375979862319811754L;
162 dl 1.1 }
163    
164     /**
165     * Padded version of AtomicReference used for head, tail and
166     * cleanMe, to alleviate contention across threads CASing one vs
167     * the other.
168     */
169     static final class PaddedAtomicReference<T> extends AtomicReference<T> {
170     // enough padding for 64bytes with 4byte refs
171     Object p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe;
172     PaddedAtomicReference(T r) { super(r); }
173 jsr166 1.24 private static final long serialVersionUID = 8170090609809740854L;
174 dl 1.1 }
175    
176    
177 dl 1.7 /** head of the queue */
178 jsr166 1.25 private transient final PaddedAtomicReference<Node<E>> head;
179 jsr166 1.23
180 dl 1.7 /** tail of the queue */
181 jsr166 1.25 private transient final PaddedAtomicReference<Node<E>> tail;
182 dl 1.1
183     /**
184     * Reference to a cancelled node that might not yet have been
185     * unlinked from queue because it was the last inserted node
186     * when it cancelled.
187     */
188 jsr166 1.25 private transient final PaddedAtomicReference<Node<E>> cleanMe;
189 dl 1.1
190     /**
191     * Tries to cas nh as new head; if successful, unlink
192     * old head's next node to avoid garbage retention.
193     */
194 jsr166 1.25 private boolean advanceHead(Node<E> h, Node<E> nh) {
195 dl 1.1 if (h == head.get() && head.compareAndSet(h, nh)) {
196 dl 1.15 h.clearNext(); // forget old next
197 dl 1.1 return true;
198     }
199     return false;
200     }
201 jsr166 1.5
202 dl 1.1 /**
203     * Puts or takes an item. Used for most queue operations (except
204 dl 1.9 * poll() and tryTransfer()). See the similar code in
205     * SynchronousQueue for detailed explanation.
206 jsr166 1.17 *
207 jsr166 1.4 * @param e the item or if null, signifies that this is a take
208 dl 1.1 * @param mode the wait mode: NOWAIT, TIMEOUT, WAIT
209     * @param nanos timeout in nanosecs, used only if mode is TIMEOUT
210     * @return an item, or null on failure
211     */
212 jsr166 1.25 private E xfer(E e, int mode, long nanos) {
213 dl 1.1 boolean isData = (e != null);
214 jsr166 1.25 Node<E> s = null;
215     final PaddedAtomicReference<Node<E>> head = this.head;
216     final PaddedAtomicReference<Node<E>> tail = this.tail;
217 dl 1.1
218     for (;;) {
219 jsr166 1.25 Node<E> t = tail.get();
220     Node<E> h = head.get();
221 dl 1.1
222     if (t != null && (t == h || t.isData == isData)) {
223     if (s == null)
224 jsr166 1.25 s = new Node<E>(e, isData);
225     Node<E> last = t.next;
226 dl 1.1 if (last != null) {
227     if (t == tail.get())
228     tail.compareAndSet(t, last);
229     }
230     else if (t.casNext(null, s)) {
231     tail.compareAndSet(t, s);
232     return awaitFulfill(t, s, e, mode, nanos);
233     }
234     }
235 jsr166 1.5
236 dl 1.1 else if (h != null) {
237 jsr166 1.25 Node<E> first = h.next;
238 jsr166 1.5 if (t == tail.get() && first != null &&
239 dl 1.1 advanceHead(h, first)) {
240     Object x = first.get();
241     if (x != first && first.compareAndSet(x, e)) {
242     LockSupport.unpark(first.waiter);
243 jsr166 1.25 return isData ? e : (E) x;
244 dl 1.1 }
245     }
246     }
247     }
248     }
249    
250    
251     /**
252     * Version of xfer for poll() and tryTransfer, which
253 jsr166 1.17 * simplifies control paths both here and in xfer.
254 dl 1.1 */
255 jsr166 1.25 private E fulfill(E e) {
256 dl 1.1 boolean isData = (e != null);
257 jsr166 1.25 final PaddedAtomicReference<Node<E>> head = this.head;
258     final PaddedAtomicReference<Node<E>> tail = this.tail;
259 dl 1.1
260     for (;;) {
261 jsr166 1.25 Node<E> t = tail.get();
262     Node<E> h = head.get();
263 dl 1.1
264     if (t != null && (t == h || t.isData == isData)) {
265 jsr166 1.25 Node<E> last = t.next;
266 dl 1.1 if (t == tail.get()) {
267     if (last != null)
268     tail.compareAndSet(t, last);
269     else
270     return null;
271     }
272     }
273     else if (h != null) {
274 jsr166 1.25 Node<E> first = h.next;
275 jsr166 1.5 if (t == tail.get() &&
276 dl 1.1 first != null &&
277     advanceHead(h, first)) {
278     Object x = first.get();
279     if (x != first && first.compareAndSet(x, e)) {
280     LockSupport.unpark(first.waiter);
281 jsr166 1.25 return isData ? e : (E) x;
282 dl 1.1 }
283     }
284     }
285     }
286     }
287    
288     /**
289     * Spins/blocks until node s is fulfilled or caller gives up,
290     * depending on wait mode.
291     *
292     * @param pred the predecessor of waiting node
293     * @param s the waiting node
294     * @param e the comparison value for checking match
295     * @param mode mode
296     * @param nanos timeout value
297 jsr166 1.39 * @return matched item, or null if cancelled
298 dl 1.1 */
299 jsr166 1.25 private E awaitFulfill(Node<E> pred, Node<E> s, E e,
300     int mode, long nanos) {
301 dl 1.1 if (mode == NOWAIT)
302     return null;
303    
304 jsr166 1.22 long lastTime = (mode == TIMEOUT) ? System.nanoTime() : 0;
305 dl 1.1 Thread w = Thread.currentThread();
306     int spins = -1; // set to desired spin count below
307     for (;;) {
308     if (w.isInterrupted())
309     s.compareAndSet(e, s);
310     Object x = s.get();
311     if (x != e) { // Node was matched or cancelled
312     advanceHead(pred, s); // unlink if head
313 jsr166 1.17 if (x == s) { // was cancelled
314 dl 1.9 clean(pred, s);
315     return null;
316     }
317 jsr166 1.5 else if (x != null) {
318 dl 1.1 s.set(s); // avoid garbage retention
319 jsr166 1.25 return (E) x;
320 dl 1.1 }
321     else
322     return e;
323     }
324     if (mode == TIMEOUT) {
325     long now = System.nanoTime();
326     nanos -= now - lastTime;
327     lastTime = now;
328     if (nanos <= 0) {
329     s.compareAndSet(e, s); // try to cancel
330     continue;
331     }
332     }
333     if (spins < 0) {
334 jsr166 1.25 Node<E> h = head.get(); // only spin if at head
335 dl 1.1 spins = ((h != null && h.next == s) ?
336 jsr166 1.22 ((mode == TIMEOUT) ?
337 dl 1.1 maxTimedSpins : maxUntimedSpins) : 0);
338     }
339     if (spins > 0)
340     --spins;
341     else if (s.waiter == null)
342     s.waiter = w;
343     else if (mode != TIMEOUT) {
344 dl 1.12 LockSupport.park(this);
345 dl 1.1 s.waiter = null;
346     spins = -1;
347     }
348     else if (nanos > spinForTimeoutThreshold) {
349 dl 1.12 LockSupport.parkNanos(this, nanos);
350 dl 1.1 s.waiter = null;
351     spins = -1;
352     }
353     }
354     }
355    
356     /**
357 jsr166 1.17 * Returns validated tail for use in cleaning methods.
358 dl 1.9 */
359 jsr166 1.25 private Node<E> getValidatedTail() {
360 dl 1.9 for (;;) {
361 jsr166 1.25 Node<E> h = head.get();
362     Node<E> first = h.next;
363 jsr166 1.39 if (first != null && first.get() == first) { // help advance
364 dl 1.9 advanceHead(h, first);
365     continue;
366     }
367 jsr166 1.25 Node<E> t = tail.get();
368     Node<E> last = t.next;
369 dl 1.9 if (t == tail.get()) {
370     if (last != null)
371     tail.compareAndSet(t, last); // help advance
372     else
373     return t;
374     }
375     }
376 jsr166 1.10 }
377 dl 1.9
378     /**
379 dl 1.1 * Gets rid of cancelled node s with original predecessor pred.
380 jsr166 1.17 *
381 dl 1.9 * @param pred predecessor of cancelled node
382     * @param s the cancelled node
383 dl 1.1 */
384 jsr166 1.25 private void clean(Node<E> pred, Node<E> s) {
385 dl 1.1 Thread w = s.waiter;
386     if (w != null) { // Wake up thread
387     s.waiter = null;
388     if (w != Thread.currentThread())
389     LockSupport.unpark(w);
390     }
391 dl 1.15
392     if (pred == null)
393     return;
394    
395 dl 1.9 /*
396     * At any given time, exactly one node on list cannot be
397     * deleted -- the last inserted node. To accommodate this, if
398     * we cannot delete s, we save its predecessor as "cleanMe",
399     * processing the previously saved version first. At least one
400     * of node s or the node previously saved can always be
401     * processed, so this always terminates.
402     */
403     while (pred.next == s) {
404 jsr166 1.25 Node<E> oldpred = reclean(); // First, help get rid of cleanMe
405     Node<E> t = getValidatedTail();
406 dl 1.9 if (s != t) { // If not tail, try to unsplice
407 jsr166 1.25 Node<E> sn = s.next; // s.next == s means s already off list
408 jsr166 1.10 if (sn == s || pred.casNext(s, sn))
409 dl 1.9 break;
410     }
411     else if (oldpred == pred || // Already saved
412     (oldpred == null && cleanMe.compareAndSet(null, pred)))
413     break; // Postpone cleaning
414     }
415     }
416 jsr166 1.5
417 dl 1.9 /**
418     * Tries to unsplice the cancelled node held in cleanMe that was
419     * previously uncleanable because it was at tail.
420 jsr166 1.17 *
421 dl 1.9 * @return current cleanMe node (or null)
422     */
423 jsr166 1.25 private Node<E> reclean() {
424 jsr166 1.10 /*
425 dl 1.9 * cleanMe is, or at one time was, predecessor of cancelled
426     * node s that was the tail so could not be unspliced. If s
427     * is no longer the tail, try to unsplice if necessary and
428     * make cleanMe slot available. This differs from similar
429     * code in clean() because we must check that pred still
430     * points to a cancelled node that must be unspliced -- if
431     * not, we can (must) clear cleanMe without unsplicing.
432     * This can loop only due to contention on casNext or
433 jsr166 1.10 * clearing cleanMe.
434 dl 1.9 */
435 jsr166 1.25 Node<E> pred;
436 dl 1.9 while ((pred = cleanMe.get()) != null) {
437 jsr166 1.25 Node<E> t = getValidatedTail();
438     Node<E> s = pred.next;
439 jsr166 1.10 if (s != t) {
440 jsr166 1.25 Node<E> sn;
441 dl 1.9 if (s == null || s == pred || s.get() != s ||
442     (sn = s.next) == s || pred.casNext(s, sn))
443     cleanMe.compareAndSet(pred, null);
444 dl 1.1 }
445 dl 1.9 else // s is still tail; cannot clean
446     break;
447 dl 1.1 }
448 dl 1.9 return pred;
449 dl 1.1 }
450 jsr166 1.5
451 dl 1.1 /**
452 jsr166 1.11 * Creates an initially empty {@code LinkedTransferQueue}.
453 dl 1.1 */
454     public LinkedTransferQueue() {
455 jsr166 1.25 Node<E> dummy = new Node<E>(null, false);
456     head = new PaddedAtomicReference<Node<E>>(dummy);
457     tail = new PaddedAtomicReference<Node<E>>(dummy);
458     cleanMe = new PaddedAtomicReference<Node<E>>(null);
459 dl 1.1 }
460    
461     /**
462 jsr166 1.11 * Creates a {@code LinkedTransferQueue}
463 dl 1.1 * initially containing the elements of the given collection,
464     * added in traversal order of the collection's iterator.
465 jsr166 1.17 *
466 dl 1.1 * @param c the collection of elements to initially contain
467     * @throws NullPointerException if the specified collection or any
468     * of its elements are null
469     */
470     public LinkedTransferQueue(Collection<? extends E> c) {
471 dl 1.7 this();
472 dl 1.1 addAll(c);
473     }
474    
475 jsr166 1.29 /**
476 jsr166 1.35 * Inserts the specified element at the tail of this queue.
477     * As the queue is unbounded, this method will never block.
478     *
479     * @throws NullPointerException if the specified element is null
480 jsr166 1.29 */
481 jsr166 1.35 public void put(E e) {
482     offer(e);
483 dl 1.1 }
484    
485 jsr166 1.29 /**
486 jsr166 1.35 * Inserts the specified element at the tail of this queue.
487     * As the queue is unbounded, this method will never block or
488     * return {@code false}.
489     *
490     * @return {@code true} (as specified by
491     * {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer})
492     * @throws NullPointerException if the specified element is null
493 jsr166 1.29 */
494 jsr166 1.35 public boolean offer(E e, long timeout, TimeUnit unit) {
495     return offer(e);
496 dl 1.1 }
497    
498 jsr166 1.29 /**
499 jsr166 1.35 * Inserts the specified element at the tail of this queue.
500     * As the queue is unbounded, this method will never return {@code false}.
501     *
502     * @return {@code true} (as specified by
503     * {@link BlockingQueue#offer(Object) BlockingQueue.offer})
504     * @throws NullPointerException if the specified element is null
505 jsr166 1.29 */
506 dl 1.1 public boolean offer(E e) {
507     if (e == null) throw new NullPointerException();
508     xfer(e, NOWAIT, 0);
509     return true;
510     }
511    
512 jsr166 1.29 /**
513 jsr166 1.35 * Inserts the specified element at the tail of this queue.
514 jsr166 1.37 * As the queue is unbounded, this method will never throw
515 jsr166 1.35 * {@link IllegalStateException} or return {@code false}.
516     *
517     * @return {@code true} (as specified by {@link Collection#add})
518     * @throws NullPointerException if the specified element is null
519 jsr166 1.29 */
520 dl 1.15 public boolean add(E e) {
521 jsr166 1.35 return offer(e);
522     }
523    
524     /**
525 jsr166 1.40 * Transfers the element to a waiting consumer immediately, if possible.
526     *
527     * <p>More precisely, transfers the specified element immediately
528     * if there exists a consumer already waiting to receive it (in
529     * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
530     * otherwise returning {@code false} without enqueuing the element.
531 jsr166 1.35 *
532     * @throws NullPointerException if the specified element is null
533     */
534     public boolean tryTransfer(E e) {
535 dl 1.15 if (e == null) throw new NullPointerException();
536 jsr166 1.35 return fulfill(e) != null;
537 dl 1.15 }
538    
539 jsr166 1.29 /**
540 jsr166 1.40 * Transfers the element to a consumer, waiting if necessary to do so.
541     *
542     * <p>More precisely, transfers the specified element immediately
543     * if there exists a consumer already waiting to receive it (in
544     * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
545     * else inserts the specified element at the tail of this queue
546     * and waits until the element is received by a consumer.
547 jsr166 1.35 *
548     * @throws NullPointerException if the specified element is null
549 jsr166 1.29 */
550 dl 1.1 public void transfer(E e) throws InterruptedException {
551     if (e == null) throw new NullPointerException();
552     if (xfer(e, WAIT, 0) == null) {
553 jsr166 1.6 Thread.interrupted();
554 dl 1.1 throw new InterruptedException();
555 jsr166 1.6 }
556 dl 1.1 }
557    
558 jsr166 1.29 /**
559 jsr166 1.40 * Transfers the element to a consumer if it is possible to do so
560     * before the timeout elapses.
561     *
562     * <p>More precisely, transfers the specified element immediately
563     * if there exists a consumer already waiting to receive it (in
564     * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
565     * else inserts the specified element at the tail of this queue
566     * and waits until the element is received by a consumer,
567     * returning {@code false} if the specified wait time elapses
568     * before the element can be transferred.
569 jsr166 1.35 *
570     * @throws NullPointerException if the specified element is null
571 jsr166 1.29 */
572 dl 1.1 public boolean tryTransfer(E e, long timeout, TimeUnit unit)
573     throws InterruptedException {
574     if (e == null) throw new NullPointerException();
575     if (xfer(e, TIMEOUT, unit.toNanos(timeout)) != null)
576     return true;
577     if (!Thread.interrupted())
578     return false;
579     throw new InterruptedException();
580     }
581    
582     public E take() throws InterruptedException {
583 jsr166 1.34 E e = xfer(null, WAIT, 0);
584 dl 1.1 if (e != null)
585 jsr166 1.34 return e;
586 jsr166 1.6 Thread.interrupted();
587 dl 1.1 throw new InterruptedException();
588     }
589    
590     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
591 jsr166 1.34 E e = xfer(null, TIMEOUT, unit.toNanos(timeout));
592 dl 1.1 if (e != null || !Thread.interrupted())
593 jsr166 1.34 return e;
594 dl 1.1 throw new InterruptedException();
595     }
596    
597     public E poll() {
598 jsr166 1.25 return fulfill(null);
599 dl 1.1 }
600    
601 jsr166 1.29 /**
602 jsr166 1.30 * @throws NullPointerException {@inheritDoc}
603     * @throws IllegalArgumentException {@inheritDoc}
604 jsr166 1.29 */
605 dl 1.1 public int drainTo(Collection<? super E> c) {
606     if (c == null)
607     throw new NullPointerException();
608     if (c == this)
609     throw new IllegalArgumentException();
610     int n = 0;
611     E e;
612     while ( (e = poll()) != null) {
613     c.add(e);
614     ++n;
615     }
616     return n;
617     }
618    
619 jsr166 1.29 /**
620 jsr166 1.30 * @throws NullPointerException {@inheritDoc}
621     * @throws IllegalArgumentException {@inheritDoc}
622 jsr166 1.29 */
623 dl 1.1 public int drainTo(Collection<? super E> c, int maxElements) {
624     if (c == null)
625     throw new NullPointerException();
626     if (c == this)
627     throw new IllegalArgumentException();
628     int n = 0;
629     E e;
630     while (n < maxElements && (e = poll()) != null) {
631     c.add(e);
632     ++n;
633     }
634     return n;
635     }
636    
637     // Traversal-based methods
638    
639     /**
640 jsr166 1.17 * Returns head after performing any outstanding helping steps.
641 dl 1.1 */
642 jsr166 1.25 private Node<E> traversalHead() {
643 dl 1.1 for (;;) {
644 jsr166 1.25 Node<E> t = tail.get();
645     Node<E> h = head.get();
646 dl 1.1 if (h != null && t != null) {
647 jsr166 1.25 Node<E> last = t.next;
648     Node<E> first = h.next;
649 dl 1.1 if (t == tail.get()) {
650 jsr166 1.5 if (last != null)
651 dl 1.1 tail.compareAndSet(t, last);
652     else if (first != null) {
653     Object x = first.get();
654 jsr166 1.5 if (x == first)
655     advanceHead(h, first);
656 dl 1.1 else
657     return h;
658     }
659     else
660     return h;
661     }
662     }
663 dl 1.15 reclean();
664 dl 1.1 }
665     }
666    
667 jsr166 1.35 /**
668     * Returns an iterator over the elements in this queue in proper
669     * sequence, from head to tail.
670     *
671     * <p>The returned iterator is a "weakly consistent" iterator that
672     * will never throw
673     * {@link ConcurrentModificationException ConcurrentModificationException},
674     * and guarantees to traverse elements as they existed upon
675     * construction of the iterator, and may (but is not guaranteed
676     * to) reflect any modifications subsequent to construction.
677     *
678     * @return an iterator over the elements in this queue in proper sequence
679     */
680 dl 1.1 public Iterator<E> iterator() {
681     return new Itr();
682     }
683    
684     /**
685 jsr166 1.4 * Iterators. Basic strategy is to traverse list, treating
686 dl 1.1 * non-data (i.e., request) nodes as terminating list.
687     * Once a valid data node is found, the item is cached
688     * so that the next call to next() will return it even
689     * if subsequently removed.
690     */
691     class Itr implements Iterator<E> {
692 jsr166 1.25 Node<E> next; // node to return next
693     Node<E> pnext; // predecessor of next
694     Node<E> curr; // last returned node, for remove()
695     Node<E> pcurr; // predecessor of curr, for remove()
696 dl 1.33 E nextItem; // Cache of next item, once committed to in next
697 jsr166 1.5
698 dl 1.1 Itr() {
699 dl 1.33 advance();
700 dl 1.1 }
701 jsr166 1.5
702 dl 1.15 /**
703 dl 1.33 * Moves to next valid node and returns item to return for
704     * next(), or null if no such.
705 dl 1.15 */
706 dl 1.33 private E advance() {
707     pcurr = pnext;
708     curr = next;
709     E item = nextItem;
710    
711 dl 1.1 for (;;) {
712 jsr166 1.34 pnext = (next == null) ? traversalHead() : next;
713 dl 1.33 next = pnext.next;
714     if (next == pnext) {
715 dl 1.15 next = null;
716 dl 1.33 continue; // restart
717 dl 1.15 }
718 dl 1.33 if (next == null)
719     break;
720     Object x = next.get();
721     if (x != null && x != next) {
722 jsr166 1.22 nextItem = (E) x;
723 dl 1.33 break;
724 dl 1.1 }
725     }
726 dl 1.33 return item;
727 dl 1.1 }
728 jsr166 1.5
729 dl 1.1 public boolean hasNext() {
730 dl 1.15 return next != null;
731 dl 1.1 }
732 jsr166 1.5
733 dl 1.1 public E next() {
734 jsr166 1.35 if (next == null)
735 dl 1.33 throw new NoSuchElementException();
736     return advance();
737 dl 1.1 }
738 jsr166 1.5
739 dl 1.1 public void remove() {
740 jsr166 1.25 Node<E> p = curr;
741 dl 1.15 if (p == null)
742 dl 1.1 throw new IllegalStateException();
743     Object x = p.get();
744     if (x != null && x != p && p.compareAndSet(x, p))
745 dl 1.15 clean(pcurr, p);
746 dl 1.1 }
747     }
748    
749     public E peek() {
750     for (;;) {
751 jsr166 1.25 Node<E> h = traversalHead();
752     Node<E> p = h.next;
753 dl 1.1 if (p == null)
754     return null;
755     Object x = p.get();
756     if (p != x) {
757     if (!p.isData)
758     return null;
759     if (x != null)
760 jsr166 1.22 return (E) x;
761 dl 1.1 }
762     }
763     }
764    
765 dl 1.2 public boolean isEmpty() {
766     for (;;) {
767 jsr166 1.25 Node<E> h = traversalHead();
768     Node<E> p = h.next;
769 dl 1.2 if (p == null)
770     return true;
771     Object x = p.get();
772     if (p != x) {
773     if (!p.isData)
774     return true;
775     if (x != null)
776     return false;
777     }
778     }
779     }
780    
781 dl 1.1 public boolean hasWaitingConsumer() {
782     for (;;) {
783 jsr166 1.25 Node<E> h = traversalHead();
784     Node<E> p = h.next;
785 dl 1.1 if (p == null)
786     return false;
787     Object x = p.get();
788 jsr166 1.5 if (p != x)
789 dl 1.1 return !p.isData;
790     }
791     }
792 jsr166 1.5
793 dl 1.1 /**
794     * Returns the number of elements in this queue. If this queue
795 jsr166 1.11 * contains more than {@code Integer.MAX_VALUE} elements, returns
796     * {@code Integer.MAX_VALUE}.
797 dl 1.1 *
798     * <p>Beware that, unlike in most collections, this method is
799     * <em>NOT</em> a constant-time operation. Because of the
800     * asynchronous nature of these queues, determining the current
801     * number of elements requires an O(n) traversal.
802     *
803     * @return the number of elements in this queue
804     */
805     public int size() {
806 dl 1.33 for (;;) {
807     int count = 0;
808     Node<E> pred = traversalHead();
809     for (;;) {
810     Node<E> q = pred.next;
811     if (q == pred) // restart
812 dl 1.1 break;
813 dl 1.33 if (q == null || !q.isData)
814     return count;
815     Object x = q.get();
816     if (x != null && x != q) {
817     if (++count == Integer.MAX_VALUE) // saturated
818     return count;
819     }
820     pred = q;
821 dl 1.1 }
822     }
823     }
824    
825     public int getWaitingConsumerCount() {
826 dl 1.33 // converse of size -- count valid non-data nodes
827     for (;;) {
828     int count = 0;
829     Node<E> pred = traversalHead();
830     for (;;) {
831     Node<E> q = pred.next;
832     if (q == pred) // restart
833 dl 1.1 break;
834 dl 1.33 if (q == null || q.isData)
835     return count;
836     Object x = q.get();
837     if (x == null) {
838     if (++count == Integer.MAX_VALUE) // saturated
839     return count;
840     }
841     pred = q;
842 dl 1.1 }
843     }
844     }
845    
846 dl 1.15 public boolean remove(Object o) {
847     if (o == null)
848     return false;
849     for (;;) {
850 jsr166 1.25 Node<E> pred = traversalHead();
851 dl 1.15 for (;;) {
852 jsr166 1.25 Node<E> q = pred.next;
853 dl 1.33 if (q == pred) // restart
854     break;
855 dl 1.15 if (q == null || !q.isData)
856     return false;
857     Object x = q.get();
858 jsr166 1.17 if (x != null && x != q && o.equals(x) &&
859 dl 1.15 q.compareAndSet(x, q)) {
860     clean(pred, q);
861     return true;
862     }
863     pred = q;
864     }
865     }
866     }
867    
868 jsr166 1.35 /**
869     * Always returns {@code Integer.MAX_VALUE} because a
870     * {@code LinkedTransferQueue} is not capacity constrained.
871     *
872     * @return {@code Integer.MAX_VALUE} (as specified by
873     * {@link BlockingQueue#remainingCapacity()})
874     */
875 dl 1.33 public int remainingCapacity() {
876     return Integer.MAX_VALUE;
877     }
878    
879 dl 1.1 /**
880     * Save the state to a stream (that is, serialize it).
881     *
882 jsr166 1.11 * @serialData All of the elements (each an {@code E}) in
883 dl 1.1 * the proper order, followed by a null
884     * @param s the stream
885     */
886     private void writeObject(java.io.ObjectOutputStream s)
887     throws java.io.IOException {
888     s.defaultWriteObject();
889 jsr166 1.16 for (E e : this)
890     s.writeObject(e);
891 dl 1.1 // Use trailing null as sentinel
892     s.writeObject(null);
893     }
894    
895     /**
896     * Reconstitute the Queue instance from a stream (that is,
897     * deserialize it).
898 jsr166 1.19 *
899 dl 1.1 * @param s the stream
900     */
901     private void readObject(java.io.ObjectInputStream s)
902     throws java.io.IOException, ClassNotFoundException {
903     s.defaultReadObject();
904 dl 1.7 resetHeadAndTail();
905 dl 1.1 for (;;) {
906 jsr166 1.25 @SuppressWarnings("unchecked") E item = (E) s.readObject();
907 dl 1.1 if (item == null)
908     break;
909     else
910     offer(item);
911     }
912     }
913 dl 1.7
914     // Support for resetting head/tail while deserializing
915 dl 1.12 private void resetHeadAndTail() {
916 jsr166 1.25 Node<E> dummy = new Node<E>(null, false);
917 jsr166 1.20 UNSAFE.putObjectVolatile(this, headOffset,
918 jsr166 1.25 new PaddedAtomicReference<Node<E>>(dummy));
919 jsr166 1.20 UNSAFE.putObjectVolatile(this, tailOffset,
920 jsr166 1.25 new PaddedAtomicReference<Node<E>>(dummy));
921 jsr166 1.20 UNSAFE.putObjectVolatile(this, cleanMeOffset,
922 jsr166 1.25 new PaddedAtomicReference<Node<E>>(null));
923 dl 1.12 }
924 dl 1.7
925 jsr166 1.28 // Unsafe mechanics
926    
927     private static final sun.misc.Unsafe UNSAFE = getUnsafe();
928     private static final long headOffset =
929 jsr166 1.31 objectFieldOffset(UNSAFE, "head", LinkedTransferQueue.class);
930 jsr166 1.28 private static final long tailOffset =
931 jsr166 1.31 objectFieldOffset(UNSAFE, "tail", LinkedTransferQueue.class);
932 jsr166 1.28 private static final long cleanMeOffset =
933 jsr166 1.31 objectFieldOffset(UNSAFE, "cleanMe", LinkedTransferQueue.class);
934    
935 jsr166 1.28
936 jsr166 1.31 static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
937     String field, Class<?> klazz) {
938 jsr166 1.28 try {
939     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
940     } catch (NoSuchFieldException e) {
941     // Convert Exception to corresponding Error
942     NoSuchFieldError error = new NoSuchFieldError(field);
943     error.initCause(e);
944     throw error;
945     }
946     }
947    
948     /**
949     * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
950     * Replace with a simple call to Unsafe.getUnsafe when integrating
951     * into a jdk.
952     *
953     * @return a sun.misc.Unsafe
954     */
955 jsr166 1.25 private static sun.misc.Unsafe getUnsafe() {
956 jsr166 1.13 try {
957 jsr166 1.25 return sun.misc.Unsafe.getUnsafe();
958 jsr166 1.13 } catch (SecurityException se) {
959     try {
960     return java.security.AccessController.doPrivileged
961 jsr166 1.28 (new java.security
962     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
963 jsr166 1.25 public sun.misc.Unsafe run() throws Exception {
964 jsr166 1.28 java.lang.reflect.Field f = sun.misc
965     .Unsafe.class.getDeclaredField("theUnsafe");
966     f.setAccessible(true);
967     return (sun.misc.Unsafe) f.get(null);
968 jsr166 1.13 }});
969     } catch (java.security.PrivilegedActionException e) {
970 jsr166 1.25 throw new RuntimeException("Could not initialize intrinsics",
971     e.getCause());
972 jsr166 1.13 }
973     }
974     }
975 dl 1.1 }