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