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 org.jspecify.annotations.Nullable; 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 @Nullable Guard next; 317 318 protected Guard(Monitor monitor) { 319 this.monitor = checkNotNull(monitor, "monitor"); 320 this.condition = monitor.lock.newCondition(); 321 } 322 323 /** 324 * Evaluates this guard's boolean condition. This method is always called with the associated 325 * monitor already occupied. Implementations of this method must depend only on state protected 326 * by the associated monitor, and must not modify that state. 327 */ 328 public abstract boolean isSatisfied(); 329 } 330 331 /** Whether this monitor is fair. */ 332 private final boolean fair; 333 334 /** The lock underlying this monitor. */ 335 private final ReentrantLock lock; 336 337 /** 338 * The guards associated with this monitor that currently have waiters ({@code waiterCount > 0}). 339 * A linked list threaded through the Guard.next field. 340 */ 341 @GuardedBy("lock") 342 private @Nullable Guard activeGuards = null; 343 344 /** 345 * Creates a monitor with a non-fair (but fast) ordering policy. Equivalent to {@code 346 * Monitor(false)}. 347 */ 348 public Monitor() { 349 this(false); 350 } 351 352 /** 353 * Creates a monitor with the given ordering policy. 354 * 355 * @param fair whether this monitor should use a fair ordering policy rather than a non-fair (but 356 * fast) one 357 */ 358 public Monitor(boolean fair) { 359 this.fair = fair; 360 this.lock = new ReentrantLock(fair); 361 } 362 363 /** 364 * Creates a new {@linkplain Guard guard} for this monitor. 365 * 366 * @param isSatisfied the new guard's boolean condition (see {@link Guard#isSatisfied 367 * isSatisfied()}) 368 * @since 21.0 (but only since 33.4.0 in the Android flavor) 369 */ 370 public Guard newGuard(final BooleanSupplier isSatisfied) { 371 checkNotNull(isSatisfied, "isSatisfied"); 372 return new Guard(this) { 373 @Override 374 public boolean isSatisfied() { 375 return isSatisfied.getAsBoolean(); 376 } 377 }; 378 } 379 380 /** Enters this monitor. Blocks indefinitely. */ 381 public void enter() { 382 lock.lock(); 383 } 384 385 /** 386 * Enters this monitor. Blocks at most the given time. 387 * 388 * @return whether the monitor was entered 389 * @since 28.0 (but only since 33.4.0 in the Android flavor) 390 */ 391 public boolean enter(Duration time) { 392 return enter(toNanosSaturated(time), TimeUnit.NANOSECONDS); 393 } 394 395 /** 396 * Enters this monitor. Blocks at most the given time. 397 * 398 * @return whether the monitor was entered 399 */ 400 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 401 public boolean enter(long time, TimeUnit unit) { 402 final long timeoutNanos = toSafeNanos(time, unit); 403 final ReentrantLock lock = this.lock; 404 if (!fair && lock.tryLock()) { 405 return true; 406 } 407 boolean interrupted = Thread.interrupted(); 408 try { 409 final long startTime = System.nanoTime(); 410 for (long remainingNanos = timeoutNanos; ; ) { 411 try { 412 return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS); 413 } catch (InterruptedException interrupt) { 414 interrupted = true; 415 remainingNanos = remainingNanos(startTime, timeoutNanos); 416 } 417 } 418 } finally { 419 if (interrupted) { 420 Thread.currentThread().interrupt(); 421 } 422 } 423 } 424 425 /** 426 * Enters this monitor. Blocks indefinitely, but may be interrupted. 427 * 428 * @throws InterruptedException if interrupted while waiting 429 */ 430 public void enterInterruptibly() throws InterruptedException { 431 lock.lockInterruptibly(); 432 } 433 434 /** 435 * Enters this monitor. Blocks at most the given time, and may be interrupted. 436 * 437 * @return whether the monitor was entered 438 * @throws InterruptedException if interrupted while waiting 439 * @since 28.0 (but only since 33.4.0 in the Android flavor) 440 */ 441 public boolean enterInterruptibly(Duration time) throws InterruptedException { 442 return enterInterruptibly(toNanosSaturated(time), TimeUnit.NANOSECONDS); 443 } 444 445 /** 446 * Enters this monitor. Blocks at most the given time, and may be interrupted. 447 * 448 * @return whether the monitor was entered 449 * @throws InterruptedException if interrupted while waiting 450 */ 451 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 452 public boolean enterInterruptibly(long time, TimeUnit unit) throws InterruptedException { 453 return lock.tryLock(time, unit); 454 } 455 456 /** 457 * Enters this monitor if it is possible to do so immediately. Does not block. 458 * 459 * <p><b>Note:</b> This method disregards the fairness setting of this monitor. 460 * 461 * @return whether the monitor was entered 462 */ 463 public boolean tryEnter() { 464 return lock.tryLock(); 465 } 466 467 /** 468 * Enters this monitor when the guard is satisfied. Blocks indefinitely, but may be interrupted. 469 * 470 * @throws InterruptedException if interrupted while waiting 471 */ 472 public void enterWhen(Guard guard) throws InterruptedException { 473 if (guard.monitor != this) { 474 throw new IllegalMonitorStateException(); 475 } 476 final ReentrantLock lock = this.lock; 477 boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); 478 lock.lockInterruptibly(); 479 480 boolean satisfied = false; 481 try { 482 if (!guard.isSatisfied()) { 483 await(guard, signalBeforeWaiting); 484 } 485 satisfied = true; 486 } finally { 487 if (!satisfied) { 488 leave(); 489 } 490 } 491 } 492 493 /** 494 * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both 495 * the time to acquire the lock and the time to wait for the guard to be satisfied, and may be 496 * interrupted. 497 * 498 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 499 * @throws InterruptedException if interrupted while waiting 500 * @since 28.0 (but only since 33.4.0 in the Android flavor) 501 */ 502 public boolean enterWhen(Guard guard, Duration time) throws InterruptedException { 503 return enterWhen(guard, toNanosSaturated(time), TimeUnit.NANOSECONDS); 504 } 505 506 /** 507 * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both 508 * the time to acquire the lock and the time to wait for the guard to be satisfied, and may be 509 * interrupted. 510 * 511 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 512 * @throws InterruptedException if interrupted while waiting 513 */ 514 @SuppressWarnings({ 515 "GoodTime", // should accept a java.time.Duration 516 "LabelledBreakTarget", // TODO(b/345814817): Maybe fix. 517 }) 518 public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException { 519 final long timeoutNanos = toSafeNanos(time, unit); 520 if (guard.monitor != this) { 521 throw new IllegalMonitorStateException(); 522 } 523 final ReentrantLock lock = this.lock; 524 boolean reentrant = lock.isHeldByCurrentThread(); 525 long startTime = 0L; 526 527 locked: 528 { 529 if (!fair) { 530 // Check interrupt status to get behavior consistent with fair case. 531 if (Thread.interrupted()) { 532 throw new InterruptedException(); 533 } 534 if (lock.tryLock()) { 535 break locked; 536 } 537 } 538 startTime = initNanoTime(timeoutNanos); 539 if (!lock.tryLock(time, unit)) { 540 return false; 541 } 542 } 543 544 boolean satisfied = false; 545 boolean threw = true; 546 try { 547 satisfied = 548 guard.isSatisfied() 549 || awaitNanos( 550 guard, 551 (startTime == 0L) ? timeoutNanos : remainingNanos(startTime, timeoutNanos), 552 reentrant); 553 threw = false; 554 return satisfied; 555 } finally { 556 if (!satisfied) { 557 try { 558 // Don't need to signal if timed out, but do if interrupted 559 if (threw && !reentrant) { 560 signalNextWaiter(); 561 } 562 } finally { 563 lock.unlock(); 564 } 565 } 566 } 567 } 568 569 /** Enters this monitor when the guard is satisfied. Blocks indefinitely. */ 570 public void enterWhenUninterruptibly(Guard guard) { 571 if (guard.monitor != this) { 572 throw new IllegalMonitorStateException(); 573 } 574 final ReentrantLock lock = this.lock; 575 boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); 576 lock.lock(); 577 578 boolean satisfied = false; 579 try { 580 if (!guard.isSatisfied()) { 581 awaitUninterruptibly(guard, signalBeforeWaiting); 582 } 583 satisfied = true; 584 } finally { 585 if (!satisfied) { 586 leave(); 587 } 588 } 589 } 590 591 /** 592 * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both 593 * the time to acquire the lock and the time to wait for the guard to be satisfied. 594 * 595 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 596 * @since 28.0 (but only since 33.4.0 in the Android flavor) 597 */ 598 public boolean enterWhenUninterruptibly(Guard guard, Duration time) { 599 return enterWhenUninterruptibly(guard, toNanosSaturated(time), TimeUnit.NANOSECONDS); 600 } 601 602 /** 603 * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both 604 * the time to acquire the lock and the time to wait for the guard to be satisfied. 605 * 606 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 607 */ 608 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 609 public boolean enterWhenUninterruptibly(Guard guard, long time, TimeUnit unit) { 610 final long timeoutNanos = toSafeNanos(time, unit); 611 if (guard.monitor != this) { 612 throw new IllegalMonitorStateException(); 613 } 614 final ReentrantLock lock = this.lock; 615 long startTime = 0L; 616 boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); 617 boolean interrupted = Thread.interrupted(); 618 try { 619 if (fair || !lock.tryLock()) { 620 startTime = initNanoTime(timeoutNanos); 621 for (long remainingNanos = timeoutNanos; ; ) { 622 try { 623 if (lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS)) { 624 break; 625 } else { 626 return false; 627 } 628 } catch (InterruptedException interrupt) { 629 interrupted = true; 630 remainingNanos = remainingNanos(startTime, timeoutNanos); 631 } 632 } 633 } 634 635 boolean satisfied = false; 636 try { 637 while (true) { 638 try { 639 if (guard.isSatisfied()) { 640 satisfied = true; 641 } else { 642 final long remainingNanos; 643 if (startTime == 0L) { 644 startTime = initNanoTime(timeoutNanos); 645 remainingNanos = timeoutNanos; 646 } else { 647 remainingNanos = remainingNanos(startTime, timeoutNanos); 648 } 649 satisfied = awaitNanos(guard, remainingNanos, signalBeforeWaiting); 650 } 651 return satisfied; 652 } catch (InterruptedException interrupt) { 653 interrupted = true; 654 signalBeforeWaiting = false; 655 } 656 } 657 } finally { 658 if (!satisfied) { 659 lock.unlock(); // No need to signal if timed out 660 } 661 } 662 } finally { 663 if (interrupted) { 664 Thread.currentThread().interrupt(); 665 } 666 } 667 } 668 669 /** 670 * Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does 671 * not wait for the guard to be satisfied. 672 * 673 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 674 */ 675 public boolean enterIf(Guard guard) { 676 if (guard.monitor != this) { 677 throw new IllegalMonitorStateException(); 678 } 679 final ReentrantLock lock = this.lock; 680 lock.lock(); 681 682 boolean satisfied = false; 683 try { 684 return satisfied = guard.isSatisfied(); 685 } finally { 686 if (!satisfied) { 687 lock.unlock(); 688 } 689 } 690 } 691 692 /** 693 * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the 694 * lock, but does not wait for the guard to be satisfied. 695 * 696 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 697 * @since 28.0 (but only since 33.4.0 in the Android flavor) 698 */ 699 public boolean enterIf(Guard guard, Duration time) { 700 return enterIf(guard, toNanosSaturated(time), TimeUnit.NANOSECONDS); 701 } 702 703 /** 704 * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the 705 * lock, but does not wait for the guard to be satisfied. 706 * 707 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 708 */ 709 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 710 public boolean enterIf(Guard guard, long time, TimeUnit unit) { 711 if (guard.monitor != this) { 712 throw new IllegalMonitorStateException(); 713 } 714 if (!enter(time, unit)) { 715 return false; 716 } 717 718 boolean satisfied = false; 719 try { 720 return satisfied = guard.isSatisfied(); 721 } finally { 722 if (!satisfied) { 723 lock.unlock(); 724 } 725 } 726 } 727 728 /** 729 * Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does 730 * not wait for the guard to be satisfied, and may be interrupted. 731 * 732 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 733 * @throws InterruptedException if interrupted while waiting 734 */ 735 public boolean enterIfInterruptibly(Guard guard) throws InterruptedException { 736 if (guard.monitor != this) { 737 throw new IllegalMonitorStateException(); 738 } 739 final ReentrantLock lock = this.lock; 740 lock.lockInterruptibly(); 741 742 boolean satisfied = false; 743 try { 744 return satisfied = guard.isSatisfied(); 745 } finally { 746 if (!satisfied) { 747 lock.unlock(); 748 } 749 } 750 } 751 752 /** 753 * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the 754 * lock, but does not wait for the guard to be satisfied, and may be interrupted. 755 * 756 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 757 * @since 28.0 (but only since 33.4.0 in the Android flavor) 758 */ 759 public boolean enterIfInterruptibly(Guard guard, Duration time) throws InterruptedException { 760 return enterIfInterruptibly(guard, toNanosSaturated(time), TimeUnit.NANOSECONDS); 761 } 762 763 /** 764 * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the 765 * lock, but does not wait for the guard to be satisfied, and may be interrupted. 766 * 767 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 768 */ 769 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 770 public boolean enterIfInterruptibly(Guard guard, long time, TimeUnit unit) 771 throws InterruptedException { 772 if (guard.monitor != this) { 773 throw new IllegalMonitorStateException(); 774 } 775 final ReentrantLock lock = this.lock; 776 if (!lock.tryLock(time, unit)) { 777 return false; 778 } 779 780 boolean satisfied = false; 781 try { 782 return satisfied = guard.isSatisfied(); 783 } finally { 784 if (!satisfied) { 785 lock.unlock(); 786 } 787 } 788 } 789 790 /** 791 * Enters this monitor if it is possible to do so immediately and the guard is satisfied. Does not 792 * block acquiring the lock and does not wait for the guard to be satisfied. 793 * 794 * <p><b>Note:</b> This method disregards the fairness setting of this monitor. 795 * 796 * @return whether the monitor was entered, which guarantees that the guard is now satisfied 797 */ 798 public boolean tryEnterIf(Guard guard) { 799 if (guard.monitor != this) { 800 throw new IllegalMonitorStateException(); 801 } 802 final ReentrantLock lock = this.lock; 803 if (!lock.tryLock()) { 804 return false; 805 } 806 807 boolean satisfied = false; 808 try { 809 return satisfied = guard.isSatisfied(); 810 } finally { 811 if (!satisfied) { 812 lock.unlock(); 813 } 814 } 815 } 816 817 /** 818 * Waits for the guard to be satisfied. Waits indefinitely, but may be interrupted. May be called 819 * only by a thread currently occupying this monitor. 820 * 821 * @throws InterruptedException if interrupted while waiting 822 */ 823 public void waitFor(Guard guard) throws InterruptedException { 824 if (!((guard.monitor == this) && lock.isHeldByCurrentThread())) { 825 throw new IllegalMonitorStateException(); 826 } 827 if (!guard.isSatisfied()) { 828 await(guard, true); 829 } 830 } 831 832 /** 833 * Waits for the guard to be satisfied. Waits at most the given time, and may be interrupted. May 834 * be called only by a thread currently occupying this monitor. 835 * 836 * @return whether the guard is now satisfied 837 * @throws InterruptedException if interrupted while waiting 838 * @since 28.0 (but only since 33.4.0 in the Android flavor) 839 */ 840 public boolean waitFor(Guard guard, Duration time) throws InterruptedException { 841 return waitFor(guard, toNanosSaturated(time), TimeUnit.NANOSECONDS); 842 } 843 844 /** 845 * Waits for the guard to be satisfied. Waits at most the given time, and may be interrupted. May 846 * be called only by a thread currently occupying this monitor. 847 * 848 * @return whether the guard is now satisfied 849 * @throws InterruptedException if interrupted while waiting 850 */ 851 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 852 public boolean waitFor(Guard guard, long time, TimeUnit unit) throws InterruptedException { 853 final long timeoutNanos = toSafeNanos(time, unit); 854 if (!((guard.monitor == this) && lock.isHeldByCurrentThread())) { 855 throw new IllegalMonitorStateException(); 856 } 857 if (guard.isSatisfied()) { 858 return true; 859 } 860 if (Thread.interrupted()) { 861 throw new InterruptedException(); 862 } 863 return awaitNanos(guard, timeoutNanos, true); 864 } 865 866 /** 867 * Waits for the guard to be satisfied. Waits indefinitely. May be called only by a thread 868 * currently occupying this monitor. 869 */ 870 public void waitForUninterruptibly(Guard guard) { 871 if (!((guard.monitor == this) && lock.isHeldByCurrentThread())) { 872 throw new IllegalMonitorStateException(); 873 } 874 if (!guard.isSatisfied()) { 875 awaitUninterruptibly(guard, true); 876 } 877 } 878 879 /** 880 * Waits for the guard to be satisfied. Waits at most the given time. May be called only by a 881 * thread currently occupying this monitor. 882 * 883 * @return whether the guard is now satisfied 884 * @since 28.0 (but only since 33.4.0 in the Android flavor) 885 */ 886 public boolean waitForUninterruptibly(Guard guard, Duration time) { 887 return waitForUninterruptibly(guard, toNanosSaturated(time), TimeUnit.NANOSECONDS); 888 } 889 890 /** 891 * Waits for the guard to be satisfied. Waits at most the given time. May be called only by a 892 * thread currently occupying this monitor. 893 * 894 * @return whether the guard is now satisfied 895 */ 896 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 897 public boolean waitForUninterruptibly(Guard guard, long time, TimeUnit unit) { 898 final long timeoutNanos = toSafeNanos(time, unit); 899 if (!((guard.monitor == this) && lock.isHeldByCurrentThread())) { 900 throw new IllegalMonitorStateException(); 901 } 902 if (guard.isSatisfied()) { 903 return true; 904 } 905 boolean signalBeforeWaiting = true; 906 final long startTime = initNanoTime(timeoutNanos); 907 boolean interrupted = Thread.interrupted(); 908 try { 909 for (long remainingNanos = timeoutNanos; ; ) { 910 try { 911 return awaitNanos(guard, remainingNanos, signalBeforeWaiting); 912 } catch (InterruptedException interrupt) { 913 interrupted = true; 914 if (guard.isSatisfied()) { 915 return true; 916 } 917 signalBeforeWaiting = false; 918 remainingNanos = remainingNanos(startTime, timeoutNanos); 919 } 920 } 921 } finally { 922 if (interrupted) { 923 Thread.currentThread().interrupt(); 924 } 925 } 926 } 927 928 /** Leaves this monitor. May be called only by a thread currently occupying this monitor. */ 929 public void leave() { 930 final ReentrantLock lock = this.lock; 931 try { 932 // No need to signal if we will still be holding the lock when we return 933 if (lock.getHoldCount() == 1) { 934 signalNextWaiter(); 935 } 936 } finally { 937 lock.unlock(); // Will throw IllegalMonitorStateException if not held 938 } 939 } 940 941 /** Returns whether this monitor is using a fair ordering policy. */ 942 public boolean isFair() { 943 return fair; 944 } 945 946 /** 947 * Returns whether this monitor is occupied by any thread. This method is designed for use in 948 * monitoring of the system state, not for synchronization control. 949 */ 950 public boolean isOccupied() { 951 return lock.isLocked(); 952 } 953 954 /** 955 * Returns whether the current thread is occupying this monitor (has entered more times than it 956 * has left). 957 */ 958 public boolean isOccupiedByCurrentThread() { 959 return lock.isHeldByCurrentThread(); 960 } 961 962 /** 963 * Returns the number of times the current thread has entered this monitor in excess of the number 964 * of times it has left. Returns 0 if the current thread is not occupying this monitor. 965 */ 966 public int getOccupiedDepth() { 967 return lock.getHoldCount(); 968 } 969 970 /** 971 * Returns an estimate of the number of threads waiting to enter this monitor. The value is only 972 * an estimate because the number of threads may change dynamically while this method traverses 973 * internal data structures. This method is designed for use in monitoring of the system state, 974 * not for synchronization control. 975 */ 976 public int getQueueLength() { 977 return lock.getQueueLength(); 978 } 979 980 /** 981 * Returns whether any threads are waiting to enter this monitor. Note that because cancellations 982 * may occur at any time, a {@code true} return does not guarantee that any other thread will ever 983 * enter this monitor. This method is designed primarily for use in monitoring of the system 984 * state. 985 */ 986 public boolean hasQueuedThreads() { 987 return lock.hasQueuedThreads(); 988 } 989 990 /** 991 * Queries whether the given thread is waiting to enter this monitor. Note that because 992 * cancellations may occur at any time, a {@code true} return does not guarantee that this thread 993 * will ever enter this monitor. This method is designed primarily for use in monitoring of the 994 * system state. 995 */ 996 public boolean hasQueuedThread(Thread thread) { 997 return lock.hasQueuedThread(thread); 998 } 999 1000 /** 1001 * Queries whether any threads are waiting for the given guard to become satisfied. Note that 1002 * because timeouts and interrupts may occur at any time, a {@code true} return does not guarantee 1003 * that the guard becoming satisfied in the future will awaken any threads. This method is 1004 * designed primarily for use in monitoring of the system state. 1005 */ 1006 public boolean hasWaiters(Guard guard) { 1007 return getWaitQueueLength(guard) > 0; 1008 } 1009 1010 /** 1011 * Returns an estimate of the number of threads waiting for the given guard to become satisfied. 1012 * Note that because timeouts and interrupts may occur at any time, the estimate serves only as an 1013 * upper bound on the actual number of waiters. This method is designed for use in monitoring of 1014 * the system state, not for synchronization control. 1015 */ 1016 public int getWaitQueueLength(Guard guard) { 1017 if (guard.monitor != this) { 1018 throw new IllegalMonitorStateException(); 1019 } 1020 lock.lock(); 1021 try { 1022 return guard.waiterCount; 1023 } finally { 1024 lock.unlock(); 1025 } 1026 } 1027 1028 /** 1029 * Returns unit.toNanos(time), additionally ensuring the returned value is not at risk of 1030 * overflowing or underflowing, by bounding the value between 0 and (Long.MAX_VALUE / 4) * 3. 1031 * Actually waiting for more than 219 years is not supported! 1032 */ 1033 private static long toSafeNanos(long time, TimeUnit unit) { 1034 long timeoutNanos = unit.toNanos(time); 1035 return Longs.constrainToRange(timeoutNanos, 0L, (Long.MAX_VALUE / 4) * 3); 1036 } 1037 1038 /** 1039 * Returns System.nanoTime() unless the timeout has already elapsed. Returns 0L if and only if the 1040 * timeout has already elapsed. 1041 */ 1042 private static long initNanoTime(long timeoutNanos) { 1043 if (timeoutNanos <= 0L) { 1044 return 0L; 1045 } else { 1046 long startTime = System.nanoTime(); 1047 return (startTime == 0L) ? 1L : startTime; 1048 } 1049 } 1050 1051 /** 1052 * Returns the remaining nanos until the given timeout, or 0L if the timeout has already elapsed. 1053 * Caller must have previously sanitized timeoutNanos using toSafeNanos. 1054 */ 1055 private static long remainingNanos(long startTime, long timeoutNanos) { 1056 // assert timeoutNanos == 0L || startTime != 0L; 1057 1058 // TODO : NOT CORRECT, BUT TESTS PASS ANYWAYS! 1059 // if (true) return timeoutNanos; 1060 // ONLY 2 TESTS FAIL IF WE DO: 1061 // if (true) return 0; 1062 1063 return (timeoutNanos <= 0L) ? 0L : timeoutNanos - (System.nanoTime() - startTime); 1064 } 1065 1066 /** 1067 * Signals some other thread waiting on a satisfied guard, if one exists. 1068 * 1069 * <p>We manage calls to this method carefully, to signal only when necessary, but never losing a 1070 * signal, which is the classic problem of this kind of concurrency construct. We must signal if 1071 * the current thread is about to relinquish the lock and may have changed the state protected by 1072 * the monitor, thereby causing some guard to be satisfied. 1073 * 1074 * <p>In addition, any thread that has been signalled when its guard was satisfied acquires the 1075 * responsibility of signalling the next thread when it again relinquishes the lock. Unlike a 1076 * normal Condition, there is no guarantee that an interrupted thread has not been signalled, 1077 * since the concurrency control must manage multiple Conditions. So this method must generally be 1078 * called when waits are interrupted. 1079 * 1080 * <p>On the other hand, if a signalled thread wakes up to discover that its guard is still not 1081 * satisfied, it does *not* need to call this method before returning to wait. This can only 1082 * happen due to spurious wakeup (ignorable) or another thread acquiring the lock before the 1083 * current thread can and returning the guard to the unsatisfied state. In the latter case the 1084 * other thread (last thread modifying the state protected by the monitor) takes over the 1085 * responsibility of signalling the next waiter. 1086 * 1087 * <p>This method must not be called from within a beginWaitingFor/endWaitingFor block, or else 1088 * the current thread's guard might be mistakenly signalled, leading to a lost signal. 1089 */ 1090 @GuardedBy("lock") 1091 private void signalNextWaiter() { 1092 for (Guard guard = activeGuards; guard != null; guard = guard.next) { 1093 if (isSatisfied(guard)) { 1094 guard.condition.signal(); 1095 break; 1096 } 1097 } 1098 } 1099 1100 /** 1101 * Exactly like signalNextWaiter, but caller guarantees that guardToSkip need not be considered, 1102 * because caller has previously checked that guardToSkip.isSatisfied() returned false. An 1103 * optimization for the case that guardToSkip.isSatisfied() may be expensive. 1104 * 1105 * <p>We decided against using this method, since in practice, isSatisfied() is likely to be very 1106 * cheap (typically one field read). Resurrect this method if you find that not to be true. 1107 */ 1108 // @GuardedBy("lock") 1109 // private void signalNextWaiterSkipping(Guard guardToSkip) { 1110 // for (Guard guard = activeGuards; guard != null; guard = guard.next) { 1111 // if (guard != guardToSkip && isSatisfied(guard)) { 1112 // guard.condition.signal(); 1113 // break; 1114 // } 1115 // } 1116 // } 1117 1118 /** 1119 * Exactly like guard.isSatisfied(), but in addition signals all waiting threads in the (hopefully 1120 * unlikely) event that isSatisfied() throws. 1121 */ 1122 @GuardedBy("lock") 1123 private boolean isSatisfied(Guard guard) { 1124 try { 1125 return guard.isSatisfied(); 1126 } catch (Throwable throwable) { 1127 // Any Exception is either a RuntimeException or sneaky checked exception. 1128 signalAllWaiters(); 1129 throw throwable; 1130 } 1131 } 1132 1133 /** Signals all threads waiting on guards. */ 1134 @GuardedBy("lock") 1135 private void signalAllWaiters() { 1136 for (Guard guard = activeGuards; guard != null; guard = guard.next) { 1137 guard.condition.signalAll(); 1138 } 1139 } 1140 1141 /** Records that the current thread is about to wait on the specified guard. */ 1142 @GuardedBy("lock") 1143 private void beginWaitingFor(Guard guard) { 1144 int waiters = guard.waiterCount++; 1145 if (waiters == 0) { 1146 // push guard onto activeGuards 1147 guard.next = activeGuards; 1148 activeGuards = guard; 1149 } 1150 } 1151 1152 /** Records that the current thread is no longer waiting on the specified guard. */ 1153 @GuardedBy("lock") 1154 private void endWaitingFor(Guard guard) { 1155 int waiters = --guard.waiterCount; 1156 if (waiters == 0) { 1157 // unlink guard from activeGuards 1158 for (Guard p = activeGuards, pred = null; ; pred = p, p = p.next) { 1159 if (p == guard) { 1160 if (pred == null) { 1161 activeGuards = p.next; 1162 } else { 1163 pred.next = p.next; 1164 } 1165 p.next = null; // help GC 1166 break; 1167 } 1168 } 1169 } 1170 } 1171 1172 /* 1173 * Methods that loop waiting on a guard's condition until the guard is satisfied, while recording 1174 * this fact so that other threads know to check our guard and signal us. It's caller's 1175 * responsibility to ensure that the guard is *not* currently satisfied. 1176 */ 1177 1178 @GuardedBy("lock") 1179 private void await(Guard guard, boolean signalBeforeWaiting) throws InterruptedException { 1180 if (signalBeforeWaiting) { 1181 signalNextWaiter(); 1182 } 1183 beginWaitingFor(guard); 1184 try { 1185 do { 1186 guard.condition.await(); 1187 } while (!guard.isSatisfied()); 1188 } finally { 1189 endWaitingFor(guard); 1190 } 1191 } 1192 1193 @GuardedBy("lock") 1194 private void awaitUninterruptibly(Guard guard, boolean signalBeforeWaiting) { 1195 if (signalBeforeWaiting) { 1196 signalNextWaiter(); 1197 } 1198 beginWaitingFor(guard); 1199 try { 1200 do { 1201 guard.condition.awaitUninterruptibly(); 1202 } while (!guard.isSatisfied()); 1203 } finally { 1204 endWaitingFor(guard); 1205 } 1206 } 1207 1208 /** Caller should check before calling that guard is not satisfied. */ 1209 @GuardedBy("lock") 1210 private boolean awaitNanos(Guard guard, long nanos, boolean signalBeforeWaiting) 1211 throws InterruptedException { 1212 boolean firstTime = true; 1213 try { 1214 do { 1215 if (nanos <= 0L) { 1216 return false; 1217 } 1218 if (firstTime) { 1219 if (signalBeforeWaiting) { 1220 signalNextWaiter(); 1221 } 1222 beginWaitingFor(guard); 1223 firstTime = false; 1224 } 1225 nanos = guard.condition.awaitNanos(nanos); 1226 } while (!guard.isSatisfied()); 1227 return true; 1228 } finally { 1229 if (!firstTime) { 1230 endWaitingFor(guard); 1231 } 1232 } 1233 } 1234}