ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java
Revision: 1.135
Committed: Fri Mar 18 16:00:15 2022 UTC (2 years, 2 months ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.134: +8 -6 lines
Log Message:
Faster queue check

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 package java.util.concurrent.locks;
8
9 import java.util.ArrayList;
10 import java.util.Collection;
11 import java.util.Date;
12 import java.util.concurrent.TimeUnit;
13 import java.util.concurrent.ForkJoinPool;
14 import java.util.concurrent.RejectedExecutionException;
15 import jdk.internal.misc.Unsafe;
16
17 /**
18 * A version of {@link AbstractQueuedSynchronizer} in
19 * which synchronization state is maintained as a {@code long}.
20 * This class has exactly the same structure, properties, and methods
21 * as {@code AbstractQueuedSynchronizer} with the exception
22 * that all state-related parameters and results are defined
23 * as {@code long} rather than {@code int}. This class
24 * may be useful when creating synchronizers such as
25 * multilevel locks and barriers that require
26 * 64 bits of state.
27 *
28 * <p>See {@link AbstractQueuedSynchronizer} for usage
29 * notes and examples.
30 *
31 * @since 1.6
32 * @author Doug Lea
33 */
34 public abstract class AbstractQueuedLongSynchronizer
35 extends AbstractOwnableSynchronizer
36 implements java.io.Serializable {
37
38 private static final long serialVersionUID = 7373984972572414692L;
39
40 /**
41 * Constructor for subclasses to call.
42 */
43 public AbstractQueuedLongSynchronizer() {}
44
45 /*
46 * To keep sources in sync, the remainder of this source file is
47 * exactly cloned from AbstractQueuedSynchronizer, replacing class
48 * name and changing ints related with sync state to longs. Please
49 * keep it that way.
50 */
51
52 // Node status bits, also used as argument and return values
53 static final int WAITING = 1; // must be 1
54 static final int CANCELLED = 0x80000000; // must be negative
55 static final int COND = 2; // in a condition wait
56
57 /** CLH Nodes */
58 abstract static class Node {
59 volatile Node prev; // initially attached via casTail
60 volatile Node next; // visibly nonnull when signallable
61 Thread waiter; // visibly nonnull when enqueued
62 volatile int status; // written by owner, atomic bit ops by others
63
64 // methods for atomic operations
65 final boolean casPrev(Node c, Node v) { // for cleanQueue
66 return U.weakCompareAndSetReference(this, PREV, c, v);
67 }
68 final boolean casNext(Node c, Node v) { // for cleanQueue
69 return U.weakCompareAndSetReference(this, NEXT, c, v);
70 }
71 final int getAndUnsetStatus(int v) { // for signalling
72 return U.getAndBitwiseAndInt(this, STATUS, ~v);
73 }
74 final void setPrevRelaxed(Node p) { // for off-queue assignment
75 U.putReference(this, PREV, p);
76 }
77 final void setStatusRelaxed(int s) { // for off-queue assignment
78 U.putInt(this, STATUS, s);
79 }
80 final void clearStatus() { // for reducing unneeded signals
81 U.putIntOpaque(this, STATUS, 0);
82 }
83
84 private static final long STATUS
85 = U.objectFieldOffset(Node.class, "status");
86 private static final long NEXT
87 = U.objectFieldOffset(Node.class, "next");
88 private static final long PREV
89 = U.objectFieldOffset(Node.class, "prev");
90 }
91
92 // Concrete classes tagged by type
93 static final class ExclusiveNode extends Node { }
94 static final class SharedNode extends Node { }
95
96 static final class ConditionNode extends Node
97 implements ForkJoinPool.ManagedBlocker {
98 ConditionNode nextWaiter; // link to next waiting node
99
100 /**
101 * Allows Conditions to be used in ForkJoinPools without
102 * risking fixed pool exhaustion. This is usable only for
103 * untimed Condition waits, not timed versions.
104 */
105 public final boolean isReleasable() {
106 return status <= 1 || Thread.currentThread().isInterrupted();
107 }
108
109 public final boolean block() {
110 while (!isReleasable()) LockSupport.park();
111 return true;
112 }
113 }
114
115 /**
116 * Head of the wait queue, lazily initialized.
117 */
118 private transient volatile Node head;
119
120 /**
121 * Tail of the wait queue. After initialization, modified only via casTail.
122 */
123 private transient volatile Node tail;
124
125 /**
126 * The synchronization state.
127 */
128 private volatile long state;
129
130 /**
131 * Returns the current value of synchronization state.
132 * This operation has memory semantics of a {@code volatile} read.
133 * @return current state value
134 */
135 protected final long getState() {
136 return state;
137 }
138
139 /**
140 * Sets the value of synchronization state.
141 * This operation has memory semantics of a {@code volatile} write.
142 * @param newState the new state value
143 */
144 protected final void setState(long newState) {
145 state = newState;
146 }
147
148 /**
149 * Atomically sets synchronization state to the given updated
150 * value if the current state value equals the expected value.
151 * This operation has memory semantics of a {@code volatile} read
152 * and write.
153 *
154 * @param expect the expected value
155 * @param update the new value
156 * @return {@code true} if successful. False return indicates that the actual
157 * value was not equal to the expected value.
158 */
159 protected final boolean compareAndSetState(long expect, long update) {
160 return U.compareAndSetLong(this, STATE, expect, update);
161 }
162
163 // Queuing utilities
164
165 private boolean casTail(Node c, Node v) {
166 return U.compareAndSetReference(this, TAIL, c, v);
167 }
168
169 /** tries once to CAS a new dummy node for head */
170 private void tryInitializeHead() {
171 Node h = new ExclusiveNode();
172 if (U.compareAndSetReference(this, HEAD, null, h))
173 tail = h;
174 }
175
176 /**
177 * Enqueues the node unless null. (Currently used only for
178 * ConditionNodes; other cases are interleaved with acquires.)
179 */
180 final void enqueue(Node node) {
181 if (node != null) {
182 for (;;) {
183 Node t = tail;
184 node.setPrevRelaxed(t); // avoid unnecessary fence
185 if (t == null) // initialize
186 tryInitializeHead();
187 else if (casTail(t, node)) {
188 t.next = node;
189 if (t.status < 0) // wake up to clean link
190 LockSupport.unpark(node.waiter);
191 break;
192 }
193 }
194 }
195 }
196
197 /** Returns true if node is found in traversal from tail */
198 final boolean isEnqueued(Node node) {
199 for (Node t = tail; t != null; t = t.prev)
200 if (t == node)
201 return true;
202 return false;
203 }
204
205 /**
206 * Wakes up the successor of given node, if one exists, and unsets its
207 * WAITING status to avoid park race. This may fail to wake up an
208 * eligible thread when one or more have been cancelled, but
209 * cancelAcquire ensures liveness.
210 */
211 private static void signalNext(Node h) {
212 Node s;
213 if (h != null && (s = h.next) != null && s.status != 0) {
214 s.getAndUnsetStatus(WAITING);
215 LockSupport.unpark(s.waiter);
216 }
217 }
218
219 /** Wakes up the given node if in shared mode */
220 private static void signalNextIfShared(Node h) {
221 Node s;
222 if (h != null && (s = h.next) != null &&
223 (s instanceof SharedNode) && s.status != 0) {
224 s.getAndUnsetStatus(WAITING);
225 LockSupport.unpark(s.waiter);
226 }
227 }
228
229 /**
230 * Main acquire method, invoked by all exported acquire methods.
231 *
232 * @param node null unless a reacquiring Condition
233 * @param arg the acquire argument
234 * @param shared true if shared mode else exclusive
235 * @param interruptible if abort and return negative on interrupt
236 * @param timed if true use timed waits
237 * @param time if timed, the System.nanoTime value to timeout
238 * @return positive if acquired, 0 if timed out, negative if interrupted
239 */
240 final int acquire(Node node, long arg, boolean shared,
241 boolean interruptible, boolean timed, long time) {
242 Thread current = Thread.currentThread();
243 byte spins = 0, postSpins = 0; // retries upon unpark of first thread
244 boolean interrupted = false, first = false;
245 Node pred = null; // predecessor of node when enqueued
246
247 /*
248 * Repeatedly:
249 * Check if node now first
250 * if so, ensure head stable, else ensure valid predecessor
251 * if node is first or not yet enqueued, try acquiring
252 * else if node not yet created, create it
253 * else if not yet enqueued, try once to enqueue
254 * else if woken from park, retry (up to postSpins times)
255 * else if WAITING status not set, set and retry
256 * else park and clear WAITING status, and check cancellation
257 */
258
259 for (;;) {
260 if (!first && (pred = (node == null) ? null : node.prev) != null &&
261 !(first = (head == pred))) {
262 if (pred.status < 0) {
263 cleanQueue(); // predecessor cancelled
264 continue;
265 } else if (pred.prev == null) {
266 Thread.onSpinWait(); // ensure serialization
267 continue;
268 }
269 }
270 if (first || pred == null) {
271 boolean acquired;
272 try {
273 if (shared)
274 acquired = (tryAcquireShared(arg) >= 0);
275 else
276 acquired = tryAcquire(arg);
277 } catch (Throwable ex) {
278 cancelAcquire(node, interrupted, false);
279 throw ex;
280 }
281 if (acquired) {
282 if (first) {
283 node.prev = null;
284 head = node;
285 pred.next = null;
286 node.waiter = null;
287 if (shared)
288 signalNextIfShared(node);
289 if (interrupted)
290 current.interrupt();
291 }
292 return 1;
293 }
294 }
295 if (node == null) { // allocate; retry before enqueue
296 if (shared)
297 node = new SharedNode();
298 else
299 node = new ExclusiveNode();
300 } else if (pred == null) { // try to enqueue
301 node.waiter = current;
302 Node t = tail;
303 node.setPrevRelaxed(t); // avoid unnecessary fence
304 if (t == null)
305 tryInitializeHead();
306 else if (!casTail(t, node))
307 node.setPrevRelaxed(null); // back out
308 else
309 t.next = node;
310 } else if (first && spins != 0) {
311 --spins; // reduce unfairness on rewaits
312 Thread.onSpinWait();
313 } else if (node.status == 0) {
314 node.status = WAITING; // enable signal and recheck
315 } else {
316 long nanos;
317 spins = postSpins = (byte)((postSpins << 1) | 1);
318 if (!timed)
319 LockSupport.park(this);
320 else if ((nanos = time - System.nanoTime()) > 0L)
321 LockSupport.parkNanos(this, nanos);
322 else
323 break;
324 node.clearStatus();
325 if ((interrupted |= Thread.interrupted()) && interruptible)
326 break;
327 }
328 }
329 return cancelAcquire(node, interrupted, interruptible);
330 }
331
332 /**
333 * Possibly repeatedly traverses from tail, unsplicing cancelled
334 * nodes until none are found.
335 */
336 private void cleanQueue() {
337 for (;;) { // restart point
338 for (Node q = tail, s = null, p, n;;) { // (p, q, s) triples
339 if (q == null || (p = q.prev) == null)
340 return; // end of list
341 if (s == null ? tail != q : (s.prev != q || s.status < 0))
342 break; // inconsistent
343 if (q.status < 0) { // cancelled
344 if ((s == null ? casTail(q, p) : s.casPrev(q, p)) &&
345 q.prev == p) {
346 p.casNext(q, s); // OK if fails
347 if (p.prev == null)
348 signalNext(p);
349 }
350 break;
351 }
352 if ((n = p.next) != q) { // help finish
353 if (n != null && q.prev == p) {
354 p.casNext(n, q);
355 if (p.prev == null)
356 signalNext(p);
357 }
358 break;
359 }
360 s = q;
361 q = q.prev;
362 }
363 }
364 }
365
366 /**
367 * Cancels an ongoing attempt to acquire.
368 *
369 * @param node the node (may be null if cancelled before enqueuing)
370 * @param interrupted true if thread interrupted
371 * @param interruptible if should report interruption vs reset
372 */
373 private int cancelAcquire(Node node, boolean interrupted,
374 boolean interruptible) {
375 if (node != null) {
376 node.waiter = null;
377 node.status = CANCELLED;
378 if (node.prev != null)
379 cleanQueue();
380 }
381 if (interrupted) {
382 if (interruptible)
383 return CANCELLED;
384 else
385 Thread.currentThread().interrupt();
386 }
387 return 0;
388 }
389
390 // Main exported methods
391
392 /**
393 * Attempts to acquire in exclusive mode. This method should query
394 * if the state of the object permits it to be acquired in the
395 * exclusive mode, and if so to acquire it.
396 *
397 * <p>This method is always invoked by the thread performing
398 * acquire. If this method reports failure, the acquire method
399 * may queue the thread, if it is not already queued, until it is
400 * signalled by a release from some other thread. This can be used
401 * to implement method {@link Lock#tryLock()}.
402 *
403 * <p>The default
404 * implementation throws {@link UnsupportedOperationException}.
405 *
406 * @param arg the acquire argument. This value is always the one
407 * passed to an acquire method, or is the value saved on entry
408 * to a condition wait. The value is otherwise uninterpreted
409 * and can represent anything you like.
410 * @return {@code true} if successful. Upon success, this object has
411 * been acquired.
412 * @throws IllegalMonitorStateException if acquiring would place this
413 * synchronizer in an illegal state. This exception must be
414 * thrown in a consistent fashion for synchronization to work
415 * correctly.
416 * @throws UnsupportedOperationException if exclusive mode is not supported
417 */
418 protected boolean tryAcquire(long arg) {
419 throw new UnsupportedOperationException();
420 }
421
422 /**
423 * Attempts to set the state to reflect a release in exclusive
424 * mode.
425 *
426 * <p>This method is always invoked by the thread performing release.
427 *
428 * <p>The default implementation throws
429 * {@link UnsupportedOperationException}.
430 *
431 * @param arg the release argument. This value is always the one
432 * passed to a release method, or the current state value upon
433 * entry to a condition wait. The value is otherwise
434 * uninterpreted and can represent anything you like.
435 * @return {@code true} if this object is now in a fully released
436 * state, so that any waiting threads may attempt to acquire;
437 * and {@code false} otherwise.
438 * @throws IllegalMonitorStateException if releasing would place this
439 * synchronizer in an illegal state. This exception must be
440 * thrown in a consistent fashion for synchronization to work
441 * correctly.
442 * @throws UnsupportedOperationException if exclusive mode is not supported
443 */
444 protected boolean tryRelease(long arg) {
445 throw new UnsupportedOperationException();
446 }
447
448 /**
449 * Attempts to acquire in shared mode. This method should query if
450 * the state of the object permits it to be acquired in the shared
451 * mode, and if so to acquire it.
452 *
453 * <p>This method is always invoked by the thread performing
454 * acquire. If this method reports failure, the acquire method
455 * may queue the thread, if it is not already queued, until it is
456 * signalled by a release from some other thread.
457 *
458 * <p>The default implementation throws {@link
459 * UnsupportedOperationException}.
460 *
461 * @param arg the acquire argument. This value is always the one
462 * passed to an acquire method, or is the value saved on entry
463 * to a condition wait. The value is otherwise uninterpreted
464 * and can represent anything you like.
465 * @return a negative value on failure; zero if acquisition in shared
466 * mode succeeded but no subsequent shared-mode acquire can
467 * succeed; and a positive value if acquisition in shared
468 * mode succeeded and subsequent shared-mode acquires might
469 * also succeed, in which case a subsequent waiting thread
470 * must check availability. (Support for three different
471 * return values enables this method to be used in contexts
472 * where acquires only sometimes act exclusively.) Upon
473 * success, this object has been acquired.
474 * @throws IllegalMonitorStateException if acquiring would place this
475 * synchronizer in an illegal state. This exception must be
476 * thrown in a consistent fashion for synchronization to work
477 * correctly.
478 * @throws UnsupportedOperationException if shared mode is not supported
479 */
480 protected long tryAcquireShared(long arg) {
481 throw new UnsupportedOperationException();
482 }
483
484 /**
485 * Attempts to set the state to reflect a release in shared mode.
486 *
487 * <p>This method is always invoked by the thread performing release.
488 *
489 * <p>The default implementation throws
490 * {@link UnsupportedOperationException}.
491 *
492 * @param arg the release argument. This value is always the one
493 * passed to a release method, or the current state value upon
494 * entry to a condition wait. The value is otherwise
495 * uninterpreted and can represent anything you like.
496 * @return {@code true} if this release of shared mode may permit a
497 * waiting acquire (shared or exclusive) to succeed; and
498 * {@code false} otherwise
499 * @throws IllegalMonitorStateException if releasing would place this
500 * synchronizer in an illegal state. This exception must be
501 * thrown in a consistent fashion for synchronization to work
502 * correctly.
503 * @throws UnsupportedOperationException if shared mode is not supported
504 */
505 protected boolean tryReleaseShared(long arg) {
506 throw new UnsupportedOperationException();
507 }
508
509 /**
510 * Returns {@code true} if synchronization is held exclusively with
511 * respect to the current (calling) thread. This method is invoked
512 * upon each call to a {@link ConditionObject} method.
513 *
514 * <p>The default implementation throws {@link
515 * UnsupportedOperationException}. This method is invoked
516 * internally only within {@link ConditionObject} methods, so need
517 * not be defined if conditions are not used.
518 *
519 * @return {@code true} if synchronization is held exclusively;
520 * {@code false} otherwise
521 * @throws UnsupportedOperationException if conditions are not supported
522 */
523 protected boolean isHeldExclusively() {
524 throw new UnsupportedOperationException();
525 }
526
527 /**
528 * Acquires in exclusive mode, ignoring interrupts. Implemented
529 * by invoking at least once {@link #tryAcquire},
530 * returning on success. Otherwise the thread is queued, possibly
531 * repeatedly blocking and unblocking, invoking {@link
532 * #tryAcquire} until success. This method can be used
533 * to implement method {@link Lock#lock}.
534 *
535 * @param arg the acquire argument. This value is conveyed to
536 * {@link #tryAcquire} but is otherwise uninterpreted and
537 * can represent anything you like.
538 */
539 public final void acquire(long arg) {
540 if (!tryAcquire(arg))
541 acquire(null, arg, false, false, false, 0L);
542 }
543
544 /**
545 * Acquires in exclusive mode, aborting if interrupted.
546 * Implemented by first checking interrupt status, then invoking
547 * at least once {@link #tryAcquire}, returning on
548 * success. Otherwise the thread is queued, possibly repeatedly
549 * blocking and unblocking, invoking {@link #tryAcquire}
550 * until success or the thread is interrupted. This method can be
551 * used to implement method {@link Lock#lockInterruptibly}.
552 *
553 * @param arg the acquire argument. This value is conveyed to
554 * {@link #tryAcquire} but is otherwise uninterpreted and
555 * can represent anything you like.
556 * @throws InterruptedException if the current thread is interrupted
557 */
558 public final void acquireInterruptibly(long arg)
559 throws InterruptedException {
560 if (Thread.interrupted() ||
561 (!tryAcquire(arg) && acquire(null, arg, false, true, false, 0L) < 0))
562 throw new InterruptedException();
563 }
564
565 /**
566 * Attempts to acquire in exclusive mode, aborting if interrupted,
567 * and failing if the given timeout elapses. Implemented by first
568 * checking interrupt status, then invoking at least once {@link
569 * #tryAcquire}, returning on success. Otherwise, the thread is
570 * queued, possibly repeatedly blocking and unblocking, invoking
571 * {@link #tryAcquire} until success or the thread is interrupted
572 * or the timeout elapses. This method can be used to implement
573 * method {@link Lock#tryLock(long, TimeUnit)}.
574 *
575 * @param arg the acquire argument. This value is conveyed to
576 * {@link #tryAcquire} but is otherwise uninterpreted and
577 * can represent anything you like.
578 * @param nanosTimeout the maximum number of nanoseconds to wait
579 * @return {@code true} if acquired; {@code false} if timed out
580 * @throws InterruptedException if the current thread is interrupted
581 */
582 public final boolean tryAcquireNanos(long arg, long nanosTimeout)
583 throws InterruptedException {
584 if (!Thread.interrupted()) {
585 if (tryAcquire(arg))
586 return true;
587 if (nanosTimeout <= 0L)
588 return false;
589 int stat = acquire(null, arg, false, true, true,
590 System.nanoTime() + nanosTimeout);
591 if (stat > 0)
592 return true;
593 if (stat == 0)
594 return false;
595 }
596 throw new InterruptedException();
597 }
598
599 /**
600 * Releases in exclusive mode. Implemented by unblocking one or
601 * more threads if {@link #tryRelease} returns true.
602 * This method can be used to implement method {@link Lock#unlock}.
603 *
604 * @param arg the release argument. This value is conveyed to
605 * {@link #tryRelease} but is otherwise uninterpreted and
606 * can represent anything you like.
607 * @return the value returned from {@link #tryRelease}
608 */
609 public final boolean release(long arg) {
610 if (tryRelease(arg)) {
611 signalNext(head);
612 return true;
613 }
614 return false;
615 }
616
617 /**
618 * Acquires in shared mode, ignoring interrupts. Implemented by
619 * first invoking at least once {@link #tryAcquireShared},
620 * returning on success. Otherwise the thread is queued, possibly
621 * repeatedly blocking and unblocking, invoking {@link
622 * #tryAcquireShared} until success.
623 *
624 * @param arg the acquire argument. This value is conveyed to
625 * {@link #tryAcquireShared} but is otherwise uninterpreted
626 * and can represent anything you like.
627 */
628 public final void acquireShared(long arg) {
629 if (tryAcquireShared(arg) < 0)
630 acquire(null, arg, true, false, false, 0L);
631 }
632
633 /**
634 * Acquires in shared mode, aborting if interrupted. Implemented
635 * by first checking interrupt status, then invoking at least once
636 * {@link #tryAcquireShared}, returning on success. Otherwise the
637 * thread is queued, possibly repeatedly blocking and unblocking,
638 * invoking {@link #tryAcquireShared} until success or the thread
639 * is interrupted.
640 * @param arg the acquire argument.
641 * This value is conveyed to {@link #tryAcquireShared} but is
642 * otherwise uninterpreted and can represent anything
643 * you like.
644 * @throws InterruptedException if the current thread is interrupted
645 */
646 public final void acquireSharedInterruptibly(long arg)
647 throws InterruptedException {
648 if (Thread.interrupted() ||
649 (tryAcquireShared(arg) < 0 &&
650 acquire(null, arg, true, true, false, 0L) < 0))
651 throw new InterruptedException();
652 }
653
654 /**
655 * Attempts to acquire in shared mode, aborting if interrupted, and
656 * failing if the given timeout elapses. Implemented by first
657 * checking interrupt status, then invoking at least once {@link
658 * #tryAcquireShared}, returning on success. Otherwise, the
659 * thread is queued, possibly repeatedly blocking and unblocking,
660 * invoking {@link #tryAcquireShared} until success or the thread
661 * is interrupted or the timeout elapses.
662 *
663 * @param arg the acquire argument. This value is conveyed to
664 * {@link #tryAcquireShared} but is otherwise uninterpreted
665 * and can represent anything you like.
666 * @param nanosTimeout the maximum number of nanoseconds to wait
667 * @return {@code true} if acquired; {@code false} if timed out
668 * @throws InterruptedException if the current thread is interrupted
669 */
670 public final boolean tryAcquireSharedNanos(long arg, long nanosTimeout)
671 throws InterruptedException {
672 if (!Thread.interrupted()) {
673 if (tryAcquireShared(arg) >= 0)
674 return true;
675 if (nanosTimeout <= 0L)
676 return false;
677 int stat = acquire(null, arg, true, true, true,
678 System.nanoTime() + nanosTimeout);
679 if (stat > 0)
680 return true;
681 if (stat == 0)
682 return false;
683 }
684 throw new InterruptedException();
685 }
686
687 /**
688 * Releases in shared mode. Implemented by unblocking one or more
689 * threads if {@link #tryReleaseShared} returns true.
690 *
691 * @param arg the release argument. This value is conveyed to
692 * {@link #tryReleaseShared} but is otherwise uninterpreted
693 * and can represent anything you like.
694 * @return the value returned from {@link #tryReleaseShared}
695 */
696 public final boolean releaseShared(long arg) {
697 if (tryReleaseShared(arg)) {
698 signalNext(head);
699 return true;
700 }
701 return false;
702 }
703
704 // Queue inspection methods
705
706 /**
707 * Queries whether any threads are waiting to acquire. Note that
708 * because cancellations due to interrupts and timeouts may occur
709 * at any time, a {@code true} return does not guarantee that any
710 * other thread will ever acquire.
711 *
712 * @return {@code true} if there may be other threads waiting to acquire
713 */
714 public final boolean hasQueuedThreads() {
715 for (Node p = tail, h = head; p != h && p != null; p = p.prev)
716 if (p.status >= 0)
717 return true;
718 return false;
719 }
720
721 /**
722 * Queries whether any threads have ever contended to acquire this
723 * synchronizer; that is, if an acquire method has ever blocked.
724 *
725 * <p>In this implementation, this operation returns in
726 * constant time.
727 *
728 * @return {@code true} if there has ever been contention
729 */
730 public final boolean hasContended() {
731 return head != null;
732 }
733
734 /**
735 * Returns the first (longest-waiting) thread in the queue, or
736 * {@code null} if no threads are currently queued.
737 *
738 * <p>In this implementation, this operation normally returns in
739 * constant time, but may iterate upon contention if other threads are
740 * concurrently modifying the queue.
741 *
742 * @return the first (longest-waiting) thread in the queue, or
743 * {@code null} if no threads are currently queued
744 */
745 public final Thread getFirstQueuedThread() {
746 Thread first = null, w; Node h, s;
747 if ((h = head) != null && ((s = h.next) == null ||
748 (first = s.waiter) == null ||
749 s.prev == null)) {
750 // traverse from tail on stale reads
751 for (Node p = tail, q; p != null && (q = p.prev) != null; p = q)
752 if ((w = p.waiter) != null)
753 first = w;
754 }
755 return first;
756 }
757
758 /**
759 * Returns true if the given thread is currently queued.
760 *
761 * <p>This implementation traverses the queue to determine
762 * presence of the given thread.
763 *
764 * @param thread the thread
765 * @return {@code true} if the given thread is on the queue
766 * @throws NullPointerException if the thread is null
767 */
768 public final boolean isQueued(Thread thread) {
769 if (thread == null)
770 throw new NullPointerException();
771 for (Node p = tail; p != null; p = p.prev)
772 if (p.waiter == thread)
773 return true;
774 return false;
775 }
776
777 /**
778 * Returns {@code true} if the apparent first queued thread, if one
779 * exists, is waiting in exclusive mode. If this method returns
780 * {@code true}, and the current thread is attempting to acquire in
781 * shared mode (that is, this method is invoked from {@link
782 * #tryAcquireShared}) then it is guaranteed that the current thread
783 * is not the first queued thread. Used only as a heuristic in
784 * ReentrantReadWriteLock.
785 */
786 final boolean apparentlyFirstQueuedIsExclusive() {
787 Node h, s;
788 return (h = head) != null && (s = h.next) != null &&
789 !(s instanceof SharedNode) && s.waiter != null;
790 }
791
792 /**
793 * Queries whether any threads have been waiting to acquire longer
794 * than the current thread.
795 *
796 * <p>An invocation of this method is equivalent to (but may be
797 * more efficient than):
798 * <pre> {@code
799 * getFirstQueuedThread() != Thread.currentThread()
800 * && hasQueuedThreads()}</pre>
801 *
802 * <p>Note that because cancellations due to interrupts and
803 * timeouts may occur at any time, a {@code true} return does not
804 * guarantee that some other thread will acquire before the current
805 * thread. Likewise, it is possible for another thread to win a
806 * race to enqueue after this method has returned {@code false},
807 * due to the queue being empty.
808 *
809 * <p>This method is designed to be used by a fair synchronizer to
810 * avoid <a href="AbstractQueuedSynchronizer.html#barging">barging</a>.
811 * Such a synchronizer's {@link #tryAcquire} method should return
812 * {@code false}, and its {@link #tryAcquireShared} method should
813 * return a negative value, if this method returns {@code true}
814 * (unless this is a reentrant acquire). For example, the {@code
815 * tryAcquire} method for a fair, reentrant, exclusive mode
816 * synchronizer might look like this:
817 *
818 * <pre> {@code
819 * protected boolean tryAcquire(long arg) {
820 * if (isHeldExclusively()) {
821 * // A reentrant acquire; increment hold count
822 * return true;
823 * } else if (hasQueuedPredecessors()) {
824 * return false;
825 * } else {
826 * // try to acquire normally
827 * }
828 * }}</pre>
829 *
830 * @return {@code true} if there is a queued thread preceding the
831 * current thread, and {@code false} if the current thread
832 * is at the head of the queue or the queue is empty
833 * @since 1.7
834 */
835 public final boolean hasQueuedPredecessors() {
836 Thread first = null; Node h, s;
837 if ((h = head) != null && ((s = h.next) == null ||
838 (first = s.waiter) == null ||
839 s.prev == null))
840 first = getFirstQueuedThread(); // retry via getFirstQueuedThread
841 return first != null && first != Thread.currentThread();
842 }
843
844 // Instrumentation and monitoring methods
845
846 /**
847 * Returns an estimate of the number of threads waiting to
848 * acquire. The value is only an estimate because the number of
849 * threads may change dynamically while this method traverses
850 * internal data structures. This method is designed for use in
851 * monitoring system state, not for synchronization control.
852 *
853 * @return the estimated number of threads waiting to acquire
854 */
855 public final int getQueueLength() {
856 int n = 0;
857 for (Node p = tail; p != null; p = p.prev) {
858 if (p.waiter != null)
859 ++n;
860 }
861 return n;
862 }
863
864 /**
865 * Returns a collection containing threads that may be waiting to
866 * acquire. Because the actual set of threads may change
867 * dynamically while constructing this result, the returned
868 * collection is only a best-effort estimate. The elements of the
869 * returned collection are in no particular order. This method is
870 * designed to facilitate construction of subclasses that provide
871 * more extensive monitoring facilities.
872 *
873 * @return the collection of threads
874 */
875 public final Collection<Thread> getQueuedThreads() {
876 ArrayList<Thread> list = new ArrayList<>();
877 for (Node p = tail; p != null; p = p.prev) {
878 Thread t = p.waiter;
879 if (t != null)
880 list.add(t);
881 }
882 return list;
883 }
884
885 /**
886 * Returns a collection containing threads that may be waiting to
887 * acquire in exclusive mode. This has the same properties
888 * as {@link #getQueuedThreads} except that it only returns
889 * those threads waiting due to an exclusive acquire.
890 *
891 * @return the collection of threads
892 */
893 public final Collection<Thread> getExclusiveQueuedThreads() {
894 ArrayList<Thread> list = new ArrayList<>();
895 for (Node p = tail; p != null; p = p.prev) {
896 if (!(p instanceof SharedNode)) {
897 Thread t = p.waiter;
898 if (t != null)
899 list.add(t);
900 }
901 }
902 return list;
903 }
904
905 /**
906 * Returns a collection containing threads that may be waiting to
907 * acquire in shared mode. This has the same properties
908 * as {@link #getQueuedThreads} except that it only returns
909 * those threads waiting due to a shared acquire.
910 *
911 * @return the collection of threads
912 */
913 public final Collection<Thread> getSharedQueuedThreads() {
914 ArrayList<Thread> list = new ArrayList<>();
915 for (Node p = tail; p != null; p = p.prev) {
916 if (p instanceof SharedNode) {
917 Thread t = p.waiter;
918 if (t != null)
919 list.add(t);
920 }
921 }
922 return list;
923 }
924
925 /**
926 * Returns a string identifying this synchronizer, as well as its state.
927 * The state, in brackets, includes the String {@code "State ="}
928 * followed by the current value of {@link #getState}, and either
929 * {@code "nonempty"} or {@code "empty"} depending on whether the
930 * queue is empty.
931 *
932 * @return a string identifying this synchronizer, as well as its state
933 */
934 public String toString() {
935 return super.toString()
936 + "[State = " + getState() + ", "
937 + (hasQueuedThreads() ? "non" : "") + "empty queue]";
938 }
939
940 // Instrumentation methods for conditions
941
942 /**
943 * Queries whether the given ConditionObject
944 * uses this synchronizer as its lock.
945 *
946 * @param condition the condition
947 * @return {@code true} if owned
948 * @throws NullPointerException if the condition is null
949 */
950 public final boolean owns(ConditionObject condition) {
951 return condition.isOwnedBy(this);
952 }
953
954 /**
955 * Queries whether any threads are waiting on the given condition
956 * associated with this synchronizer. Note that because timeouts
957 * and interrupts may occur at any time, a {@code true} return
958 * does not guarantee that a future {@code signal} will awaken
959 * any threads. This method is designed primarily for use in
960 * monitoring of the system state.
961 *
962 * @param condition the condition
963 * @return {@code true} if there are any waiting threads
964 * @throws IllegalMonitorStateException if exclusive synchronization
965 * is not held
966 * @throws IllegalArgumentException if the given condition is
967 * not associated with this synchronizer
968 * @throws NullPointerException if the condition is null
969 */
970 public final boolean hasWaiters(ConditionObject condition) {
971 if (!owns(condition))
972 throw new IllegalArgumentException("Not owner");
973 return condition.hasWaiters();
974 }
975
976 /**
977 * Returns an estimate of the number of threads waiting on the
978 * given condition associated with this synchronizer. Note that
979 * because timeouts and interrupts may occur at any time, the
980 * estimate serves only as an upper bound on the actual number of
981 * waiters. This method is designed for use in monitoring system
982 * state, not for synchronization control.
983 *
984 * @param condition the condition
985 * @return the estimated number of waiting threads
986 * @throws IllegalMonitorStateException if exclusive synchronization
987 * is not held
988 * @throws IllegalArgumentException if the given condition is
989 * not associated with this synchronizer
990 * @throws NullPointerException if the condition is null
991 */
992 public final int getWaitQueueLength(ConditionObject condition) {
993 if (!owns(condition))
994 throw new IllegalArgumentException("Not owner");
995 return condition.getWaitQueueLength();
996 }
997
998 /**
999 * Returns a collection containing those threads that may be
1000 * waiting on the given condition associated with this
1001 * synchronizer. Because the actual set of threads may change
1002 * dynamically while constructing this result, the returned
1003 * collection is only a best-effort estimate. The elements of the
1004 * returned collection are in no particular order.
1005 *
1006 * @param condition the condition
1007 * @return the collection of threads
1008 * @throws IllegalMonitorStateException if exclusive synchronization
1009 * is not held
1010 * @throws IllegalArgumentException if the given condition is
1011 * not associated with this synchronizer
1012 * @throws NullPointerException if the condition is null
1013 */
1014 public final Collection<Thread> getWaitingThreads(ConditionObject condition) {
1015 if (!owns(condition))
1016 throw new IllegalArgumentException("Not owner");
1017 return condition.getWaitingThreads();
1018 }
1019
1020 /**
1021 * Condition implementation for a {@link AbstractQueuedLongSynchronizer}
1022 * serving as the basis of a {@link Lock} implementation.
1023 *
1024 * <p>Method documentation for this class describes mechanics,
1025 * not behavioral specifications from the point of view of Lock
1026 * and Condition users. Exported versions of this class will in
1027 * general need to be accompanied by documentation describing
1028 * condition semantics that rely on those of the associated
1029 * {@code AbstractQueuedLongSynchronizer}.
1030 *
1031 * <p>This class is Serializable, but all fields are transient,
1032 * so deserialized conditions have no waiters.
1033 */
1034 public class ConditionObject implements Condition, java.io.Serializable {
1035 private static final long serialVersionUID = 1173984872572414699L;
1036 /** First node of condition queue. */
1037 private transient ConditionNode firstWaiter;
1038 /** Last node of condition queue. */
1039 private transient ConditionNode lastWaiter;
1040
1041 /**
1042 * Creates a new {@code ConditionObject} instance.
1043 */
1044 public ConditionObject() { }
1045
1046 // Signalling methods
1047
1048 /**
1049 * Removes and transfers one or all waiters to sync queue.
1050 */
1051 private void doSignal(ConditionNode first, boolean all) {
1052 while (first != null) {
1053 ConditionNode next = first.nextWaiter;
1054 if ((firstWaiter = next) == null)
1055 lastWaiter = null;
1056 if ((first.getAndUnsetStatus(COND) & COND) != 0) {
1057 enqueue(first);
1058 if (!all)
1059 break;
1060 }
1061 first = next;
1062 }
1063 }
1064
1065 /**
1066 * Moves the longest-waiting thread, if one exists, from the
1067 * wait queue for this condition to the wait queue for the
1068 * owning lock.
1069 *
1070 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1071 * returns {@code false}
1072 */
1073 public final void signal() {
1074 ConditionNode first = firstWaiter;
1075 if (!isHeldExclusively())
1076 throw new IllegalMonitorStateException();
1077 if (first != null)
1078 doSignal(first, false);
1079 }
1080
1081 /**
1082 * Moves all threads from the wait queue for this condition to
1083 * the wait queue for the owning lock.
1084 *
1085 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1086 * returns {@code false}
1087 */
1088 public final void signalAll() {
1089 ConditionNode first = firstWaiter;
1090 if (!isHeldExclusively())
1091 throw new IllegalMonitorStateException();
1092 if (first != null)
1093 doSignal(first, true);
1094 }
1095
1096 // Waiting methods
1097
1098 /**
1099 * Adds node to condition list and releases lock.
1100 *
1101 * @param node the node
1102 * @return savedState to reacquire after wait
1103 */
1104 private long enableWait(ConditionNode node) {
1105 if (isHeldExclusively()) {
1106 node.waiter = Thread.currentThread();
1107 node.setStatusRelaxed(COND | WAITING);
1108 ConditionNode last = lastWaiter;
1109 if (last == null)
1110 firstWaiter = node;
1111 else
1112 last.nextWaiter = node;
1113 lastWaiter = node;
1114 long savedState = getState();
1115 if (release(savedState))
1116 return savedState;
1117 }
1118 node.status = CANCELLED; // lock not held or inconsistent
1119 throw new IllegalMonitorStateException();
1120 }
1121
1122 /**
1123 * Returns true if a node that was initially placed on a condition
1124 * queue is now ready to reacquire on sync queue.
1125 * @param node the node
1126 * @return true if is reacquiring
1127 */
1128 private boolean canReacquire(ConditionNode node) {
1129 // check links, not status to avoid enqueue race
1130 Node p; // traverse unless known to be bidirectionally linked
1131 return node != null && (p = node.prev) != null &&
1132 (p.next == node || isEnqueued(node));
1133 }
1134
1135 /**
1136 * Unlinks the given node and other non-waiting nodes from
1137 * condition queue unless already unlinked.
1138 */
1139 private void unlinkCancelledWaiters(ConditionNode node) {
1140 if (node == null || node.nextWaiter != null || node == lastWaiter) {
1141 ConditionNode w = firstWaiter, trail = null;
1142 while (w != null) {
1143 ConditionNode next = w.nextWaiter;
1144 if ((w.status & COND) == 0) {
1145 w.nextWaiter = null;
1146 if (trail == null)
1147 firstWaiter = next;
1148 else
1149 trail.nextWaiter = next;
1150 if (next == null)
1151 lastWaiter = trail;
1152 } else
1153 trail = w;
1154 w = next;
1155 }
1156 }
1157 }
1158
1159 /**
1160 * Implements uninterruptible condition wait.
1161 * <ol>
1162 * <li>Save lock state returned by {@link #getState}.
1163 * <li>Invoke {@link #release} with saved state as argument,
1164 * throwing IllegalMonitorStateException if it fails.
1165 * <li>Block until signalled.
1166 * <li>Reacquire by invoking specialized version of
1167 * {@link #acquire} with saved state as argument.
1168 * </ol>
1169 */
1170 public final void awaitUninterruptibly() {
1171 ConditionNode node = new ConditionNode();
1172 long savedState = enableWait(node);
1173 LockSupport.setCurrentBlocker(this); // for back-compatibility
1174 boolean interrupted = false, rejected = false;
1175 while (!canReacquire(node)) {
1176 if (Thread.interrupted())
1177 interrupted = true;
1178 else if ((node.status & COND) != 0) {
1179 try {
1180 if (rejected)
1181 node.block();
1182 else
1183 ForkJoinPool.managedBlock(node);
1184 } catch (RejectedExecutionException ex) {
1185 rejected = true;
1186 } catch (InterruptedException ie) {
1187 interrupted = true;
1188 }
1189 } else
1190 Thread.onSpinWait(); // awoke while enqueuing
1191 }
1192 LockSupport.setCurrentBlocker(null);
1193 node.clearStatus();
1194 acquire(node, savedState, false, false, false, 0L);
1195 if (interrupted)
1196 Thread.currentThread().interrupt();
1197 }
1198
1199 /**
1200 * Implements interruptible condition wait.
1201 * <ol>
1202 * <li>If current thread is interrupted, throw InterruptedException.
1203 * <li>Save lock state returned by {@link #getState}.
1204 * <li>Invoke {@link #release} with saved state as argument,
1205 * throwing IllegalMonitorStateException if it fails.
1206 * <li>Block until signalled or interrupted.
1207 * <li>Reacquire by invoking specialized version of
1208 * {@link #acquire} with saved state as argument.
1209 * <li>If interrupted while blocked in step 4, throw InterruptedException.
1210 * </ol>
1211 */
1212 public final void await() throws InterruptedException {
1213 if (Thread.interrupted())
1214 throw new InterruptedException();
1215 ConditionNode node = new ConditionNode();
1216 long savedState = enableWait(node);
1217 LockSupport.setCurrentBlocker(this); // for back-compatibility
1218 boolean interrupted = false, cancelled = false, rejected = false;
1219 while (!canReacquire(node)) {
1220 if (interrupted |= Thread.interrupted()) {
1221 if (cancelled = (node.getAndUnsetStatus(COND) & COND) != 0)
1222 break; // else interrupted after signal
1223 } else if ((node.status & COND) != 0) {
1224 try {
1225 if (rejected)
1226 node.block();
1227 else
1228 ForkJoinPool.managedBlock(node);
1229 } catch (RejectedExecutionException ex) {
1230 rejected = true;
1231 } catch (InterruptedException ie) {
1232 interrupted = true;
1233 }
1234 } else
1235 Thread.onSpinWait(); // awoke while enqueuing
1236 }
1237 LockSupport.setCurrentBlocker(null);
1238 node.clearStatus();
1239 acquire(node, savedState, false, false, false, 0L);
1240 if (interrupted) {
1241 if (cancelled) {
1242 unlinkCancelledWaiters(node);
1243 throw new InterruptedException();
1244 }
1245 Thread.currentThread().interrupt();
1246 }
1247 }
1248
1249 /**
1250 * Implements timed condition wait.
1251 * <ol>
1252 * <li>If current thread is interrupted, throw InterruptedException.
1253 * <li>Save lock state returned by {@link #getState}.
1254 * <li>Invoke {@link #release} with saved state as argument,
1255 * throwing IllegalMonitorStateException if it fails.
1256 * <li>Block until signalled, interrupted, or timed out.
1257 * <li>Reacquire by invoking specialized version of
1258 * {@link #acquire} with saved state as argument.
1259 * <li>If interrupted while blocked in step 4, throw InterruptedException.
1260 * </ol>
1261 */
1262 public final long awaitNanos(long nanosTimeout)
1263 throws InterruptedException {
1264 if (Thread.interrupted())
1265 throw new InterruptedException();
1266 ConditionNode node = new ConditionNode();
1267 long savedState = enableWait(node);
1268 long nanos = (nanosTimeout < 0L) ? 0L : nanosTimeout;
1269 long deadline = System.nanoTime() + nanos;
1270 boolean cancelled = false, interrupted = false;
1271 while (!canReacquire(node)) {
1272 if ((interrupted |= Thread.interrupted()) ||
1273 (nanos = deadline - System.nanoTime()) <= 0L) {
1274 if (cancelled = (node.getAndUnsetStatus(COND) & COND) != 0)
1275 break;
1276 } else
1277 LockSupport.parkNanos(this, nanos);
1278 }
1279 node.clearStatus();
1280 acquire(node, savedState, false, false, false, 0L);
1281 if (cancelled) {
1282 unlinkCancelledWaiters(node);
1283 if (interrupted)
1284 throw new InterruptedException();
1285 } else if (interrupted)
1286 Thread.currentThread().interrupt();
1287 long remaining = deadline - System.nanoTime(); // avoid overflow
1288 return (remaining <= nanosTimeout) ? remaining : Long.MIN_VALUE;
1289 }
1290
1291 /**
1292 * Implements absolute timed condition wait.
1293 * <ol>
1294 * <li>If current thread is interrupted, throw InterruptedException.
1295 * <li>Save lock state returned by {@link #getState}.
1296 * <li>Invoke {@link #release} with saved state as argument,
1297 * throwing IllegalMonitorStateException if it fails.
1298 * <li>Block until signalled, interrupted, or timed out.
1299 * <li>Reacquire by invoking specialized version of
1300 * {@link #acquire} with saved state as argument.
1301 * <li>If interrupted while blocked in step 4, throw InterruptedException.
1302 * <li>If timed out while blocked in step 4, return false, else true.
1303 * </ol>
1304 */
1305 public final boolean awaitUntil(Date deadline)
1306 throws InterruptedException {
1307 long abstime = deadline.getTime();
1308 if (Thread.interrupted())
1309 throw new InterruptedException();
1310 ConditionNode node = new ConditionNode();
1311 long savedState = enableWait(node);
1312 boolean cancelled = false, interrupted = false;
1313 while (!canReacquire(node)) {
1314 if ((interrupted |= Thread.interrupted()) ||
1315 System.currentTimeMillis() >= abstime) {
1316 if (cancelled = (node.getAndUnsetStatus(COND) & COND) != 0)
1317 break;
1318 } else
1319 LockSupport.parkUntil(this, abstime);
1320 }
1321 node.clearStatus();
1322 acquire(node, savedState, false, false, false, 0L);
1323 if (cancelled) {
1324 unlinkCancelledWaiters(node);
1325 if (interrupted)
1326 throw new InterruptedException();
1327 } else if (interrupted)
1328 Thread.currentThread().interrupt();
1329 return !cancelled;
1330 }
1331
1332 /**
1333 * Implements timed condition wait.
1334 * <ol>
1335 * <li>If current thread is interrupted, throw InterruptedException.
1336 * <li>Save lock state returned by {@link #getState}.
1337 * <li>Invoke {@link #release} with saved state as argument,
1338 * throwing IllegalMonitorStateException if it fails.
1339 * <li>Block until signalled, interrupted, or timed out.
1340 * <li>Reacquire by invoking specialized version of
1341 * {@link #acquire} with saved state as argument.
1342 * <li>If interrupted while blocked in step 4, throw InterruptedException.
1343 * <li>If timed out while blocked in step 4, return false, else true.
1344 * </ol>
1345 */
1346 public final boolean await(long time, TimeUnit unit)
1347 throws InterruptedException {
1348 long nanosTimeout = unit.toNanos(time);
1349 if (Thread.interrupted())
1350 throw new InterruptedException();
1351 ConditionNode node = new ConditionNode();
1352 long savedState = enableWait(node);
1353 long nanos = (nanosTimeout < 0L) ? 0L : nanosTimeout;
1354 long deadline = System.nanoTime() + nanos;
1355 boolean cancelled = false, interrupted = false;
1356 while (!canReacquire(node)) {
1357 if ((interrupted |= Thread.interrupted()) ||
1358 (nanos = deadline - System.nanoTime()) <= 0L) {
1359 if (cancelled = (node.getAndUnsetStatus(COND) & COND) != 0)
1360 break;
1361 } else
1362 LockSupport.parkNanos(this, nanos);
1363 }
1364 node.clearStatus();
1365 acquire(node, savedState, false, false, false, 0L);
1366 if (cancelled) {
1367 unlinkCancelledWaiters(node);
1368 if (interrupted)
1369 throw new InterruptedException();
1370 } else if (interrupted)
1371 Thread.currentThread().interrupt();
1372 return !cancelled;
1373 }
1374
1375 // support for instrumentation
1376
1377 /**
1378 * Returns true if this condition was created by the given
1379 * synchronization object.
1380 *
1381 * @return {@code true} if owned
1382 */
1383 final boolean isOwnedBy(AbstractQueuedLongSynchronizer sync) {
1384 return sync == AbstractQueuedLongSynchronizer.this;
1385 }
1386
1387 /**
1388 * Queries whether any threads are waiting on this condition.
1389 * Implements {@link AbstractQueuedLongSynchronizer#hasWaiters(ConditionObject)}.
1390 *
1391 * @return {@code true} if there are any waiting threads
1392 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1393 * returns {@code false}
1394 */
1395 protected final boolean hasWaiters() {
1396 if (!isHeldExclusively())
1397 throw new IllegalMonitorStateException();
1398 for (ConditionNode w = firstWaiter; w != null; w = w.nextWaiter) {
1399 if ((w.status & COND) != 0)
1400 return true;
1401 }
1402 return false;
1403 }
1404
1405 /**
1406 * Returns an estimate of the number of threads waiting on
1407 * this condition.
1408 * Implements {@link AbstractQueuedLongSynchronizer#getWaitQueueLength(ConditionObject)}.
1409 *
1410 * @return the estimated number of waiting threads
1411 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1412 * returns {@code false}
1413 */
1414 protected final int getWaitQueueLength() {
1415 if (!isHeldExclusively())
1416 throw new IllegalMonitorStateException();
1417 int n = 0;
1418 for (ConditionNode w = firstWaiter; w != null; w = w.nextWaiter) {
1419 if ((w.status & COND) != 0)
1420 ++n;
1421 }
1422 return n;
1423 }
1424
1425 /**
1426 * Returns a collection containing those threads that may be
1427 * waiting on this Condition.
1428 * Implements {@link AbstractQueuedLongSynchronizer#getWaitingThreads(ConditionObject)}.
1429 *
1430 * @return the collection of threads
1431 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1432 * returns {@code false}
1433 */
1434 protected final Collection<Thread> getWaitingThreads() {
1435 if (!isHeldExclusively())
1436 throw new IllegalMonitorStateException();
1437 ArrayList<Thread> list = new ArrayList<>();
1438 for (ConditionNode w = firstWaiter; w != null; w = w.nextWaiter) {
1439 if ((w.status & COND) != 0) {
1440 Thread t = w.waiter;
1441 if (t != null)
1442 list.add(t);
1443 }
1444 }
1445 return list;
1446 }
1447 }
1448
1449 // Unsafe
1450 private static final Unsafe U = Unsafe.getUnsafe();
1451 private static final long STATE
1452 = U.objectFieldOffset(AbstractQueuedLongSynchronizer.class, "state");
1453 private static final long HEAD
1454 = U.objectFieldOffset(AbstractQueuedLongSynchronizer.class, "head");
1455 private static final long TAIL
1456 = U.objectFieldOffset(AbstractQueuedLongSynchronizer.class, "tail");
1457
1458 static {
1459 Class<?> ensureLoaded = LockSupport.class;
1460 }
1461 }