ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedTransferQueue.java
Revision: 1.26
Committed: Wed Sep 1 23:40:29 2010 UTC (13 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.25: +2 -1 lines
Log Message:
very small docstring improvement

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 java.util.concurrent;
8
9 import java.util.AbstractQueue;
10 import java.util.Collection;
11 import java.util.ConcurrentModificationException;
12 import java.util.Iterator;
13 import java.util.NoSuchElementException;
14 import java.util.Queue;
15 import java.util.concurrent.locks.LockSupport;
16
17 /**
18 * An unbounded {@link TransferQueue} based on linked nodes.
19 * This queue orders elements FIFO (first-in-first-out) with respect
20 * to any given producer. The <em>head</em> of the queue is that
21 * element that has been on the queue the longest time for some
22 * producer. The <em>tail</em> of the queue is that element that has
23 * been on the queue the shortest time for some producer.
24 *
25 * <p>Beware that, unlike in most collections, the {@code size}
26 * method is <em>NOT</em> a constant-time operation. Because of the
27 * asynchronous nature of these queues, determining the current number
28 * of elements requires a traversal of the elements.
29 *
30 * <p>This class and its iterator implement all of the
31 * <em>optional</em> methods of the {@link Collection} and {@link
32 * Iterator} interfaces.
33 *
34 * <p>Memory consistency effects: As with other concurrent
35 * collections, actions in a thread prior to placing an object into a
36 * {@code LinkedTransferQueue}
37 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
38 * actions subsequent to the access or removal of that element from
39 * the {@code LinkedTransferQueue} in another thread.
40 *
41 * <p>This class is a member of the
42 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
43 * Java Collections Framework</a>.
44 *
45 * @since 1.7
46 * @author Doug Lea
47 * @param <E> the type of elements held in this collection
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 * *** Overview of Dual Queues with Slack ***
55 *
56 * Dual Queues, introduced by Scherer and Scott
57 * (http://www.cs.rice.edu/~wns1/papers/2004-DISC-DDS.pdf) are
58 * (linked) queues in which nodes may represent either data or
59 * requests. When a thread tries to enqueue a data node, but
60 * encounters a request node, it instead "matches" and removes it;
61 * and vice versa for enqueuing requests. Blocking Dual Queues
62 * arrange that threads enqueuing unmatched requests block until
63 * other threads provide the match. Dual Synchronous Queues (see
64 * Scherer, Lea, & Scott
65 * http://www.cs.rochester.edu/u/scott/papers/2009_Scherer_CACM_SSQ.pdf)
66 * additionally arrange that threads enqueuing unmatched data also
67 * block. Dual Transfer Queues support all of these modes, as
68 * dictated by callers.
69 *
70 * A FIFO dual queue may be implemented using a variation of the
71 * Michael & Scott (M&S) lock-free queue algorithm
72 * (http://www.cs.rochester.edu/u/scott/papers/1996_PODC_queues.pdf).
73 * It maintains two pointer fields, "head", pointing to a
74 * (matched) node that in turn points to the first actual
75 * (unmatched) queue node (or null if empty); and "tail" that
76 * points to the last node on the queue (or again null if
77 * empty). For example, here is a possible queue with four data
78 * elements:
79 *
80 * head tail
81 * | |
82 * v v
83 * M -> U -> U -> U -> U
84 *
85 * The M&S queue algorithm is known to be prone to scalability and
86 * overhead limitations when maintaining (via CAS) these head and
87 * tail pointers. This has led to the development of
88 * contention-reducing variants such as elimination arrays (see
89 * Moir et al http://portal.acm.org/citation.cfm?id=1074013) and
90 * optimistic back pointers (see Ladan-Mozes & Shavit
91 * http://people.csail.mit.edu/edya/publications/OptimisticFIFOQueue-journal.pdf).
92 * However, the nature of dual queues enables a simpler tactic for
93 * improving M&S-style implementations when dual-ness is needed.
94 *
95 * In a dual queue, each node must atomically maintain its match
96 * status. While there are other possible variants, we implement
97 * this here as: for a data-mode node, matching entails CASing an
98 * "item" field from a non-null data value to null upon match, and
99 * vice-versa for request nodes, CASing from null to a data
100 * value. (Note that the linearization properties of this style of
101 * queue are easy to verify -- elements are made available by
102 * linking, and unavailable by matching.) Compared to plain M&S
103 * queues, this property of dual queues requires one additional
104 * successful atomic operation per enq/deq pair. But it also
105 * enables lower cost variants of queue maintenance mechanics. (A
106 * variation of this idea applies even for non-dual queues that
107 * support deletion of interior elements, such as
108 * j.u.c.ConcurrentLinkedQueue.)
109 *
110 * Once a node is matched, its match status can never again
111 * change. We may thus arrange that the linked list of them
112 * contain a prefix of zero or more matched nodes, followed by a
113 * suffix of zero or more unmatched nodes. (Note that we allow
114 * both the prefix and suffix to be zero length, which in turn
115 * means that we do not use a dummy header.) If we were not
116 * concerned with either time or space efficiency, we could
117 * correctly perform enqueue and dequeue operations by traversing
118 * from a pointer to the initial node; CASing the item of the
119 * first unmatched node on match and CASing the next field of the
120 * trailing node on appends. (Plus some special-casing when
121 * initially empty). While this would be a terrible idea in
122 * itself, it does have the benefit of not requiring ANY atomic
123 * updates on head/tail fields.
124 *
125 * We introduce here an approach that lies between the extremes of
126 * never versus always updating queue (head and tail) pointers.
127 * This offers a tradeoff between sometimes requiring extra
128 * traversal steps to locate the first and/or last unmatched
129 * nodes, versus the reduced overhead and contention of fewer
130 * updates to queue pointers. For example, a possible snapshot of
131 * a queue is:
132 *
133 * head tail
134 * | |
135 * v v
136 * M -> M -> U -> U -> U -> U
137 *
138 * The best value for this "slack" (the targeted maximum distance
139 * between the value of "head" and the first unmatched node, and
140 * similarly for "tail") is an empirical matter. We have found
141 * that using very small constants in the range of 1-3 work best
142 * over a range of platforms. Larger values introduce increasing
143 * costs of cache misses and risks of long traversal chains, while
144 * smaller values increase CAS contention and overhead.
145 *
146 * Dual queues with slack differ from plain M&S dual queues by
147 * virtue of only sometimes updating head or tail pointers when
148 * matching, appending, or even traversing nodes; in order to
149 * maintain a targeted slack. The idea of "sometimes" may be
150 * operationalized in several ways. The simplest is to use a
151 * per-operation counter incremented on each traversal step, and
152 * to try (via CAS) to update the associated queue pointer
153 * whenever the count exceeds a threshold. Another, that requires
154 * more overhead, is to use random number generators to update
155 * with a given probability per traversal step.
156 *
157 * In any strategy along these lines, because CASes updating
158 * fields may fail, the actual slack may exceed targeted
159 * slack. However, they may be retried at any time to maintain
160 * targets. Even when using very small slack values, this
161 * approach works well for dual queues because it allows all
162 * operations up to the point of matching or appending an item
163 * (hence potentially allowing progress by another thread) to be
164 * read-only, thus not introducing any further contention. As
165 * described below, we implement this by performing slack
166 * maintenance retries only after these points.
167 *
168 * As an accompaniment to such techniques, traversal overhead can
169 * be further reduced without increasing contention of head
170 * pointer updates: Threads may sometimes shortcut the "next" link
171 * path from the current "head" node to be closer to the currently
172 * known first unmatched node, and similarly for tail. Again, this
173 * may be triggered with using thresholds or randomization.
174 *
175 * These ideas must be further extended to avoid unbounded amounts
176 * of costly-to-reclaim garbage caused by the sequential "next"
177 * links of nodes starting at old forgotten head nodes: As first
178 * described in detail by Boehm
179 * (http://portal.acm.org/citation.cfm?doid=503272.503282) if a GC
180 * delays noticing that any arbitrarily old node has become
181 * garbage, all newer dead nodes will also be unreclaimed.
182 * (Similar issues arise in non-GC environments.) To cope with
183 * this in our implementation, upon CASing to advance the head
184 * pointer, we set the "next" link of the previous head to point
185 * only to itself; thus limiting the length of connected dead lists.
186 * (We also take similar care to wipe out possibly garbage
187 * retaining values held in other Node fields.) However, doing so
188 * adds some further complexity to traversal: If any "next"
189 * pointer links to itself, it indicates that the current thread
190 * has lagged behind a head-update, and so the traversal must
191 * continue from the "head". Traversals trying to find the
192 * current tail starting from "tail" may also encounter
193 * self-links, in which case they also continue at "head".
194 *
195 * It is tempting in slack-based scheme to not even use CAS for
196 * updates (similarly to Ladan-Mozes & Shavit). However, this
197 * cannot be done for head updates under the above link-forgetting
198 * mechanics because an update may leave head at a detached node.
199 * And while direct writes are possible for tail updates, they
200 * increase the risk of long retraversals, and hence long garbage
201 * chains, which can be much more costly than is worthwhile
202 * considering that the cost difference of performing a CAS vs
203 * write is smaller when they are not triggered on each operation
204 * (especially considering that writes and CASes equally require
205 * additional GC bookkeeping ("write barriers") that are sometimes
206 * more costly than the writes themselves because of contention).
207 *
208 * *** Overview of implementation ***
209 *
210 * We use a threshold-based approach to updates, with a slack
211 * threshold of two -- that is, we update head/tail when the
212 * current pointer appears to be two or more steps away from the
213 * first/last node. The slack value is hard-wired: a path greater
214 * than one is naturally implemented by checking equality of
215 * traversal pointers except when the list has only one element,
216 * in which case we keep slack threshold at one. Avoiding tracking
217 * explicit counts across method calls slightly simplifies an
218 * already-messy implementation. Using randomization would
219 * probably work better if there were a low-quality dirt-cheap
220 * per-thread one available, but even ThreadLocalRandom is too
221 * heavy for these purposes.
222 *
223 * With such a small slack threshold value, it is not worthwhile
224 * to augment this with path short-circuiting (i.e., unsplicing
225 * interior nodes) except in the case of cancellation/removal (see
226 * below).
227 *
228 * We allow both the head and tail fields to be null before any
229 * nodes are enqueued; initializing upon first append. This
230 * simplifies some other logic, as well as providing more
231 * efficient explicit control paths instead of letting JVMs insert
232 * implicit NullPointerExceptions when they are null. While not
233 * currently fully implemented, we also leave open the possibility
234 * of re-nulling these fields when empty (which is complicated to
235 * arrange, for little benefit.)
236 *
237 * All enqueue/dequeue operations are handled by the single method
238 * "xfer" with parameters indicating whether to act as some form
239 * of offer, put, poll, take, or transfer (each possibly with
240 * timeout). The relative complexity of using one monolithic
241 * method outweighs the code bulk and maintenance problems of
242 * using separate methods for each case.
243 *
244 * Operation consists of up to three phases. The first is
245 * implemented within method xfer, the second in tryAppend, and
246 * the third in method awaitMatch.
247 *
248 * 1. Try to match an existing node
249 *
250 * Starting at head, skip already-matched nodes until finding
251 * an unmatched node of opposite mode, if one exists, in which
252 * case matching it and returning, also if necessary updating
253 * head to one past the matched node (or the node itself if the
254 * list has no other unmatched nodes). If the CAS misses, then
255 * a loop retries advancing head by two steps until either
256 * success or the slack is at most two. By requiring that each
257 * attempt advances head by two (if applicable), we ensure that
258 * the slack does not grow without bound. Traversals also check
259 * if the initial head is now off-list, in which case they
260 * start at the new head.
261 *
262 * If no candidates are found and the call was untimed
263 * poll/offer, (argument "how" is NOW) return.
264 *
265 * 2. Try to append a new node (method tryAppend)
266 *
267 * Starting at current tail pointer, find the actual last node
268 * and try to append a new node (or if head was null, establish
269 * the first node). Nodes can be appended only if their
270 * predecessors are either already matched or are of the same
271 * mode. If we detect otherwise, then a new node with opposite
272 * mode must have been appended during traversal, so we must
273 * restart at phase 1. The traversal and update steps are
274 * otherwise similar to phase 1: Retrying upon CAS misses and
275 * checking for staleness. In particular, if a self-link is
276 * encountered, then we can safely jump to a node on the list
277 * by continuing the traversal at current head.
278 *
279 * On successful append, if the call was ASYNC, return.
280 *
281 * 3. Await match or cancellation (method awaitMatch)
282 *
283 * Wait for another thread to match node; instead cancelling if
284 * the current thread was interrupted or the wait timed out. On
285 * multiprocessors, we use front-of-queue spinning: If a node
286 * appears to be the first unmatched node in the queue, it
287 * spins a bit before blocking. In either case, before blocking
288 * it tries to unsplice any nodes between the current "head"
289 * and the first unmatched node.
290 *
291 * Front-of-queue spinning vastly improves performance of
292 * heavily contended queues. And so long as it is relatively
293 * brief and "quiet", spinning does not much impact performance
294 * of less-contended queues. During spins threads check their
295 * interrupt status and generate a thread-local random number
296 * to decide to occasionally perform a Thread.yield. While
297 * yield has underdefined specs, we assume that might it help,
298 * and will not hurt in limiting impact of spinning on busy
299 * systems. We also use smaller (1/2) spins for nodes that are
300 * not known to be front but whose predecessors have not
301 * blocked -- these "chained" spins avoid artifacts of
302 * front-of-queue rules which otherwise lead to alternating
303 * nodes spinning vs blocking. Further, front threads that
304 * represent phase changes (from data to request node or vice
305 * versa) compared to their predecessors receive additional
306 * chained spins, reflecting longer paths typically required to
307 * unblock threads during phase changes.
308 *
309 *
310 * ** Unlinking removed interior nodes **
311 *
312 * In addition to minimizing garbage retention via self-linking
313 * described above, we also unlink removed interior nodes. These
314 * may arise due to timed out or interrupted waits, or calls to
315 * remove(x) or Iterator.remove. Normally, given a node that was
316 * at one time known to be the predecessor of some node s that is
317 * to be removed, we can unsplice s by CASing the next field of
318 * its predecessor if it still points to s (otherwise s must
319 * already have been removed or is now offlist). But there are two
320 * situations in which we cannot guarantee to make node s
321 * unreachable in this way: (1) If s is the trailing node of list
322 * (i.e., with null next), then it is pinned as the target node
323 * for appends, so can only be removed later after other nodes are
324 * appended. (2) We cannot necessarily unlink s given a
325 * predecessor node that is matched (including the case of being
326 * cancelled): the predecessor may already be unspliced, in which
327 * case some previous reachable node may still point to s.
328 * (For further explanation see Herlihy & Shavit "The Art of
329 * Multiprocessor Programming" chapter 9). Although, in both
330 * cases, we can rule out the need for further action if either s
331 * or its predecessor are (or can be made to be) at, or fall off
332 * from, the head of list.
333 *
334 * Without taking these into account, it would be possible for an
335 * unbounded number of supposedly removed nodes to remain
336 * reachable. Situations leading to such buildup are uncommon but
337 * can occur in practice; for example when a series of short timed
338 * calls to poll repeatedly time out but never otherwise fall off
339 * the list because of an untimed call to take at the front of the
340 * queue.
341 *
342 * When these cases arise, rather than always retraversing the
343 * entire list to find an actual predecessor to unlink (which
344 * won't help for case (1) anyway), we record a conservative
345 * estimate of possible unsplice failures (in "sweepVotes").
346 * We trigger a full sweep when the estimate exceeds a threshold
347 * ("SWEEP_THRESHOLD") indicating the maximum number of estimated
348 * removal failures to tolerate before sweeping through, unlinking
349 * cancelled nodes that were not unlinked upon initial removal.
350 * We perform sweeps by the thread hitting threshold (rather than
351 * background threads or by spreading work to other threads)
352 * because in the main contexts in which removal occurs, the
353 * caller is already timed-out, cancelled, or performing a
354 * potentially O(n) operation (e.g. remove(x)), none of which are
355 * time-critical enough to warrant the overhead that alternatives
356 * would impose on other threads.
357 *
358 * Because the sweepVotes estimate is conservative, and because
359 * nodes become unlinked "naturally" as they fall off the head of
360 * the queue, and because we allow votes to accumulate even while
361 * sweeps are in progress, there are typically significantly fewer
362 * such nodes than estimated. Choice of a threshold value
363 * balances the likelihood of wasted effort and contention, versus
364 * providing a worst-case bound on retention of interior nodes in
365 * quiescent queues. The value defined below was chosen
366 * empirically to balance these under various timeout scenarios.
367 *
368 * Note that we cannot self-link unlinked interior nodes during
369 * sweeps. However, the associated garbage chains terminate when
370 * some successor ultimately falls off the head of the list and is
371 * self-linked.
372 */
373
374 /** True if on multiprocessor */
375 private static final boolean MP =
376 Runtime.getRuntime().availableProcessors() > 1;
377
378 /**
379 * The number of times to spin (with randomly interspersed calls
380 * to Thread.yield) on multiprocessor before blocking when a node
381 * is apparently the first waiter in the queue. See above for
382 * explanation. Must be a power of two. The value is empirically
383 * derived -- it works pretty well across a variety of processors,
384 * numbers of CPUs, and OSes.
385 */
386 private static final int FRONT_SPINS = 1 << 7;
387
388 /**
389 * The number of times to spin before blocking when a node is
390 * preceded by another node that is apparently spinning. Also
391 * serves as an increment to FRONT_SPINS on phase changes, and as
392 * base average frequency for yielding during spins. Must be a
393 * power of two.
394 */
395 private static final int CHAINED_SPINS = FRONT_SPINS >>> 1;
396
397 /**
398 * The maximum number of estimated removal failures (sweepVotes)
399 * to tolerate before sweeping through the queue unlinking
400 * cancelled nodes that were not unlinked upon initial
401 * removal. See above for explanation. The value must be at least
402 * two to avoid useless sweeps when removing trailing nodes.
403 */
404 static final int SWEEP_THRESHOLD = 32;
405
406 /**
407 * Queue nodes. Uses Object, not E, for items to allow forgetting
408 * them after use. Relies heavily on Unsafe mechanics to minimize
409 * unnecessary ordering constraints: Writes that are intrinsically
410 * ordered wrt other accesses or CASes use simple relaxed forms.
411 */
412 static final class Node {
413 final boolean isData; // false if this is a request node
414 volatile Object item; // initially non-null if isData; CASed to match
415 volatile Node next;
416 volatile Thread waiter; // null until waiting
417
418 // CAS methods for fields
419 final boolean casNext(Node cmp, Node val) {
420 return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);
421 }
422
423 final boolean casItem(Object cmp, Object val) {
424 // assert cmp == null || cmp.getClass() != Node.class;
425 return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val);
426 }
427
428 /**
429 * Constructs a new node. Uses relaxed write because item can
430 * only be seen after publication via casNext.
431 */
432 Node(Object item, boolean isData) {
433 UNSAFE.putObject(this, itemOffset, item); // relaxed write
434 this.isData = isData;
435 }
436
437 /**
438 * Links node to itself to avoid garbage retention. Called
439 * only after CASing head field, so uses relaxed write.
440 */
441 final void forgetNext() {
442 UNSAFE.putObject(this, nextOffset, this);
443 }
444
445 /**
446 * Sets item to self and waiter to null, to avoid garbage
447 * retention after matching or cancelling. Uses relaxed writes
448 * because order is already constrained in the only calling
449 * contexts: item is forgotten only after volatile/atomic
450 * mechanics that extract items. Similarly, clearing waiter
451 * follows either CAS or return from park (if ever parked;
452 * else we don't care).
453 */
454 final void forgetContents() {
455 UNSAFE.putObject(this, itemOffset, this);
456 UNSAFE.putObject(this, waiterOffset, null);
457 }
458
459 /**
460 * Returns true if this node has been matched, including the
461 * case of artificial matches due to cancellation.
462 */
463 final boolean isMatched() {
464 Object x = item;
465 return (x == this) || ((x == null) == isData);
466 }
467
468 /**
469 * Returns true if this is an unmatched request node.
470 */
471 final boolean isUnmatchedRequest() {
472 return !isData && item == null;
473 }
474
475 /**
476 * Returns true if a node with the given mode cannot be
477 * appended to this node because this node is unmatched and
478 * has opposite data mode.
479 */
480 final boolean cannotPrecede(boolean haveData) {
481 boolean d = isData;
482 Object x;
483 return d != haveData && (x = item) != this && (x != null) == d;
484 }
485
486 /**
487 * Tries to artificially match a data node -- used by remove.
488 */
489 final boolean tryMatchData() {
490 // assert isData;
491 Object x = item;
492 if (x != null && x != this && casItem(x, null)) {
493 LockSupport.unpark(waiter);
494 return true;
495 }
496 return false;
497 }
498
499 // Unsafe mechanics
500 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
501 private static final long nextOffset =
502 objectFieldOffset(UNSAFE, "next", Node.class);
503 private static final long itemOffset =
504 objectFieldOffset(UNSAFE, "item", Node.class);
505 private static final long waiterOffset =
506 objectFieldOffset(UNSAFE, "waiter", Node.class);
507
508 private static final long serialVersionUID = -3375979862319811754L;
509 }
510
511 /** head of the queue; null until first enqueue */
512 transient volatile Node head;
513
514 /** tail of the queue; null until first append */
515 private transient volatile Node tail;
516
517 /** The number of apparent failures to unsplice removed nodes */
518 private transient volatile int sweepVotes;
519
520 // CAS methods for fields
521 private boolean casTail(Node cmp, Node val) {
522 return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
523 }
524
525 private boolean casHead(Node cmp, Node val) {
526 return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
527 }
528
529 private boolean casSweepVotes(int cmp, int val) {
530 return UNSAFE.compareAndSwapInt(this, sweepVotesOffset, cmp, val);
531 }
532
533 /*
534 * Possible values for "how" argument in xfer method.
535 */
536 private static final int NOW = 0; // for untimed poll, tryTransfer
537 private static final int ASYNC = 1; // for offer, put, add
538 private static final int SYNC = 2; // for transfer, take
539 private static final int TIMED = 3; // for timed poll, tryTransfer
540
541 @SuppressWarnings("unchecked")
542 static <E> E cast(Object item) {
543 // assert item == null || item.getClass() != Node.class;
544 return (E) item;
545 }
546
547 /**
548 * Implements all queuing methods. See above for explanation.
549 *
550 * @param e the item or null for take
551 * @param haveData true if this is a put, else a take
552 * @param how NOW, ASYNC, SYNC, or TIMED
553 * @param nanos timeout in nanosecs, used only if mode is TIMED
554 * @return an item if matched, else e
555 * @throws NullPointerException if haveData mode but e is null
556 */
557 private E xfer(E e, boolean haveData, int how, long nanos) {
558 if (haveData && (e == null))
559 throw new NullPointerException();
560 Node s = null; // the node to append, if needed
561
562 retry: for (;;) { // restart on append race
563
564 for (Node h = head, p = h; p != null;) { // find & match first node
565 boolean isData = p.isData;
566 Object item = p.item;
567 if (item != p && (item != null) == isData) { // unmatched
568 if (isData == haveData) // can't match
569 break;
570 if (p.casItem(item, e)) { // match
571 for (Node q = p; q != h;) {
572 Node n = q.next; // update by 2 unless singleton
573 if (head == h && casHead(h, n == null? q : n)) {
574 h.forgetNext();
575 break;
576 } // advance and retry
577 if ((h = head) == null ||
578 (q = h.next) == null || !q.isMatched())
579 break; // unless slack < 2
580 }
581 LockSupport.unpark(p.waiter);
582 return this.<E>cast(item);
583 }
584 }
585 Node n = p.next;
586 p = (p != n) ? n : (h = head); // Use head if p offlist
587 }
588
589 if (how != NOW) { // No matches available
590 if (s == null)
591 s = new Node(e, haveData);
592 Node pred = tryAppend(s, haveData);
593 if (pred == null)
594 continue retry; // lost race vs opposite mode
595 if (how != ASYNC)
596 return awaitMatch(s, pred, e, (how == TIMED), nanos);
597 }
598 return e; // not waiting
599 }
600 }
601
602 /**
603 * Tries to append node s as tail.
604 *
605 * @param s the node to append
606 * @param haveData true if appending in data mode
607 * @return null on failure due to losing race with append in
608 * different mode, else s's predecessor, or s itself if no
609 * predecessor
610 */
611 private Node tryAppend(Node s, boolean haveData) {
612 for (Node t = tail, p = t;;) { // move p to last node and append
613 Node n, u; // temps for reads of next & tail
614 if (p == null && (p = head) == null) {
615 if (casHead(null, s))
616 return s; // initialize
617 }
618 else if (p.cannotPrecede(haveData))
619 return null; // lost race vs opposite mode
620 else if ((n = p.next) != null) // not last; keep traversing
621 p = p != t && t != (u = tail) ? (t = u) : // stale tail
622 (p != n) ? n : null; // restart if off list
623 else if (!p.casNext(null, s))
624 p = p.next; // re-read on CAS failure
625 else {
626 if (p != t) { // update if slack now >= 2
627 while ((tail != t || !casTail(t, s)) &&
628 (t = tail) != null &&
629 (s = t.next) != null && // advance and retry
630 (s = s.next) != null && s != t);
631 }
632 return p;
633 }
634 }
635 }
636
637 /**
638 * Spins/yields/blocks until node s is matched or caller gives up.
639 *
640 * @param s the waiting node
641 * @param pred the predecessor of s, or s itself if it has no
642 * predecessor, or null if unknown (the null case does not occur
643 * in any current calls but may in possible future extensions)
644 * @param e the comparison value for checking match
645 * @param timed if true, wait only until timeout elapses
646 * @param nanos timeout in nanosecs, used only if timed is true
647 * @return matched item, or e if unmatched on interrupt or timeout
648 */
649 private E awaitMatch(Node s, Node pred, E e, boolean timed, long nanos) {
650 long lastTime = timed ? System.nanoTime() : 0L;
651 Thread w = Thread.currentThread();
652 int spins = -1; // initialized after first item and cancel checks
653 ThreadLocalRandom randomYields = null; // bound if needed
654
655 for (;;) {
656 Object item = s.item;
657 if (item != e) { // matched
658 // assert item != s;
659 s.forgetContents(); // avoid garbage
660 return this.<E>cast(item);
661 }
662 if ((w.isInterrupted() || (timed && nanos <= 0)) &&
663 s.casItem(e, s)) { // cancel
664 unsplice(pred, s);
665 return e;
666 }
667
668 if (spins < 0) { // establish spins at/near front
669 if ((spins = spinsFor(pred, s.isData)) > 0)
670 randomYields = ThreadLocalRandom.current();
671 }
672 else if (spins > 0) { // spin
673 --spins;
674 if (randomYields.nextInt(CHAINED_SPINS) == 0)
675 Thread.yield(); // occasionally yield
676 }
677 else if (s.waiter == null) {
678 s.waiter = w; // request unpark then recheck
679 }
680 else if (timed) {
681 long now = System.nanoTime();
682 if ((nanos -= now - lastTime) > 0)
683 LockSupport.parkNanos(this, nanos);
684 lastTime = now;
685 }
686 else {
687 LockSupport.park(this);
688 }
689 }
690 }
691
692 /**
693 * Returns spin/yield value for a node with given predecessor and
694 * data mode. See above for explanation.
695 */
696 private static int spinsFor(Node pred, boolean haveData) {
697 if (MP && pred != null) {
698 if (pred.isData != haveData) // phase change
699 return FRONT_SPINS + CHAINED_SPINS;
700 if (pred.isMatched()) // probably at front
701 return FRONT_SPINS;
702 if (pred.waiter == null) // pred apparently spinning
703 return CHAINED_SPINS;
704 }
705 return 0;
706 }
707
708 /* -------------- Traversal methods -------------- */
709
710 /**
711 * Returns the successor of p, or the head node if p.next has been
712 * linked to self, which will only be true if traversing with a
713 * stale pointer that is now off the list.
714 */
715 final Node succ(Node p) {
716 Node next = p.next;
717 return (p == next) ? head : next;
718 }
719
720 /**
721 * Returns the first unmatched node of the given mode, or null if
722 * none. Used by methods isEmpty, hasWaitingConsumer.
723 */
724 private Node firstOfMode(boolean isData) {
725 for (Node p = head; p != null; p = succ(p)) {
726 if (!p.isMatched())
727 return (p.isData == isData) ? p : null;
728 }
729 return null;
730 }
731
732 /**
733 * Returns the item in the first unmatched node with isData; or
734 * null if none. Used by peek.
735 */
736 private E firstDataItem() {
737 for (Node p = head; p != null; p = succ(p)) {
738 Object item = p.item;
739 if (p.isData) {
740 if (item != null && item != p)
741 return this.<E>cast(item);
742 }
743 else if (item == null)
744 return null;
745 }
746 return null;
747 }
748
749 /**
750 * Traverses and counts unmatched nodes of the given mode.
751 * Used by methods size and getWaitingConsumerCount.
752 */
753 private int countOfMode(boolean data) {
754 int count = 0;
755 for (Node p = head; p != null; ) {
756 if (!p.isMatched()) {
757 if (p.isData != data)
758 return 0;
759 if (++count == Integer.MAX_VALUE) // saturated
760 break;
761 }
762 Node n = p.next;
763 if (n != p)
764 p = n;
765 else {
766 count = 0;
767 p = head;
768 }
769 }
770 return count;
771 }
772
773 final class Itr implements Iterator<E> {
774 private Node nextNode; // next node to return item for
775 private E nextItem; // the corresponding item
776 private Node lastRet; // last returned node, to support remove
777 private Node lastPred; // predecessor to unlink lastRet
778
779 /**
780 * Moves to next node after prev, or first node if prev null.
781 */
782 private void advance(Node prev) {
783 lastPred = lastRet;
784 lastRet = prev;
785 for (Node p = (prev == null) ? head : succ(prev);
786 p != null; p = succ(p)) {
787 Object item = p.item;
788 if (p.isData) {
789 if (item != null && item != p) {
790 nextItem = LinkedTransferQueue.this.<E>cast(item);
791 nextNode = p;
792 return;
793 }
794 }
795 else if (item == null)
796 break;
797 }
798 nextNode = null;
799 }
800
801 Itr() {
802 advance(null);
803 }
804
805 public final boolean hasNext() {
806 return nextNode != null;
807 }
808
809 public final E next() {
810 Node p = nextNode;
811 if (p == null) throw new NoSuchElementException();
812 E e = nextItem;
813 advance(p);
814 return e;
815 }
816
817 public final void remove() {
818 Node p = lastRet;
819 if (p == null) throw new IllegalStateException();
820 if (p.tryMatchData())
821 unsplice(lastPred, p);
822 }
823 }
824
825 /* -------------- Removal methods -------------- */
826
827 /**
828 * Unsplices (now or later) the given deleted/cancelled node with
829 * the given predecessor.
830 *
831 * @param pred a node that was at one time known to be the
832 * predecessor of s, or null or s itself if s is/was at head
833 * @param s the node to be unspliced
834 */
835 final void unsplice(Node pred, Node s) {
836 s.forgetContents(); // forget unneeded fields
837 /*
838 * See above for rationale. Briefly: if pred still points to
839 * s, try to unlink s. If s cannot be unlinked, because it is
840 * trailing node or pred might be unlinked, and neither pred
841 * nor s are head or offlist, add to sweepVotes, and if enough
842 * votes have accumulated, sweep.
843 */
844 if (pred != null && pred != s && pred.next == s) {
845 Node n = s.next;
846 if (n == null ||
847 (n != s && pred.casNext(s, n) && pred.isMatched())) {
848 for (;;) { // check if at, or could be, head
849 Node h = head;
850 if (h == pred || h == s || h == null)
851 return; // at head or list empty
852 if (!h.isMatched())
853 break;
854 Node hn = h.next;
855 if (hn == null)
856 return; // now empty
857 if (hn != h && casHead(h, hn))
858 h.forgetNext(); // advance head
859 }
860 if (pred.next != pred && s.next != s) { // recheck if offlist
861 for (;;) { // sweep now if enough votes
862 int v = sweepVotes;
863 if (v < SWEEP_THRESHOLD) {
864 if (casSweepVotes(v, v + 1))
865 break;
866 }
867 else if (casSweepVotes(v, 0)) {
868 sweep();
869 break;
870 }
871 }
872 }
873 }
874 }
875 }
876
877 /**
878 * Unlinks matched (typically cancelled) nodes encountered in a
879 * traversal from head.
880 */
881 private void sweep() {
882 for (Node p = head, s, n; p != null && (s = p.next) != null; ) {
883 if (p == s) // stale
884 p = head;
885 else if (!s.isMatched())
886 p = s;
887 else if ((n = s.next) == null) // trailing node is pinned
888 break;
889 else
890 p.casNext(s, n);
891 }
892 }
893
894 /**
895 * Main implementation of remove(Object)
896 */
897 private boolean findAndRemove(Object e) {
898 if (e != null) {
899 for (Node pred = null, p = head; p != null; ) {
900 Object item = p.item;
901 if (p.isData) {
902 if (item != null && item != p && e.equals(item) &&
903 p.tryMatchData()) {
904 unsplice(pred, p);
905 return true;
906 }
907 }
908 else if (item == null)
909 break;
910 pred = p;
911 if ((p = p.next) == pred) { // stale
912 pred = null;
913 p = head;
914 }
915 }
916 }
917 return false;
918 }
919
920
921 /**
922 * Creates an initially empty {@code LinkedTransferQueue}.
923 */
924 public LinkedTransferQueue() {
925 }
926
927 /**
928 * Creates a {@code LinkedTransferQueue}
929 * initially containing the elements of the given collection,
930 * added in traversal order of the collection's iterator.
931 *
932 * @param c the collection of elements to initially contain
933 * @throws NullPointerException if the specified collection or any
934 * of its elements are null
935 */
936 public LinkedTransferQueue(Collection<? extends E> c) {
937 this();
938 addAll(c);
939 }
940
941 /**
942 * Inserts the specified element at the tail of this queue.
943 * As the queue is unbounded, this method will never block.
944 *
945 * @throws NullPointerException if the specified element is null
946 */
947 public void put(E e) {
948 xfer(e, true, ASYNC, 0);
949 }
950
951 /**
952 * Inserts the specified element at the tail of this queue.
953 * As the queue is unbounded, this method will never block or
954 * return {@code false}.
955 *
956 * @return {@code true} (as specified by
957 * {@link BlockingQueue#offer(Object,long,TimeUnit) BlockingQueue.offer})
958 * @throws NullPointerException if the specified element is null
959 */
960 public boolean offer(E e, long timeout, TimeUnit unit) {
961 xfer(e, true, ASYNC, 0);
962 return true;
963 }
964
965 /**
966 * Inserts the specified element at the tail of this queue.
967 * As the queue is unbounded, this method will never return {@code false}.
968 *
969 * @return {@code true} (as specified by
970 * {@link BlockingQueue#offer(Object) BlockingQueue.offer})
971 * @throws NullPointerException if the specified element is null
972 */
973 public boolean offer(E e) {
974 xfer(e, true, ASYNC, 0);
975 return true;
976 }
977
978 /**
979 * Inserts the specified element at the tail of this queue.
980 * As the queue is unbounded, this method will never throw
981 * {@link IllegalStateException} or return {@code false}.
982 *
983 * @return {@code true} (as specified by {@link Collection#add})
984 * @throws NullPointerException if the specified element is null
985 */
986 public boolean add(E e) {
987 xfer(e, true, ASYNC, 0);
988 return true;
989 }
990
991 /**
992 * Transfers the element to a waiting consumer immediately, if possible.
993 *
994 * <p>More precisely, transfers the specified element immediately
995 * if there exists a consumer already waiting to receive it (in
996 * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
997 * otherwise returning {@code false} without enqueuing the element.
998 *
999 * @throws NullPointerException if the specified element is null
1000 */
1001 public boolean tryTransfer(E e) {
1002 return xfer(e, true, NOW, 0) == null;
1003 }
1004
1005 /**
1006 * Transfers the element to a consumer, waiting if necessary to do so.
1007 *
1008 * <p>More precisely, transfers the specified element immediately
1009 * if there exists a consumer already waiting to receive it (in
1010 * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1011 * else inserts the specified element at the tail of this queue
1012 * and waits until the element is received by a consumer.
1013 *
1014 * @throws NullPointerException if the specified element is null
1015 */
1016 public void transfer(E e) throws InterruptedException {
1017 if (xfer(e, true, SYNC, 0) != null) {
1018 Thread.interrupted(); // failure possible only due to interrupt
1019 throw new InterruptedException();
1020 }
1021 }
1022
1023 /**
1024 * Transfers the element to a consumer if it is possible to do so
1025 * before the timeout elapses.
1026 *
1027 * <p>More precisely, transfers the specified element immediately
1028 * if there exists a consumer already waiting to receive it (in
1029 * {@link #take} or timed {@link #poll(long,TimeUnit) poll}),
1030 * else inserts the specified element at the tail of this queue
1031 * and waits until the element is received by a consumer,
1032 * returning {@code false} if the specified wait time elapses
1033 * before the element can be transferred.
1034 *
1035 * @throws NullPointerException if the specified element is null
1036 */
1037 public boolean tryTransfer(E e, long timeout, TimeUnit unit)
1038 throws InterruptedException {
1039 if (xfer(e, true, TIMED, unit.toNanos(timeout)) == null)
1040 return true;
1041 if (!Thread.interrupted())
1042 return false;
1043 throw new InterruptedException();
1044 }
1045
1046 public E take() throws InterruptedException {
1047 E e = xfer(null, false, SYNC, 0);
1048 if (e != null)
1049 return e;
1050 Thread.interrupted();
1051 throw new InterruptedException();
1052 }
1053
1054 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
1055 E e = xfer(null, false, TIMED, unit.toNanos(timeout));
1056 if (e != null || !Thread.interrupted())
1057 return e;
1058 throw new InterruptedException();
1059 }
1060
1061 public E poll() {
1062 return xfer(null, false, NOW, 0);
1063 }
1064
1065 /**
1066 * @throws NullPointerException {@inheritDoc}
1067 * @throws IllegalArgumentException {@inheritDoc}
1068 */
1069 public int drainTo(Collection<? super E> c) {
1070 if (c == null)
1071 throw new NullPointerException();
1072 if (c == this)
1073 throw new IllegalArgumentException();
1074 int n = 0;
1075 E e;
1076 while ( (e = poll()) != null) {
1077 c.add(e);
1078 ++n;
1079 }
1080 return n;
1081 }
1082
1083 /**
1084 * @throws NullPointerException {@inheritDoc}
1085 * @throws IllegalArgumentException {@inheritDoc}
1086 */
1087 public int drainTo(Collection<? super E> c, int maxElements) {
1088 if (c == null)
1089 throw new NullPointerException();
1090 if (c == this)
1091 throw new IllegalArgumentException();
1092 int n = 0;
1093 E e;
1094 while (n < maxElements && (e = poll()) != null) {
1095 c.add(e);
1096 ++n;
1097 }
1098 return n;
1099 }
1100
1101 /**
1102 * Returns an iterator over the elements in this queue in proper
1103 * sequence, from head to tail.
1104 *
1105 * <p>The returned iterator is a "weakly consistent" iterator that
1106 * will never throw
1107 * {@link ConcurrentModificationException ConcurrentModificationException},
1108 * and guarantees to traverse elements as they existed upon
1109 * construction of the iterator, and may (but is not guaranteed
1110 * to) reflect any modifications subsequent to construction.
1111 *
1112 * @return an iterator over the elements in this queue in proper sequence
1113 */
1114 public Iterator<E> iterator() {
1115 return new Itr();
1116 }
1117
1118 public E peek() {
1119 return firstDataItem();
1120 }
1121
1122 /**
1123 * Returns {@code true} if this queue contains no elements.
1124 *
1125 * @return {@code true} if this queue contains no elements
1126 */
1127 public boolean isEmpty() {
1128 for (Node p = head; p != null; p = succ(p)) {
1129 if (!p.isMatched())
1130 return !p.isData;
1131 }
1132 return true;
1133 }
1134
1135 public boolean hasWaitingConsumer() {
1136 return firstOfMode(false) != null;
1137 }
1138
1139 /**
1140 * Returns the number of elements in this queue. If this queue
1141 * contains more than {@code Integer.MAX_VALUE} elements, returns
1142 * {@code Integer.MAX_VALUE}.
1143 *
1144 * <p>Beware that, unlike in most collections, this method is
1145 * <em>NOT</em> a constant-time operation. Because of the
1146 * asynchronous nature of these queues, determining the current
1147 * number of elements requires an O(n) traversal.
1148 *
1149 * @return the number of elements in this queue
1150 */
1151 public int size() {
1152 return countOfMode(true);
1153 }
1154
1155 public int getWaitingConsumerCount() {
1156 return countOfMode(false);
1157 }
1158
1159 /**
1160 * Removes a single instance of the specified element from this queue,
1161 * if it is present. More formally, removes an element {@code e} such
1162 * that {@code o.equals(e)}, if this queue contains one or more such
1163 * elements.
1164 * Returns {@code true} if this queue contained the specified element
1165 * (or equivalently, if this queue changed as a result of the call).
1166 *
1167 * @param o element to be removed from this queue, if present
1168 * @return {@code true} if this queue changed as a result of the call
1169 */
1170 public boolean remove(Object o) {
1171 return findAndRemove(o);
1172 }
1173
1174 /**
1175 * Always returns {@code Integer.MAX_VALUE} because a
1176 * {@code LinkedTransferQueue} is not capacity constrained.
1177 *
1178 * @return {@code Integer.MAX_VALUE} (as specified by
1179 * {@link BlockingQueue#remainingCapacity()})
1180 */
1181 public int remainingCapacity() {
1182 return Integer.MAX_VALUE;
1183 }
1184
1185 /**
1186 * Saves the state to a stream (that is, serializes it).
1187 *
1188 * @serialData All of the elements (each an {@code E}) in
1189 * the proper order, followed by a null
1190 * @param s the stream
1191 */
1192 private void writeObject(java.io.ObjectOutputStream s)
1193 throws java.io.IOException {
1194 s.defaultWriteObject();
1195 for (E e : this)
1196 s.writeObject(e);
1197 // Use trailing null as sentinel
1198 s.writeObject(null);
1199 }
1200
1201 /**
1202 * Reconstitutes the Queue instance from a stream (that is,
1203 * deserializes it).
1204 *
1205 * @param s the stream
1206 */
1207 private void readObject(java.io.ObjectInputStream s)
1208 throws java.io.IOException, ClassNotFoundException {
1209 s.defaultReadObject();
1210 for (;;) {
1211 @SuppressWarnings("unchecked") E item = (E) s.readObject();
1212 if (item == null)
1213 break;
1214 else
1215 offer(item);
1216 }
1217 }
1218
1219 // Unsafe mechanics
1220
1221 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
1222 private static final long headOffset =
1223 objectFieldOffset(UNSAFE, "head", LinkedTransferQueue.class);
1224 private static final long tailOffset =
1225 objectFieldOffset(UNSAFE, "tail", LinkedTransferQueue.class);
1226 private static final long sweepVotesOffset =
1227 objectFieldOffset(UNSAFE, "sweepVotes", LinkedTransferQueue.class);
1228
1229 static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
1230 String field, Class<?> klazz) {
1231 try {
1232 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1233 } catch (NoSuchFieldException e) {
1234 // Convert Exception to corresponding Error
1235 NoSuchFieldError error = new NoSuchFieldError(field);
1236 error.initCause(e);
1237 throw error;
1238 }
1239 }
1240 }