ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/LinkedTransferQueue.java
Revision: 1.21
Committed: Wed Jul 22 01:36:51 2009 UTC (14 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.20: +0 -1 lines
Log Message:
Add @since, @author tags

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