ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/LinkedTransferQueue.java
Revision: 1.15
Committed: Wed Mar 25 13:43:42 2009 UTC (15 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.14: +82 -32 lines
Log Message:
Fix iterators, add explicit remove method

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.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.4 * 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 dl 1.9 if (x == s) { // was cancelled
276     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 dl 1.9 * Returns validated tail for use in cleaning methods
320     */
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 dl 1.9 * @param pred predecessor of cancelled node
343     * @param s the cancelled node
344 dl 1.1 */
345 dl 1.9 private void clean(QNode pred, QNode s) {
346 dl 1.1 Thread w = s.waiter;
347     if (w != null) { // Wake up thread
348     s.waiter = null;
349     if (w != Thread.currentThread())
350     LockSupport.unpark(w);
351     }
352 dl 1.15
353     if (pred == null)
354     return;
355    
356 dl 1.9 /*
357     * At any given time, exactly one node on list cannot be
358     * deleted -- the last inserted node. To accommodate this, if
359     * we cannot delete s, we save its predecessor as "cleanMe",
360     * processing the previously saved version first. At least one
361     * of node s or the node previously saved can always be
362     * processed, so this always terminates.
363     */
364     while (pred.next == s) {
365     QNode oldpred = reclean(); // First, help get rid of cleanMe
366     QNode t = getValidatedTail();
367     if (s != t) { // If not tail, try to unsplice
368     QNode sn = s.next; // s.next == s means s already off list
369 jsr166 1.10 if (sn == s || pred.casNext(s, sn))
370 dl 1.9 break;
371     }
372     else if (oldpred == pred || // Already saved
373     (oldpred == null && cleanMe.compareAndSet(null, pred)))
374     break; // Postpone cleaning
375     }
376     }
377 jsr166 1.5
378 dl 1.9 /**
379     * Tries to unsplice the cancelled node held in cleanMe that was
380     * previously uncleanable because it was at tail.
381     * @return current cleanMe node (or null)
382     */
383     private QNode reclean() {
384 jsr166 1.10 /*
385 dl 1.9 * cleanMe is, or at one time was, predecessor of cancelled
386     * node s that was the tail so could not be unspliced. If s
387     * is no longer the tail, try to unsplice if necessary and
388     * make cleanMe slot available. This differs from similar
389     * code in clean() because we must check that pred still
390     * points to a cancelled node that must be unspliced -- if
391     * not, we can (must) clear cleanMe without unsplicing.
392     * This can loop only due to contention on casNext or
393 jsr166 1.10 * clearing cleanMe.
394 dl 1.9 */
395     QNode pred;
396     while ((pred = cleanMe.get()) != null) {
397     QNode t = getValidatedTail();
398     QNode s = pred.next;
399 jsr166 1.10 if (s != t) {
400 dl 1.9 QNode sn;
401     if (s == null || s == pred || s.get() != s ||
402     (sn = s.next) == s || pred.casNext(s, sn))
403     cleanMe.compareAndSet(pred, null);
404 dl 1.1 }
405 dl 1.9 else // s is still tail; cannot clean
406     break;
407 dl 1.1 }
408 dl 1.9 return pred;
409 dl 1.1 }
410 jsr166 1.5
411 dl 1.1 /**
412 jsr166 1.11 * Creates an initially empty {@code LinkedTransferQueue}.
413 dl 1.1 */
414     public LinkedTransferQueue() {
415 dl 1.7 QNode dummy = new QNode(null, false);
416     head = new PaddedAtomicReference<QNode>(dummy);
417     tail = new PaddedAtomicReference<QNode>(dummy);
418     cleanMe = new PaddedAtomicReference<QNode>(null);
419 dl 1.1 }
420    
421     /**
422 jsr166 1.11 * Creates a {@code LinkedTransferQueue}
423 dl 1.1 * initially containing the elements of the given collection,
424     * added in traversal order of the collection's iterator.
425     * @param c the collection of elements to initially contain
426     * @throws NullPointerException if the specified collection or any
427     * of its elements are null
428     */
429     public LinkedTransferQueue(Collection<? extends E> c) {
430 dl 1.7 this();
431 dl 1.1 addAll(c);
432     }
433    
434     public void put(E e) throws InterruptedException {
435     if (e == null) throw new NullPointerException();
436     if (Thread.interrupted()) throw new InterruptedException();
437     xfer(e, NOWAIT, 0);
438     }
439    
440 jsr166 1.5 public boolean offer(E e, long timeout, TimeUnit unit)
441 dl 1.1 throws InterruptedException {
442     if (e == null) throw new NullPointerException();
443     if (Thread.interrupted()) throw new InterruptedException();
444     xfer(e, NOWAIT, 0);
445     return true;
446     }
447    
448     public boolean offer(E e) {
449     if (e == null) throw new NullPointerException();
450     xfer(e, NOWAIT, 0);
451     return true;
452     }
453    
454 dl 1.15 public boolean add(E e) {
455     if (e == null) throw new NullPointerException();
456     xfer(e, NOWAIT, 0);
457     return true;
458     }
459    
460 dl 1.1 public void transfer(E e) throws InterruptedException {
461     if (e == null) throw new NullPointerException();
462     if (xfer(e, WAIT, 0) == null) {
463 jsr166 1.6 Thread.interrupted();
464 dl 1.1 throw new InterruptedException();
465 jsr166 1.6 }
466 dl 1.1 }
467    
468     public boolean tryTransfer(E e, long timeout, TimeUnit unit)
469     throws InterruptedException {
470     if (e == null) throw new NullPointerException();
471     if (xfer(e, TIMEOUT, unit.toNanos(timeout)) != null)
472     return true;
473     if (!Thread.interrupted())
474     return false;
475     throw new InterruptedException();
476     }
477    
478     public boolean tryTransfer(E e) {
479     if (e == null) throw new NullPointerException();
480     return fulfill(e) != null;
481     }
482    
483     public E take() throws InterruptedException {
484     Object e = xfer(null, WAIT, 0);
485     if (e != null)
486     return (E)e;
487 jsr166 1.6 Thread.interrupted();
488 dl 1.1 throw new InterruptedException();
489     }
490    
491     public E poll(long timeout, TimeUnit unit) throws InterruptedException {
492     Object e = xfer(null, TIMEOUT, unit.toNanos(timeout));
493     if (e != null || !Thread.interrupted())
494     return (E)e;
495     throw new InterruptedException();
496     }
497    
498     public E poll() {
499     return (E)fulfill(null);
500     }
501    
502     public int drainTo(Collection<? super E> c) {
503     if (c == null)
504     throw new NullPointerException();
505     if (c == this)
506     throw new IllegalArgumentException();
507     int n = 0;
508     E e;
509     while ( (e = poll()) != null) {
510     c.add(e);
511     ++n;
512     }
513     return n;
514     }
515    
516     public int drainTo(Collection<? super E> c, int maxElements) {
517     if (c == null)
518     throw new NullPointerException();
519     if (c == this)
520     throw new IllegalArgumentException();
521     int n = 0;
522     E e;
523     while (n < maxElements && (e = poll()) != null) {
524     c.add(e);
525     ++n;
526     }
527     return n;
528     }
529    
530     // Traversal-based methods
531    
532     /**
533     * Return head after performing any outstanding helping steps
534     */
535     private QNode traversalHead() {
536     for (;;) {
537     QNode t = tail.get();
538     QNode h = head.get();
539     if (h != null && t != null) {
540     QNode last = t.next;
541     QNode first = h.next;
542     if (t == tail.get()) {
543 jsr166 1.5 if (last != null)
544 dl 1.1 tail.compareAndSet(t, last);
545     else if (first != null) {
546     Object x = first.get();
547 jsr166 1.5 if (x == first)
548     advanceHead(h, first);
549 dl 1.1 else
550     return h;
551     }
552     else
553     return h;
554     }
555     }
556 dl 1.15 reclean();
557 dl 1.1 }
558     }
559    
560    
561     public Iterator<E> iterator() {
562     return new Itr();
563     }
564    
565     /**
566 jsr166 1.4 * Iterators. Basic strategy is to traverse list, treating
567 dl 1.1 * non-data (i.e., request) nodes as terminating list.
568     * Once a valid data node is found, the item is cached
569     * so that the next call to next() will return it even
570     * if subsequently removed.
571     */
572     class Itr implements Iterator<E> {
573 dl 1.15 QNode next; // node to return next
574     QNode pnext; // predecessor of next
575     QNode snext; // successor of next
576     QNode curr; // last returned node, for remove()
577     QNode pcurr; // predecessor of curr, for remove()
578 dl 1.1 E nextItem; // Cache of next item, once commited to in next
579 jsr166 1.5
580 dl 1.1 Itr() {
581 dl 1.15 findNext();
582 dl 1.1 }
583 jsr166 1.5
584 dl 1.15 /**
585     * Ensure next points to next valid node, or null if none.
586     */
587     void findNext() {
588 dl 1.1 for (;;) {
589 dl 1.15 QNode pred = pnext;
590     QNode q = next;
591     if (pred == null || pred == q) {
592     pred = traversalHead();
593     q = pred.next;
594     }
595     if (q == null || !q.isData) {
596     next = null;
597     return;
598     }
599     Object x = q.get();
600     QNode s = q.next;
601     if (x != null && q != x && q != s) {
602     nextItem = (E)x;
603     snext = s;
604     pnext = pred;
605     next = q;
606     return;
607 dl 1.1 }
608 dl 1.15 pnext = q;
609     next = s;
610 dl 1.1 }
611     }
612 jsr166 1.5
613 dl 1.1 public boolean hasNext() {
614 dl 1.15 return next != null;
615 dl 1.1 }
616 jsr166 1.5
617 dl 1.1 public E next() {
618 dl 1.15 if (next == null) throw new NoSuchElementException();
619     pcurr = pnext;
620     curr = next;
621     pnext = next;
622     next = snext;
623     E x = nextItem;
624     findNext();
625     return x;
626 dl 1.1 }
627 jsr166 1.5
628 dl 1.1 public void remove() {
629 dl 1.15 QNode p = curr;
630     if (p == null)
631 dl 1.1 throw new IllegalStateException();
632     Object x = p.get();
633     if (x != null && x != p && p.compareAndSet(x, p))
634 dl 1.15 clean(pcurr, p);
635 dl 1.1 }
636     }
637    
638     public E peek() {
639     for (;;) {
640     QNode h = traversalHead();
641     QNode p = h.next;
642     if (p == null)
643     return null;
644     Object x = p.get();
645     if (p != x) {
646     if (!p.isData)
647     return null;
648     if (x != null)
649     return (E)x;
650     }
651     }
652     }
653    
654 dl 1.2 public boolean isEmpty() {
655     for (;;) {
656     QNode h = traversalHead();
657     QNode p = h.next;
658     if (p == null)
659     return true;
660     Object x = p.get();
661     if (p != x) {
662     if (!p.isData)
663     return true;
664     if (x != null)
665     return false;
666     }
667     }
668     }
669    
670 dl 1.1 public boolean hasWaitingConsumer() {
671     for (;;) {
672     QNode h = traversalHead();
673     QNode p = h.next;
674     if (p == null)
675     return false;
676     Object x = p.get();
677 jsr166 1.5 if (p != x)
678 dl 1.1 return !p.isData;
679     }
680     }
681 jsr166 1.5
682 dl 1.1 /**
683     * Returns the number of elements in this queue. If this queue
684 jsr166 1.11 * contains more than {@code Integer.MAX_VALUE} elements, returns
685     * {@code Integer.MAX_VALUE}.
686 dl 1.1 *
687     * <p>Beware that, unlike in most collections, this method is
688     * <em>NOT</em> a constant-time operation. Because of the
689     * asynchronous nature of these queues, determining the current
690     * number of elements requires an O(n) traversal.
691     *
692     * @return the number of elements in this queue
693     */
694     public int size() {
695     int count = 0;
696     QNode h = traversalHead();
697     for (QNode p = h.next; p != null && p.isData; p = p.next) {
698     Object x = p.get();
699 jsr166 1.5 if (x != null && x != p) {
700 dl 1.1 if (++count == Integer.MAX_VALUE) // saturated
701     break;
702     }
703     }
704     return count;
705     }
706    
707     public int getWaitingConsumerCount() {
708     int count = 0;
709     QNode h = traversalHead();
710     for (QNode p = h.next; p != null && !p.isData; p = p.next) {
711     if (p.get() == null) {
712     if (++count == Integer.MAX_VALUE)
713     break;
714     }
715     }
716     return count;
717     }
718    
719     public int remainingCapacity() {
720     return Integer.MAX_VALUE;
721     }
722    
723 dl 1.15 public boolean remove(Object o) {
724     if (o == null)
725     return false;
726     for (;;) {
727     QNode pred = traversalHead();
728     for (;;) {
729     QNode q = pred.next;
730     if (q == null || !q.isData)
731     return false;
732     if (q == pred) // restart
733     break;
734     Object x = q.get();
735     if (x != null && x != q && o.equals(x) &&
736     q.compareAndSet(x, q)) {
737     clean(pred, q);
738     return true;
739     }
740     pred = q;
741     }
742     }
743     }
744    
745 dl 1.1 /**
746     * Save the state to a stream (that is, serialize it).
747     *
748 jsr166 1.11 * @serialData All of the elements (each an {@code E}) in
749 dl 1.1 * the proper order, followed by a null
750     * @param s the stream
751     */
752     private void writeObject(java.io.ObjectOutputStream s)
753     throws java.io.IOException {
754     s.defaultWriteObject();
755     for (Iterator<E> it = iterator(); it.hasNext(); )
756     s.writeObject(it.next());
757     // Use trailing null as sentinel
758     s.writeObject(null);
759     }
760    
761     /**
762     * Reconstitute the Queue instance from a stream (that is,
763     * deserialize it).
764     * @param s the stream
765     */
766     private void readObject(java.io.ObjectInputStream s)
767     throws java.io.IOException, ClassNotFoundException {
768     s.defaultReadObject();
769 dl 1.7 resetHeadAndTail();
770 dl 1.1 for (;;) {
771     E item = (E)s.readObject();
772     if (item == null)
773     break;
774     else
775     offer(item);
776     }
777     }
778 dl 1.7
779    
780     // Support for resetting head/tail while deserializing
781 dl 1.12 private void resetHeadAndTail() {
782     QNode dummy = new QNode(null, false);
783     _unsafe.putObjectVolatile(this, headOffset,
784     new PaddedAtomicReference<QNode>(dummy));
785     _unsafe.putObjectVolatile(this, tailOffset,
786     new PaddedAtomicReference<QNode>(dummy));
787     _unsafe.putObjectVolatile(this, cleanMeOffset,
788     new PaddedAtomicReference<QNode>(null));
789     }
790 dl 1.7
791     // Temporary Unsafe mechanics for preliminary release
792 jsr166 1.13 private static Unsafe getUnsafe() throws Throwable {
793     try {
794     return Unsafe.getUnsafe();
795     } catch (SecurityException se) {
796     try {
797     return java.security.AccessController.doPrivileged
798     (new java.security.PrivilegedExceptionAction<Unsafe>() {
799     public Unsafe run() throws Exception {
800     return getUnsafePrivileged();
801     }});
802     } catch (java.security.PrivilegedActionException e) {
803     throw e.getCause();
804     }
805     }
806     }
807    
808     private static Unsafe getUnsafePrivileged()
809     throws NoSuchFieldException, IllegalAccessException {
810     Field f = Unsafe.class.getDeclaredField("theUnsafe");
811     f.setAccessible(true);
812 jsr166 1.14 return (Unsafe) f.get(null);
813 jsr166 1.13 }
814    
815     private static long fieldOffset(String fieldName)
816     throws NoSuchFieldException {
817     return _unsafe.objectFieldOffset
818     (LinkedTransferQueue.class.getDeclaredField(fieldName));
819     }
820    
821 dl 1.7 private static final Unsafe _unsafe;
822     private static final long headOffset;
823     private static final long tailOffset;
824     private static final long cleanMeOffset;
825     static {
826     try {
827 jsr166 1.13 _unsafe = getUnsafe();
828     headOffset = fieldOffset("head");
829     tailOffset = fieldOffset("tail");
830     cleanMeOffset = fieldOffset("cleanMe");
831     } catch (Throwable e) {
832 dl 1.7 throw new RuntimeException("Could not initialize intrinsics", e);
833     }
834     }
835    
836 dl 1.1 }