ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.7
Committed: Tue Aug 4 20:41:40 2009 UTC (14 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.6: +18 -23 lines
Log Message:
sync with jsr166 package

File Contents

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