001/* 002 * Copyright (C) 2010 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.util.concurrent; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018 019import com.google.common.annotations.Beta; 020import com.google.common.annotations.GwtIncompatible; 021import com.google.common.base.Throwables; 022import com.google.errorprone.annotations.concurrent.GuardedBy; 023import com.google.j2objc.annotations.Weak; 024import java.util.concurrent.TimeUnit; 025import java.util.concurrent.locks.Condition; 026import java.util.concurrent.locks.ReentrantLock; 027 028/** 029 * A synchronization abstraction supporting waiting on arbitrary boolean conditions. 030 * 031 * <p>This class is intended as a replacement for {@link ReentrantLock}. Code using {@code Monitor} 032 * is less error-prone and more readable than code using {@code ReentrantLock}, without significant 033 * performance loss. {@code Monitor} even has the potential for performance gain by optimizing the 034 * evaluation and signaling of conditions. Signaling is entirely <a 035 * href="http://en.wikipedia.org/wiki/Monitor_(synchronization)#Implicit_signaling">implicit</a>. By 036 * eliminating explicit signaling, this class can guarantee that only one thread is awakened when a 037 * condition becomes true (no "signaling storms" due to use of {@link 038 * java.util.concurrent.locks.Condition#signalAll Condition.signalAll}) and that no signals are lost 039 * (no "hangs" due to incorrect use of {@link java.util.concurrent.locks.Condition#signal 040 * Condition.signal}). 041 * 042 * <p>A thread is said to <i>occupy</i> a monitor if it has <i>entered</i> the monitor but not yet 043 * <i>left</i>. Only one thread may occupy a given monitor at any moment. A monitor is also 044 * reentrant, so a thread may enter a monitor any number of times, and then must leave the same 045 * number of times. The <i>enter</i> and <i>leave</i> operations have the same synchronization 046 * semantics as the built-in Java language synchronization primitives. 047 * 048 * <p>A call to any of the <i>enter</i> methods with <b>void</b> return type should always be 049 * followed immediately by a <i>try/finally</i> block to ensure that the current thread leaves the 050 * monitor cleanly: 051 * 052 * <pre>{@code 053 * monitor.enter(); 054 * try { 055 * // do things while occupying the monitor 056 * } finally { 057 * monitor.leave(); 058 * } 059 * }</pre> 060 * 061 * <p>A call to any of the <i>enter</i> methods with <b>boolean</b> return type should always appear 062 * as the condition of an <i>if</i> statement containing a <i>try/finally</i> block to ensure that 063 * the current thread leaves the monitor cleanly: 064 * 065 * <pre>{@code 066 * if (monitor.tryEnter()) { 067 * try { 068 * // do things while occupying the monitor 069 * } finally { 070 * monitor.leave(); 071 * } 072 * } else { 073 * // do other things since the monitor was not available 074 * } 075 * }</pre> 076 * 077 * <h2>Comparison with {@code synchronized} and {@code ReentrantLock}</h2> 078 * 079 * <p>The following examples show a simple threadsafe holder expressed using {@code synchronized}, 080 * {@link ReentrantLock}, and {@code Monitor}. 081 * 082 * <h3>{@code synchronized}</h3> 083 * 084 * <p>This version is the fewest lines of code, largely because the synchronization mechanism used 085 * is built into the language and runtime. But the programmer has to remember to avoid a couple of 086 * common bugs: The {@code wait()} must be inside a {@code while} instead of an {@code if}, and 087 * {@code notifyAll()} must be used instead of {@code notify()} because there are two different 088 * logical conditions being awaited. 089 * 090 * <pre>{@code 091 * public class SafeBox<V> { 092 * private V value; 093 * 094 * public synchronized V get() throws InterruptedException { 095 * while (value == null) { 096 * wait(); 097 * } 098 * V result = value; 099 * value = null; 100 * notifyAll(); 101 * return result; 102 * } 103 * 104 * public synchronized void set(V newValue) throws InterruptedException { 105 * while (value != null) { 106 * wait(); 107 * } 108 * value = newValue; 109 * notifyAll(); 110 * } 111 * } 112 * }</pre> 113 * 114 * <h3>{@code ReentrantLock}</h3> 115 * 116 * <p>This version is much more verbose than the {@code synchronized} version, and still suffers 117 * from the need for the programmer to remember to use {@code while} instead of {@code if}. However, 118 * one advantage is that we can introduce two separate {@code Condition} objects, which allows us to 119 * use {@code signal()} instead of {@code signalAll()}, which may be a performance benefit. 120 * 121 * <pre>{@code 122 * public class SafeBox<V> { 123 * private final ReentrantLock lock = new ReentrantLock(); 124 * private final Condition valuePresent = lock.newCondition(); 125 * private final Condition valueAbsent = lock.newCondition(); 126 * private V value; 127 * 128 * public V get() throws InterruptedException { 129 * lock.lock(); 130 * try { 131 * while (value == null) { 132 * valuePresent.await(); 133 * } 134 * V result = value; 135 * value = null; 136 * valueAbsent.signal(); 137 * return result; 138 * } finally { 139 * lock.unlock(); 140 * } 141 * } 142 * 143 * public void set(V newValue) throws InterruptedException { 144 * lock.lock(); 145 * try { 146 * while (value != null) { 147 * valueAbsent.await(); 148 * } 149 * value = newValue; 150 * valuePresent.signal(); 151 * } finally { 152 * lock.unlock(); 153 * } 154 * } 155 * } 156 * }</pre> 157 * 158 * <h3>{@code Monitor}</h3> 159 * 160 * <p>This version adds some verbosity around the {@code Guard} objects, but removes that same 161 * verbosity, and more, from the {@code get} and {@code set} methods. {@code Monitor} implements the 162 * same efficient signaling as we had to hand-code in the {@code ReentrantLock} version above. 163 * Finally, the programmer no longer has to hand-code the wait loop, and therefore doesn't have to 164 * remember to use {@code while} instead of {@code if}. 165 * 166 * <pre>{@code 167 * public class SafeBox<V> { 168 * private final Monitor monitor = new Monitor(); 169 * private final Monitor.Guard valuePresent = new Monitor.Guard(monitor) { 170 * public boolean isSatisfied() { 171 * return value != null; 172 * } 173 * }; 174 * private final Monitor.Guard valueAbsent = new Monitor.Guard(monitor) { 175 * public boolean isSatisfied() { 176 * return value == null; 177 * } 178 * }; 179 * private V value; 180 * 181 * public V get() throws InterruptedException { 182 * monitor.enterWhen(valuePresent); 183 * try { 184 * V result = value; 185 * value = null; 186 * return result; 187 * } finally { 188 * monitor.leave(); 189 * } 190 * } 191 * 192 * public void set(V newValue) throws InterruptedException { 193 * monitor.enterWhen(valueAbsent); 194 * try { 195 * value = newValue; 196 * } finally { 197 * monitor.leave(); 198 * } 199 * } 200 * } 201 * }</pre> 202 * 203 * @author Justin T. Sampson 204 * @author Martin Buchholz 205 * @since 10.0 206 */ 207@Beta 208@GwtIncompatible 209@SuppressWarnings("GuardedBy") // TODO(b/35466881): Fix or suppress. 210public final class Monitor { 211 // TODO(user): Use raw LockSupport or AbstractQueuedSynchronizer instead of ReentrantLock. 212 // TODO(user): "Port" jsr166 tests for ReentrantLock. 213 // 214 // TODO(user): Change API to make it impossible to use a Guard with the "wrong" monitor, 215 // by making the monitor implicit, and to eliminate other sources of IMSE. 216 // Imagine: 217 // guard.lock(); 218 // try { /* monitor locked and guard satisfied here */ } 219 // finally { guard.unlock(); } 220 // Here are Justin's design notes about this: 221 // 222 // This idea has come up from time to time, and I think one of my 223 // earlier versions of Monitor even did something like this. I ended 224 // up strongly favoring the current interface. 225 // 226 // I probably can't remember all the reasons (it's possible you 227 // could find them in the code review archives), but here are a few: 228 // 229 // 1. What about leaving/unlocking? Are you going to do 230 // guard.enter() paired with monitor.leave()? That might get 231 // confusing. It's nice for the finally block to look as close as 232 // possible to the thing right before the try. You could have 233 // guard.leave(), but that's a little odd as well because the 234 // guard doesn't have anything to do with leaving. You can't 235 // really enforce that the guard you're leaving is the same one 236 // you entered with, and it doesn't actually matter. 237 // 238 // 2. Since you can enter the monitor without a guard at all, some 239 // places you'll have monitor.enter()/monitor.leave() and other 240 // places you'll have guard.enter()/guard.leave() even though 241 // it's the same lock being acquired underneath. Always using 242 // monitor.enterXXX()/monitor.leave() will make it really clear 243 // which lock is held at any point in the code. 244 // 245 // 3. I think "enterWhen(notEmpty)" reads better than "notEmpty.enter()". 246 // 247 // TODO(user): Implement ReentrantLock features: 248 // - toString() method 249 // - getOwner() method 250 // - getQueuedThreads() method 251 // - getWaitingThreads(Guard) method 252 // - implement Serializable 253 // - redo the API to be as close to identical to ReentrantLock as possible, 254 // since, after all, this class is also a reentrant mutual exclusion lock!? 255 256 /* 257 * One of the key challenges of this class is to prevent lost signals, while trying hard to 258 * minimize unnecessary signals. One simple and correct algorithm is to signal some other waiter 259 * with a satisfied guard (if one exists) whenever any thread occupying the monitor exits the 260 * monitor, either by unlocking all of its held locks, or by starting to wait for a guard. This 261 * includes exceptional exits, so all control paths involving signalling must be protected by a 262 * finally block. 263 * 264 * Further optimizations of this algorithm become increasingly subtle. A wait that terminates 265 * without the guard being satisfied (due to timeout, but not interrupt) can then immediately exit 266 * the monitor without signalling. If it timed out without being signalled, it does not need to 267 * "pass on" the signal to another thread. If it *was* signalled, then its guard must have been 268 * satisfied at the time of signal, and has since been modified by some other thread to be 269 * non-satisfied before reacquiring the lock, and that other thread takes over the responsibility 270 * of signaling the next waiter. 271 * 272 * Unlike the underlying Condition, if we are not careful, an interrupt *can* cause a signal to be 273 * lost, because the signal may be sent to a condition whose sole waiter has just been 274 * interrupted. 275 * 276 * Imagine a monitor with multiple guards. A thread enters the monitor, satisfies all the guards, 277 * and leaves, calling signalNextWaiter. With traditional locks and conditions, all the conditions 278 * need to be signalled because it is not known which if any of them have waiters (and hasWaiters 279 * can't be used reliably because of a check-then-act race). With our Monitor guards, we only 280 * signal the first active guard that is satisfied. But the corresponding thread may have already 281 * been interrupted and is waiting to reacquire the lock while still registered in activeGuards, 282 * in which case the signal is a no-op, and the bigger-picture signal is lost unless interrupted 283 * threads take special action by participating in the signal-passing game. 284 */ 285 286 /* 287 * Timeout handling is intricate, especially given our ambitious goals: 288 * - Avoid underflow and overflow of timeout values when specified timeouts are close to 289 * Long.MIN_VALUE or Long.MAX_VALUE. 290 * - Favor responding to interrupts over timeouts. 291 * - System.nanoTime() is expensive enough that we want to call it the minimum required number of 292 * times, typically once before invoking a blocking method. This often requires keeping track of 293 * the first time in a method that nanoTime() has been invoked, for which the special value 0L 294 * is reserved to mean "uninitialized". If timeout is non-positive, then nanoTime need never be 295 * called. 296 * - Keep behavior of fair and non-fair instances consistent. 297 */ 298 299 /** 300 * A boolean condition for which a thread may wait. A {@code Guard} is associated with a single 301 * {@code Monitor}. The monitor may check the guard at arbitrary times from any thread occupying 302 * the monitor, so code should not be written to rely on how often a guard might or might not be 303 * checked. 304 * 305 * <p>If a {@code Guard} is passed into any method of a {@code Monitor} other than the one it is 306 * associated with, an {@link IllegalMonitorStateException} is thrown. 307 * 308 * @since 10.0 309 */ 310 @Beta 311 public abstract static class Guard { 312 313 @Weak final Monitor monitor; 314 final Condition condition; 315 316 @GuardedBy("monitor.lock") 317 int waiterCount = 0; 318 319 /** The next active guard */ 320 @GuardedBy("monitor.lock") 321 Guard next; 322 323 protected Guard(Monitor monitor) { 324 this.monitor = checkNotNull(monitor, "monitor"); 325 this.condition = monitor.lock.newCondition(); 326 } 327 328 /** 329 * Evaluates this guard's boolean condition. This method is always called with the associated 330 * monitor already occupied. Implementations of this method must depend only on state protected 331 * by the associated monitor, and must not modify that state. 332 */ 333 public abstract boolean isSatisfied(); 334 } 335 336 /** Whether this monitor is fair. */ 337 private final boolean fair; 338 339 /** The lock underlying this monitor. */ 340 private final ReentrantLock lock; 341 342 /** 343 * The guards associated with this monitor that currently have waiters ({@code waiterCount > 0}). 344 * A linked list threaded through the Guard.next field. 345 */ 346 @GuardedBy("lock") 347 private Guard activeGuards = null; 348 349 /** 350 * Creates a monitor with a non-fair (but fast) ordering policy. Equivalent to {@code 351 * Monitor(false)}. 352 */ 353 public Monitor() { 354 this(false); 355 } 356 357 /** 358 * Creates a monitor with the given ordering policy. 359 * 360 * @param fair whether this monitor should use a fair ordering policy rather than a non-fair (but 361 * fast) one 362 */ 363 public Monitor(boolean fair) { 364 this.fair = fair; 365 this.lock = new ReentrantLock(fair); 366 } 367 368 /** Enters this monitor. Blocks indefinitely. */ 369 public void enter() { 370 lock.lock(); 371 } 372 373 /** 374 * Enters this monitor. Blocks indefinitely, but may be interrupted. 375 * 376 * @throws InterruptedException if interrupted while waiting 377 */ 378 public void enterInterruptibly() throws InterruptedException { 379 lock.lockInterruptibly(); 380 } 381 382 /** 383 * Enters this monitor. Blocks at most the given time. 384 * 385 * @return whether the monitor was entered 386 */ 387 public boolean enter(long time, TimeUnit unit) { 388 final long timeoutNanos = toSafeNanos(time, unit); 389 final ReentrantLock lock = this.lock; 390 if (!fair && lock.tryLock()) { 391 return true; 392 } 393 boolean interrupted = Thread.interrupted(); 394 try { 395 final long startTime = System.nanoTime(); 396 for (long remainingNanos = timeoutNanos; ; ) { 397 try { 398 return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS); 399 } catch (InterruptedException interrupt) { 400 interrupted = true; 401 remainingNanos = remainingNanos(startTime, timeoutNanos); 402 } 403 } 404 } finally { 405 if (interrupted) { 406 Thread.currentThread().interrupt(); 407 } 408 } 409 } 410 411 /** 412 * Enters this monitor. Blocks at most the given time, and may be interrupted. 413 * 414 * @return whether the monitor was entered 415 * @throws InterruptedException if interrupted while waiting 416 */ 417 public boolean enterInterruptibly(long time, TimeUnit unit) throws InterruptedException { 418 return lock.tryLock(time, unit); 419 } 420 421 /** 422 * Enters this monitor if it is possible to do so immediately. Does not block. 423 * 424 * <p><b>Note:</b> This method disregards the fairness setting of this monitor. 425 * 426 * @return whether the monitor was entered 427 */ 428 public boolean tryEnter() { 429 return lock.tryLock(); 430 } 431 432 /** 433 * Enters this monitor when the guard is satisfied. Blocks indefinitely, but may be interrupted. 434 * 435 * @throws InterruptedException if interrupted while waiting 436 */ 437 public void enterWhen(Guard guard) throws InterruptedException { 438 if (guard.monitor != this) { 439 throw new IllegalMonitorStateException(); 440 } 441 final ReentrantLock lock = this.lock; 442 boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); 443 lock.lockInterruptibly(); 444 445 boolean satisfied = false; 446 try { 447 if (!guard.isSatisfied()) { 448 await(guard, signalBeforeWaiting); 449 } 450 satisfied = true; 451 } finally { 452 if (!satisfied) { 453 leave(); 454 } 455 } 456 } 457 458 /** Enters this monitor when the guard is satisfied. Blocks indefinitely. */ 459 public void enterWhenUninterruptibly(Guard guard) { 460 if (guard.monitor != this) { 461 throw new IllegalMonitorStateException(); 462 } 463 final ReentrantLock lock = this.lock; 464 boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); 465 lock.lock(); 466 467 boolean satisfied = false; 468 try { 469 if (!guard.isSatisfied()) { 470 awaitUninterruptibly(guard, signalBeforeWaiting); 471 } 472 satisfied = true; 473 } finally { 474 if (!satisfied) { 475 leave(); 476 } 477 } 478 } 479 480 /** 481 * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both 482 * the time to acquire the lock and the time to wait for the guard to be satisfied, and may be 483 * interrupted. 484 * 485 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 486 * @throws InterruptedException if interrupted while waiting 487 */ 488 public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException { 489 final long timeoutNanos = toSafeNanos(time, unit); 490 if (guard.monitor != this) { 491 throw new IllegalMonitorStateException(); 492 } 493 final ReentrantLock lock = this.lock; 494 boolean reentrant = lock.isHeldByCurrentThread(); 495 long startTime = 0L; 496 497 locked: 498 { 499 if (!fair) { 500 // Check interrupt status to get behavior consistent with fair case. 501 if (Thread.interrupted()) { 502 throw new InterruptedException(); 503 } 504 if (lock.tryLock()) { 505 break locked; 506 } 507 } 508 startTime = initNanoTime(timeoutNanos); 509 if (!lock.tryLock(time, unit)) { 510 return false; 511 } 512 } 513 514 boolean satisfied = false; 515 boolean threw = true; 516 try { 517 satisfied = 518 guard.isSatisfied() 519 || awaitNanos( 520 guard, 521 (startTime == 0L) ? timeoutNanos : remainingNanos(startTime, timeoutNanos), 522 reentrant); 523 threw = false; 524 return satisfied; 525 } finally { 526 if (!satisfied) { 527 try { 528 // Don't need to signal if timed out, but do if interrupted 529 if (threw && !reentrant) { 530 signalNextWaiter(); 531 } 532 } finally { 533 lock.unlock(); 534 } 535 } 536 } 537 } 538 539 /** 540 * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both 541 * the time to acquire the lock and the time to wait for the guard to be satisfied. 542 * 543 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 544 */ 545 public boolean enterWhenUninterruptibly(Guard guard, long time, TimeUnit unit) { 546 final long timeoutNanos = toSafeNanos(time, unit); 547 if (guard.monitor != this) { 548 throw new IllegalMonitorStateException(); 549 } 550 final ReentrantLock lock = this.lock; 551 long startTime = 0L; 552 boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); 553 boolean interrupted = Thread.interrupted(); 554 try { 555 if (fair || !lock.tryLock()) { 556 startTime = initNanoTime(timeoutNanos); 557 for (long remainingNanos = timeoutNanos; ; ) { 558 try { 559 if (lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS)) { 560 break; 561 } else { 562 return false; 563 } 564 } catch (InterruptedException interrupt) { 565 interrupted = true; 566 remainingNanos = remainingNanos(startTime, timeoutNanos); 567 } 568 } 569 } 570 571 boolean satisfied = false; 572 try { 573 while (true) { 574 try { 575 if (guard.isSatisfied()) { 576 satisfied = true; 577 } else { 578 final long remainingNanos; 579 if (startTime == 0L) { 580 startTime = initNanoTime(timeoutNanos); 581 remainingNanos = timeoutNanos; 582 } else { 583 remainingNanos = remainingNanos(startTime, timeoutNanos); 584 } 585 satisfied = awaitNanos(guard, remainingNanos, signalBeforeWaiting); 586 } 587 return satisfied; 588 } catch (InterruptedException interrupt) { 589 interrupted = true; 590 signalBeforeWaiting = false; 591 } 592 } 593 } finally { 594 if (!satisfied) { 595 lock.unlock(); // No need to signal if timed out 596 } 597 } 598 } finally { 599 if (interrupted) { 600 Thread.currentThread().interrupt(); 601 } 602 } 603 } 604 605 /** 606 * Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does 607 * not wait for the guard to be satisfied. 608 * 609 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 610 */ 611 public boolean enterIf(Guard guard) { 612 if (guard.monitor != this) { 613 throw new IllegalMonitorStateException(); 614 } 615 final ReentrantLock lock = this.lock; 616 lock.lock(); 617 618 boolean satisfied = false; 619 try { 620 return satisfied = guard.isSatisfied(); 621 } finally { 622 if (!satisfied) { 623 lock.unlock(); 624 } 625 } 626 } 627 628 /** 629 * Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does 630 * not wait for the guard to be satisfied, and may be interrupted. 631 * 632 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 633 * @throws InterruptedException if interrupted while waiting 634 */ 635 public boolean enterIfInterruptibly(Guard guard) throws InterruptedException { 636 if (guard.monitor != this) { 637 throw new IllegalMonitorStateException(); 638 } 639 final ReentrantLock lock = this.lock; 640 lock.lockInterruptibly(); 641 642 boolean satisfied = false; 643 try { 644 return satisfied = guard.isSatisfied(); 645 } finally { 646 if (!satisfied) { 647 lock.unlock(); 648 } 649 } 650 } 651 652 /** 653 * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the 654 * lock, but does not wait for the guard to be satisfied. 655 * 656 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 657 */ 658 public boolean enterIf(Guard guard, long time, TimeUnit unit) { 659 if (guard.monitor != this) { 660 throw new IllegalMonitorStateException(); 661 } 662 if (!enter(time, unit)) { 663 return false; 664 } 665 666 boolean satisfied = false; 667 try { 668 return satisfied = guard.isSatisfied(); 669 } finally { 670 if (!satisfied) { 671 lock.unlock(); 672 } 673 } 674 } 675 676 /** 677 * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the 678 * lock, but does not wait for the guard to be satisfied, and may be interrupted. 679 * 680 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 681 */ 682 public boolean enterIfInterruptibly(Guard guard, long time, TimeUnit unit) 683 throws InterruptedException { 684 if (guard.monitor != this) { 685 throw new IllegalMonitorStateException(); 686 } 687 final ReentrantLock lock = this.lock; 688 if (!lock.tryLock(time, unit)) { 689 return false; 690 } 691 692 boolean satisfied = false; 693 try { 694 return satisfied = guard.isSatisfied(); 695 } finally { 696 if (!satisfied) { 697 lock.unlock(); 698 } 699 } 700 } 701 702 /** 703 * Enters this monitor if it is possible to do so immediately and the guard is satisfied. Does not 704 * block acquiring the lock and does not wait for the guard to be satisfied. 705 * 706 * <p><b>Note:</b> This method disregards the fairness setting of this monitor. 707 * 708 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 709 */ 710 public boolean tryEnterIf(Guard guard) { 711 if (guard.monitor != this) { 712 throw new IllegalMonitorStateException(); 713 } 714 final ReentrantLock lock = this.lock; 715 if (!lock.tryLock()) { 716 return false; 717 } 718 719 boolean satisfied = false; 720 try { 721 return satisfied = guard.isSatisfied(); 722 } finally { 723 if (!satisfied) { 724 lock.unlock(); 725 } 726 } 727 } 728 729 /** 730 * Waits for the guard to be satisfied. Waits indefinitely, but may be interrupted. May be called 731 * only by a thread currently occupying this monitor. 732 * 733 * @throws InterruptedException if interrupted while waiting 734 */ 735 public void waitFor(Guard guard) throws InterruptedException { 736 if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { 737 throw new IllegalMonitorStateException(); 738 } 739 if (!guard.isSatisfied()) { 740 await(guard, true); 741 } 742 } 743 744 /** 745 * Waits for the guard to be satisfied. Waits indefinitely. May be called only by a thread 746 * currently occupying this monitor. 747 */ 748 public void waitForUninterruptibly(Guard guard) { 749 if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { 750 throw new IllegalMonitorStateException(); 751 } 752 if (!guard.isSatisfied()) { 753 awaitUninterruptibly(guard, true); 754 } 755 } 756 757 /** 758 * Waits for the guard to be satisfied. Waits at most the given time, and may be interrupted. May 759 * be called only by a thread currently occupying this monitor. 760 * 761 * @return whether the guard is now satisfied 762 * @throws InterruptedException if interrupted while waiting 763 */ 764 public boolean waitFor(Guard guard, long time, TimeUnit unit) throws InterruptedException { 765 final long timeoutNanos = toSafeNanos(time, unit); 766 if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { 767 throw new IllegalMonitorStateException(); 768 } 769 if (guard.isSatisfied()) { 770 return true; 771 } 772 if (Thread.interrupted()) { 773 throw new InterruptedException(); 774 } 775 return awaitNanos(guard, timeoutNanos, true); 776 } 777 778 /** 779 * Waits for the guard to be satisfied. Waits at most the given time. May be called only by a 780 * thread currently occupying this monitor. 781 * 782 * @return whether the guard is now satisfied 783 */ 784 public boolean waitForUninterruptibly(Guard guard, long time, TimeUnit unit) { 785 final long timeoutNanos = toSafeNanos(time, unit); 786 if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { 787 throw new IllegalMonitorStateException(); 788 } 789 if (guard.isSatisfied()) { 790 return true; 791 } 792 boolean signalBeforeWaiting = true; 793 final long startTime = initNanoTime(timeoutNanos); 794 boolean interrupted = Thread.interrupted(); 795 try { 796 for (long remainingNanos = timeoutNanos; ; ) { 797 try { 798 return awaitNanos(guard, remainingNanos, signalBeforeWaiting); 799 } catch (InterruptedException interrupt) { 800 interrupted = true; 801 if (guard.isSatisfied()) { 802 return true; 803 } 804 signalBeforeWaiting = false; 805 remainingNanos = remainingNanos(startTime, timeoutNanos); 806 } 807 } 808 } finally { 809 if (interrupted) { 810 Thread.currentThread().interrupt(); 811 } 812 } 813 } 814 815 /** Leaves this monitor. May be called only by a thread currently occupying this monitor. */ 816 public void leave() { 817 final ReentrantLock lock = this.lock; 818 try { 819 // No need to signal if we will still be holding the lock when we return 820 if (lock.getHoldCount() == 1) { 821 signalNextWaiter(); 822 } 823 } finally { 824 lock.unlock(); // Will throw IllegalMonitorStateException if not held 825 } 826 } 827 828 /** Returns whether this monitor is using a fair ordering policy. */ 829 public boolean isFair() { 830 return fair; 831 } 832 833 /** 834 * Returns whether this monitor is occupied by any thread. This method is designed for use in 835 * monitoring of the system state, not for synchronization control. 836 */ 837 public boolean isOccupied() { 838 return lock.isLocked(); 839 } 840 841 /** 842 * Returns whether the current thread is occupying this monitor (has entered more times than it 843 * has left). 844 */ 845 public boolean isOccupiedByCurrentThread() { 846 return lock.isHeldByCurrentThread(); 847 } 848 849 /** 850 * Returns the number of times the current thread has entered this monitor in excess of the number 851 * of times it has left. Returns 0 if the current thread is not occupying this monitor. 852 */ 853 public int getOccupiedDepth() { 854 return lock.getHoldCount(); 855 } 856 857 /** 858 * Returns an estimate of the number of threads waiting to enter this monitor. The value is only 859 * an estimate because the number of threads may change dynamically while this method traverses 860 * internal data structures. This method is designed for use in monitoring of the system state, 861 * not for synchronization control. 862 */ 863 public int getQueueLength() { 864 return lock.getQueueLength(); 865 } 866 867 /** 868 * Returns whether any threads are waiting to enter this monitor. Note that because cancellations 869 * may occur at any time, a {@code true} return does not guarantee that any other thread will ever 870 * enter this monitor. This method is designed primarily for use in monitoring of the system 871 * state. 872 */ 873 public boolean hasQueuedThreads() { 874 return lock.hasQueuedThreads(); 875 } 876 877 /** 878 * Queries whether the given thread is waiting to enter this monitor. Note that because 879 * cancellations may occur at any time, a {@code true} return does not guarantee that this thread 880 * will ever enter this monitor. This method is designed primarily for use in monitoring of the 881 * system state. 882 */ 883 public boolean hasQueuedThread(Thread thread) { 884 return lock.hasQueuedThread(thread); 885 } 886 887 /** 888 * Queries whether any threads are waiting for the given guard to become satisfied. Note that 889 * because timeouts and interrupts may occur at any time, a {@code true} return does not guarantee 890 * that the guard becoming satisfied in the future will awaken any threads. This method is 891 * designed primarily for use in monitoring of the system state. 892 */ 893 public boolean hasWaiters(Guard guard) { 894 return getWaitQueueLength(guard) > 0; 895 } 896 897 /** 898 * Returns an estimate of the number of threads waiting for the given guard to become satisfied. 899 * Note that because timeouts and interrupts may occur at any time, the estimate serves only as an 900 * upper bound on the actual number of waiters. This method is designed for use in monitoring of 901 * the system state, not for synchronization control. 902 */ 903 public int getWaitQueueLength(Guard guard) { 904 if (guard.monitor != this) { 905 throw new IllegalMonitorStateException(); 906 } 907 lock.lock(); 908 try { 909 return guard.waiterCount; 910 } finally { 911 lock.unlock(); 912 } 913 } 914 915 /** 916 * Returns unit.toNanos(time), additionally ensuring the returned value is not at risk of 917 * overflowing or underflowing, by bounding the value between 0 and (Long.MAX_VALUE / 4) * 3. 918 * Actually waiting for more than 219 years is not supported! 919 */ 920 private static long toSafeNanos(long time, TimeUnit unit) { 921 long timeoutNanos = unit.toNanos(time); 922 return (timeoutNanos <= 0L) 923 ? 0L 924 : (timeoutNanos > (Long.MAX_VALUE / 4) * 3) ? (Long.MAX_VALUE / 4) * 3 : timeoutNanos; 925 } 926 927 /** 928 * Returns System.nanoTime() unless the timeout has already elapsed. Returns 0L if and only if the 929 * timeout has already elapsed. 930 */ 931 private static long initNanoTime(long timeoutNanos) { 932 if (timeoutNanos <= 0L) { 933 return 0L; 934 } else { 935 long startTime = System.nanoTime(); 936 return (startTime == 0L) ? 1L : startTime; 937 } 938 } 939 940 /** 941 * Returns the remaining nanos until the given timeout, or 0L if the timeout has already elapsed. 942 * Caller must have previously sanitized timeoutNanos using toSafeNanos. 943 */ 944 private static long remainingNanos(long startTime, long timeoutNanos) { 945 // assert timeoutNanos == 0L || startTime != 0L; 946 947 // TODO : NOT CORRECT, BUT TESTS PASS ANYWAYS! 948 // if (true) return timeoutNanos; 949 // ONLY 2 TESTS FAIL IF WE DO: 950 // if (true) return 0; 951 952 return (timeoutNanos <= 0L) ? 0L : timeoutNanos - (System.nanoTime() - startTime); 953 } 954 955 /** 956 * Signals some other thread waiting on a satisfied guard, if one exists. 957 * 958 * <p>We manage calls to this method carefully, to signal only when necessary, but never losing a 959 * signal, which is the classic problem of this kind of concurrency construct. We must signal if 960 * the current thread is about to relinquish the lock and may have changed the state protected by 961 * the monitor, thereby causing some guard to be satisfied. 962 * 963 * <p>In addition, any thread that has been signalled when its guard was satisfied acquires the 964 * responsibility of signalling the next thread when it again relinquishes the lock. Unlike a 965 * normal Condition, there is no guarantee that an interrupted thread has not been signalled, 966 * since the concurrency control must manage multiple Conditions. So this method must generally be 967 * called when waits are interrupted. 968 * 969 * <p>On the other hand, if a signalled thread wakes up to discover that its guard is still not 970 * satisfied, it does *not* need to call this method before returning to wait. This can only 971 * happen due to spurious wakeup (ignorable) or another thread acquiring the lock before the 972 * current thread can and returning the guard to the unsatisfied state. In the latter case the 973 * other thread (last thread modifying the state protected by the monitor) takes over the 974 * responsibility of signalling the next waiter. 975 * 976 * <p>This method must not be called from within a beginWaitingFor/endWaitingFor block, or else 977 * the current thread's guard might be mistakenly signalled, leading to a lost signal. 978 */ 979 @GuardedBy("lock") 980 private void signalNextWaiter() { 981 for (Guard guard = activeGuards; guard != null; guard = guard.next) { 982 if (isSatisfied(guard)) { 983 guard.condition.signal(); 984 break; 985 } 986 } 987 } 988 989 /** 990 * Exactly like signalNextWaiter, but caller guarantees that guardToSkip need not be considered, 991 * because caller has previously checked that guardToSkip.isSatisfied() returned false. An 992 * optimization for the case that guardToSkip.isSatisfied() may be expensive. 993 * 994 * <p>We decided against using this method, since in practice, isSatisfied() is likely to be very 995 * cheap (typically one field read). Resurrect this method if you find that not to be true. 996 */ 997 // @GuardedBy("lock") 998 // private void signalNextWaiterSkipping(Guard guardToSkip) { 999 // for (Guard guard = activeGuards; guard != null; guard = guard.next) { 1000 // if (guard != guardToSkip && isSatisfied(guard)) { 1001 // guard.condition.signal(); 1002 // break; 1003 // } 1004 // } 1005 // } 1006 1007 /** 1008 * Exactly like guard.isSatisfied(), but in addition signals all waiting threads in the (hopefully 1009 * unlikely) event that isSatisfied() throws. 1010 */ 1011 @GuardedBy("lock") 1012 private boolean isSatisfied(Guard guard) { 1013 try { 1014 return guard.isSatisfied(); 1015 } catch (Throwable throwable) { 1016 signalAllWaiters(); 1017 throw Throwables.propagate(throwable); 1018 } 1019 } 1020 1021 /** Signals all threads waiting on guards. */ 1022 @GuardedBy("lock") 1023 private void signalAllWaiters() { 1024 for (Guard guard = activeGuards; guard != null; guard = guard.next) { 1025 guard.condition.signalAll(); 1026 } 1027 } 1028 1029 /** Records that the current thread is about to wait on the specified guard. */ 1030 @GuardedBy("lock") 1031 private void beginWaitingFor(Guard guard) { 1032 int waiters = guard.waiterCount++; 1033 if (waiters == 0) { 1034 // push guard onto activeGuards 1035 guard.next = activeGuards; 1036 activeGuards = guard; 1037 } 1038 } 1039 1040 /** Records that the current thread is no longer waiting on the specified guard. */ 1041 @GuardedBy("lock") 1042 private void endWaitingFor(Guard guard) { 1043 int waiters = --guard.waiterCount; 1044 if (waiters == 0) { 1045 // unlink guard from activeGuards 1046 for (Guard p = activeGuards, pred = null; ; pred = p, p = p.next) { 1047 if (p == guard) { 1048 if (pred == null) { 1049 activeGuards = p.next; 1050 } else { 1051 pred.next = p.next; 1052 } 1053 p.next = null; // help GC 1054 break; 1055 } 1056 } 1057 } 1058 } 1059 1060 /* 1061 * Methods that loop waiting on a guard's condition until the guard is satisfied, while recording 1062 * this fact so that other threads know to check our guard and signal us. It's caller's 1063 * responsibility to ensure that the guard is *not* currently satisfied. 1064 */ 1065 1066 @GuardedBy("lock") 1067 private void await(Guard guard, boolean signalBeforeWaiting) throws InterruptedException { 1068 if (signalBeforeWaiting) { 1069 signalNextWaiter(); 1070 } 1071 beginWaitingFor(guard); 1072 try { 1073 do { 1074 guard.condition.await(); 1075 } while (!guard.isSatisfied()); 1076 } finally { 1077 endWaitingFor(guard); 1078 } 1079 } 1080 1081 @GuardedBy("lock") 1082 private void awaitUninterruptibly(Guard guard, boolean signalBeforeWaiting) { 1083 if (signalBeforeWaiting) { 1084 signalNextWaiter(); 1085 } 1086 beginWaitingFor(guard); 1087 try { 1088 do { 1089 guard.condition.awaitUninterruptibly(); 1090 } while (!guard.isSatisfied()); 1091 } finally { 1092 endWaitingFor(guard); 1093 } 1094 } 1095 1096 /** Caller should check before calling that guard is not satisfied. */ 1097 @GuardedBy("lock") 1098 private boolean awaitNanos(Guard guard, long nanos, boolean signalBeforeWaiting) 1099 throws InterruptedException { 1100 boolean firstTime = true; 1101 try { 1102 do { 1103 if (nanos <= 0L) { 1104 return false; 1105 } 1106 if (firstTime) { 1107 if (signalBeforeWaiting) { 1108 signalNextWaiter(); 1109 } 1110 beginWaitingFor(guard); 1111 firstTime = false; 1112 } 1113 nanos = guard.condition.awaitNanos(nanos); 1114 } while (!guard.isSatisfied()); 1115 return true; 1116 } finally { 1117 if (!firstTime) { 1118 endWaitingFor(guard); 1119 } 1120 } 1121 } 1122}