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