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