ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/LinkedTransferQueue.java
Revision: 1.19
Committed: Tue Jul 21 00:15:14 2009 UTC (14 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.18: +1 -0 lines
Log Message:
j.u.c. coding standards

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