ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/LinkedTransferQueue.java
Revision: 1.10
Committed: Mon Jan 5 03:43:07 2009 UTC (15 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.9: +7 -7 lines
Log Message:
whitespace

File Contents

# Content
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 import sun.misc.Unsafe;
14 import java.lang.reflect.*;
15
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 * <p>Beware that, unlike in most collections, the <tt>size</tt>
25 * 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 * @since 1.7
45 * @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 * 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 */
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 static final int maxTimedSpins = (NCPUS < 2)? 0 : 32;
85
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 /**
100 * 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 */
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 boolean casNext(QNode cmp, QNode val) {
120 return nextUpdater.compareAndSet(this, cmp, val);
121 }
122 }
123
124 /**
125 * Padded version of AtomicReference used for head, tail and
126 * cleanMe, to alleviate contention across threads CASing one vs
127 * the other.
128 */
129 static final class PaddedAtomicReference<T> extends AtomicReference<T> {
130 // enough padding for 64bytes with 4byte refs
131 Object p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe;
132 PaddedAtomicReference(T r) { super(r); }
133 }
134
135
136 /** head of the queue */
137 private transient final PaddedAtomicReference<QNode> head;
138 /** tail of the queue */
139 private transient final PaddedAtomicReference<QNode> tail;
140
141 /**
142 * Reference to a cancelled node that might not yet have been
143 * unlinked from queue because it was the last inserted node
144 * when it cancelled.
145 */
146 private transient final PaddedAtomicReference<QNode> cleanMe;
147
148 /**
149 * Tries to cas nh as new head; if successful, unlink
150 * old head's next node to avoid garbage retention.
151 */
152 private boolean advanceHead(QNode h, QNode nh) {
153 if (h == head.get() && head.compareAndSet(h, nh)) {
154 h.next = h; // forget old next
155 return true;
156 }
157 return false;
158 }
159
160 /**
161 * Puts or takes an item. Used for most queue operations (except
162 * poll() and tryTransfer()). See the similar code in
163 * SynchronousQueue for detailed explanation.
164 * @param e the item or if null, signifies that this is a take
165 * @param mode the wait mode: NOWAIT, TIMEOUT, WAIT
166 * @param nanos timeout in nanosecs, used only if mode is TIMEOUT
167 * @return an item, or null on failure
168 */
169 private Object xfer(Object e, int mode, long nanos) {
170 boolean isData = (e != null);
171 QNode s = null;
172 final PaddedAtomicReference<QNode> head = this.head;
173 final PaddedAtomicReference<QNode> tail = this.tail;
174
175 for (;;) {
176 QNode t = tail.get();
177 QNode h = head.get();
178
179 if (t != null && (t == h || t.isData == isData)) {
180 if (s == null)
181 s = new QNode(e, isData);
182 QNode last = t.next;
183 if (last != null) {
184 if (t == tail.get())
185 tail.compareAndSet(t, last);
186 }
187 else if (t.casNext(null, s)) {
188 tail.compareAndSet(t, s);
189 return awaitFulfill(t, s, e, mode, nanos);
190 }
191 }
192
193 else if (h != null) {
194 QNode first = h.next;
195 if (t == tail.get() && first != null &&
196 advanceHead(h, first)) {
197 Object x = first.get();
198 if (x != first && first.compareAndSet(x, e)) {
199 LockSupport.unpark(first.waiter);
200 return isData? e : x;
201 }
202 }
203 }
204 }
205 }
206
207
208 /**
209 * Version of xfer for poll() and tryTransfer, which
210 * simplifies control paths both here and in xfer
211 */
212 private Object fulfill(Object e) {
213 boolean isData = (e != null);
214 final PaddedAtomicReference<QNode> head = this.head;
215 final PaddedAtomicReference<QNode> tail = this.tail;
216
217 for (;;) {
218 QNode t = tail.get();
219 QNode h = head.get();
220
221 if (t != null && (t == h || t.isData == isData)) {
222 QNode last = t.next;
223 if (t == tail.get()) {
224 if (last != null)
225 tail.compareAndSet(t, last);
226 else
227 return null;
228 }
229 }
230 else if (h != null) {
231 QNode first = h.next;
232 if (t == tail.get() &&
233 first != null &&
234 advanceHead(h, first)) {
235 Object x = first.get();
236 if (x != first && first.compareAndSet(x, e)) {
237 LockSupport.unpark(first.waiter);
238 return isData? e : x;
239 }
240 }
241 }
242 }
243 }
244
245 /**
246 * Spins/blocks until node s is fulfilled or caller gives up,
247 * depending on wait mode.
248 *
249 * @param pred the predecessor of waiting node
250 * @param s the waiting node
251 * @param e the comparison value for checking match
252 * @param mode mode
253 * @param nanos timeout value
254 * @return matched item, or s if cancelled
255 */
256 private Object awaitFulfill(QNode pred, QNode s, Object e,
257 int mode, long nanos) {
258 if (mode == NOWAIT)
259 return null;
260
261 long lastTime = (mode == TIMEOUT)? System.nanoTime() : 0;
262 Thread w = Thread.currentThread();
263 int spins = -1; // set to desired spin count below
264 for (;;) {
265 if (w.isInterrupted())
266 s.compareAndSet(e, s);
267 Object x = s.get();
268 if (x != e) { // Node was matched or cancelled
269 advanceHead(pred, s); // unlink if head
270 if (x == s) { // was cancelled
271 clean(pred, s);
272 return null;
273 }
274 else if (x != null) {
275 s.set(s); // avoid garbage retention
276 return x;
277 }
278 else
279 return e;
280 }
281 if (mode == TIMEOUT) {
282 long now = System.nanoTime();
283 nanos -= now - lastTime;
284 lastTime = now;
285 if (nanos <= 0) {
286 s.compareAndSet(e, s); // try to cancel
287 continue;
288 }
289 }
290 if (spins < 0) {
291 QNode h = head.get(); // only spin if at head
292 spins = ((h != null && h.next == s) ?
293 (mode == TIMEOUT?
294 maxTimedSpins : maxUntimedSpins) : 0);
295 }
296 if (spins > 0)
297 --spins;
298 else if (s.waiter == null)
299 s.waiter = w;
300 else if (mode != TIMEOUT) {
301 // LockSupport.park(this);
302 LockSupport.park(); // allows run on java5
303 s.waiter = null;
304 spins = -1;
305 }
306 else if (nanos > spinForTimeoutThreshold) {
307 // LockSupport.parkNanos(this, nanos);
308 LockSupport.parkNanos(nanos);
309 s.waiter = null;
310 spins = -1;
311 }
312 }
313 }
314
315 /**
316 * Returns validated tail for use in cleaning methods
317 */
318 private QNode getValidatedTail() {
319 for (;;) {
320 QNode h = head.get();
321 QNode first = h.next;
322 if (first != null && first.next == first) { // help advance
323 advanceHead(h, first);
324 continue;
325 }
326 QNode t = tail.get();
327 QNode last = t.next;
328 if (t == tail.get()) {
329 if (last != null)
330 tail.compareAndSet(t, last); // help advance
331 else
332 return t;
333 }
334 }
335 }
336
337 /**
338 * Gets rid of cancelled node s with original predecessor pred.
339 * @param pred predecessor of cancelled node
340 * @param s the cancelled node
341 */
342 private void clean(QNode pred, QNode s) {
343 Thread w = s.waiter;
344 if (w != null) { // Wake up thread
345 s.waiter = null;
346 if (w != Thread.currentThread())
347 LockSupport.unpark(w);
348 }
349 /*
350 * At any given time, exactly one node on list cannot be
351 * deleted -- the last inserted node. To accommodate this, if
352 * we cannot delete s, we save its predecessor as "cleanMe",
353 * processing the previously saved version first. At least one
354 * of node s or the node previously saved can always be
355 * processed, so this always terminates.
356 */
357 while (pred.next == s) {
358 QNode oldpred = reclean(); // First, help get rid of cleanMe
359 QNode t = getValidatedTail();
360 if (s != t) { // If not tail, try to unsplice
361 QNode sn = s.next; // s.next == s means s already off list
362 if (sn == s || pred.casNext(s, sn))
363 break;
364 }
365 else if (oldpred == pred || // Already saved
366 (oldpred == null && cleanMe.compareAndSet(null, pred)))
367 break; // Postpone cleaning
368 }
369 }
370
371 /**
372 * Tries to unsplice the cancelled node held in cleanMe that was
373 * previously uncleanable because it was at tail.
374 * @return current cleanMe node (or null)
375 */
376 private QNode reclean() {
377 /*
378 * cleanMe is, or at one time was, predecessor of cancelled
379 * node s that was the tail so could not be unspliced. If s
380 * is no longer the tail, try to unsplice if necessary and
381 * make cleanMe slot available. This differs from similar
382 * code in clean() because we must check that pred still
383 * points to a cancelled node that must be unspliced -- if
384 * not, we can (must) clear cleanMe without unsplicing.
385 * This can loop only due to contention on casNext or
386 * clearing cleanMe.
387 */
388 QNode pred;
389 while ((pred = cleanMe.get()) != null) {
390 QNode t = getValidatedTail();
391 QNode s = pred.next;
392 if (s != t) {
393 QNode sn;
394 if (s == null || s == pred || s.get() != s ||
395 (sn = s.next) == s || pred.casNext(s, sn))
396 cleanMe.compareAndSet(pred, null);
397 }
398 else // s is still tail; cannot clean
399 break;
400 }
401 return pred;
402 }
403
404 /**
405 * Creates an initially empty <tt>LinkedTransferQueue</tt>.
406 */
407 public LinkedTransferQueue() {
408 QNode dummy = new QNode(null, false);
409 head = new PaddedAtomicReference<QNode>(dummy);
410 tail = new PaddedAtomicReference<QNode>(dummy);
411 cleanMe = new PaddedAtomicReference<QNode>(null);
412 }
413
414 /**
415 * Creates a <tt>LinkedTransferQueue</tt>
416 * initially containing the elements of the given collection,
417 * added in traversal order of the collection's iterator.
418 * @param c the collection of elements to initially contain
419 * @throws NullPointerException if the specified collection or any
420 * of its elements are null
421 */
422 public LinkedTransferQueue(Collection<? extends E> c) {
423 this();
424 addAll(c);
425 }
426
427 public void put(E e) throws InterruptedException {
428 if (e == null) throw new NullPointerException();
429 if (Thread.interrupted()) throw new InterruptedException();
430 xfer(e, NOWAIT, 0);
431 }
432
433 public boolean offer(E e, long timeout, TimeUnit unit)
434 throws InterruptedException {
435 if (e == null) throw new NullPointerException();
436 if (Thread.interrupted()) throw new InterruptedException();
437 xfer(e, NOWAIT, 0);
438 return true;
439 }
440
441 public boolean offer(E e) {
442 if (e == null) throw new NullPointerException();
443 xfer(e, NOWAIT, 0);
444 return true;
445 }
446
447 public void transfer(E e) throws InterruptedException {
448 if (e == null) throw new NullPointerException();
449 if (xfer(e, WAIT, 0) == null) {
450 Thread.interrupted();
451 throw new InterruptedException();
452 }
453 }
454
455 public boolean tryTransfer(E e, long timeout, TimeUnit unit)
456 throws InterruptedException {
457 if (e == null) throw new NullPointerException();
458 if (xfer(e, TIMEOUT, unit.toNanos(timeout)) != null)
459 return true;
460 if (!Thread.interrupted())
461 return false;
462 throw new InterruptedException();
463 }
464
465 public boolean tryTransfer(E e) {
466 if (e == null) throw new NullPointerException();
467 return fulfill(e) != null;
468 }
469
470 public E take() throws InterruptedException {
471 Object e = xfer(null, WAIT, 0);
472 if (e != null)
473 return (E)e;
474 Thread.interrupted();
475 throw new InterruptedException();
476 }
477
478 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
479 Object e = xfer(null, TIMEOUT, unit.toNanos(timeout));
480 if (e != null || !Thread.interrupted())
481 return (E)e;
482 throw new InterruptedException();
483 }
484
485 public E poll() {
486 return (E)fulfill(null);
487 }
488
489 public int drainTo(Collection<? super E> c) {
490 if (c == null)
491 throw new NullPointerException();
492 if (c == this)
493 throw new IllegalArgumentException();
494 int n = 0;
495 E e;
496 while ( (e = poll()) != null) {
497 c.add(e);
498 ++n;
499 }
500 return n;
501 }
502
503 public int drainTo(Collection<? super E> c, int maxElements) {
504 if (c == null)
505 throw new NullPointerException();
506 if (c == this)
507 throw new IllegalArgumentException();
508 int n = 0;
509 E e;
510 while (n < maxElements && (e = poll()) != null) {
511 c.add(e);
512 ++n;
513 }
514 return n;
515 }
516
517 // Traversal-based methods
518
519 /**
520 * Return head after performing any outstanding helping steps
521 */
522 private QNode traversalHead() {
523 for (;;) {
524 QNode t = tail.get();
525 QNode h = head.get();
526 if (h != null && t != null) {
527 QNode last = t.next;
528 QNode first = h.next;
529 if (t == tail.get()) {
530 if (last != null)
531 tail.compareAndSet(t, last);
532 else if (first != null) {
533 Object x = first.get();
534 if (x == first)
535 advanceHead(h, first);
536 else
537 return h;
538 }
539 else
540 return h;
541 }
542 }
543 }
544 }
545
546
547 public Iterator<E> iterator() {
548 return new Itr();
549 }
550
551 /**
552 * Iterators. Basic strategy is to traverse list, treating
553 * non-data (i.e., request) nodes as terminating list.
554 * Once a valid data node is found, the item is cached
555 * so that the next call to next() will return it even
556 * if subsequently removed.
557 */
558 class Itr implements Iterator<E> {
559 QNode nextNode; // Next node to return next
560 QNode currentNode; // last returned node, for remove()
561 QNode prevNode; // predecessor of last returned node
562 E nextItem; // Cache of next item, once commited to in next
563
564 Itr() {
565 nextNode = traversalHead();
566 advance();
567 }
568
569 E advance() {
570 prevNode = currentNode;
571 currentNode = nextNode;
572 E x = nextItem;
573
574 QNode p = nextNode.next;
575 for (;;) {
576 if (p == null || !p.isData) {
577 nextNode = null;
578 nextItem = null;
579 return x;
580 }
581 Object item = p.get();
582 if (item != p && item != null) {
583 nextNode = p;
584 nextItem = (E)item;
585 return x;
586 }
587 prevNode = p;
588 p = p.next;
589 }
590 }
591
592 public boolean hasNext() {
593 return nextNode != null;
594 }
595
596 public E next() {
597 if (nextNode == null) throw new NoSuchElementException();
598 return advance();
599 }
600
601 public void remove() {
602 QNode p = currentNode;
603 QNode prev = prevNode;
604 if (prev == null || p == null)
605 throw new IllegalStateException();
606 Object x = p.get();
607 if (x != null && x != p && p.compareAndSet(x, p))
608 clean(prev, p);
609 }
610 }
611
612 public E peek() {
613 for (;;) {
614 QNode h = traversalHead();
615 QNode p = h.next;
616 if (p == null)
617 return null;
618 Object x = p.get();
619 if (p != x) {
620 if (!p.isData)
621 return null;
622 if (x != null)
623 return (E)x;
624 }
625 }
626 }
627
628 public boolean isEmpty() {
629 for (;;) {
630 QNode h = traversalHead();
631 QNode p = h.next;
632 if (p == null)
633 return true;
634 Object x = p.get();
635 if (p != x) {
636 if (!p.isData)
637 return true;
638 if (x != null)
639 return false;
640 }
641 }
642 }
643
644 public boolean hasWaitingConsumer() {
645 for (;;) {
646 QNode h = traversalHead();
647 QNode p = h.next;
648 if (p == null)
649 return false;
650 Object x = p.get();
651 if (p != x)
652 return !p.isData;
653 }
654 }
655
656 /**
657 * Returns the number of elements in this queue. If this queue
658 * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
659 * <tt>Integer.MAX_VALUE</tt>.
660 *
661 * <p>Beware that, unlike in most collections, this method is
662 * <em>NOT</em> a constant-time operation. Because of the
663 * asynchronous nature of these queues, determining the current
664 * number of elements requires an O(n) traversal.
665 *
666 * @return the number of elements in this queue
667 */
668 public int size() {
669 int count = 0;
670 QNode h = traversalHead();
671 for (QNode p = h.next; p != null && p.isData; p = p.next) {
672 Object x = p.get();
673 if (x != null && x != p) {
674 if (++count == Integer.MAX_VALUE) // saturated
675 break;
676 }
677 }
678 return count;
679 }
680
681 public int getWaitingConsumerCount() {
682 int count = 0;
683 QNode h = traversalHead();
684 for (QNode p = h.next; p != null && !p.isData; p = p.next) {
685 if (p.get() == null) {
686 if (++count == Integer.MAX_VALUE)
687 break;
688 }
689 }
690 return count;
691 }
692
693 public int remainingCapacity() {
694 return Integer.MAX_VALUE;
695 }
696
697 /**
698 * Save the state to a stream (that is, serialize it).
699 *
700 * @serialData All of the elements (each an <tt>E</tt>) in
701 * the proper order, followed by a null
702 * @param s the stream
703 */
704 private void writeObject(java.io.ObjectOutputStream s)
705 throws java.io.IOException {
706 s.defaultWriteObject();
707 for (Iterator<E> it = iterator(); it.hasNext(); )
708 s.writeObject(it.next());
709 // Use trailing null as sentinel
710 s.writeObject(null);
711 }
712
713 /**
714 * Reconstitute the Queue instance from a stream (that is,
715 * deserialize it).
716 * @param s the stream
717 */
718 private void readObject(java.io.ObjectInputStream s)
719 throws java.io.IOException, ClassNotFoundException {
720 s.defaultReadObject();
721 resetHeadAndTail();
722 for (;;) {
723 E item = (E)s.readObject();
724 if (item == null)
725 break;
726 else
727 offer(item);
728 }
729 }
730
731
732 // Support for resetting head/tail while deserializing
733
734 // Temporary Unsafe mechanics for preliminary release
735 private static final Unsafe _unsafe;
736 private static final long headOffset;
737 private static final long tailOffset;
738 private static final long cleanMeOffset;
739 static {
740 try {
741 if (LinkedTransferQueue.class.getClassLoader() != null) {
742 Field f = Unsafe.class.getDeclaredField("theUnsafe");
743 f.setAccessible(true);
744 _unsafe = (Unsafe)f.get(null);
745 }
746 else
747 _unsafe = Unsafe.getUnsafe();
748 headOffset = _unsafe.objectFieldOffset
749 (LinkedTransferQueue.class.getDeclaredField("head"));
750 tailOffset = _unsafe.objectFieldOffset
751 (LinkedTransferQueue.class.getDeclaredField("tail"));
752 cleanMeOffset = _unsafe.objectFieldOffset
753 (LinkedTransferQueue.class.getDeclaredField("cleanMe"));
754 } catch (Exception e) {
755 throw new RuntimeException("Could not initialize intrinsics", e);
756 }
757 }
758
759 private void resetHeadAndTail() {
760 QNode dummy = new QNode(null, false);
761 _unsafe.putObjectVolatile(this, headOffset,
762 new PaddedAtomicReference<QNode>(dummy));
763 _unsafe.putObjectVolatile(this, tailOffset,
764 new PaddedAtomicReference<QNode>(dummy));
765 _unsafe.putObjectVolatile(this, cleanMeOffset,
766 new PaddedAtomicReference<QNode>(null));
767
768 }
769
770 }