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.
206@ElementTypesAreNonnullByDefault
207public final class Monitor {
208  // TODO(user): Use raw LockSupport or AbstractQueuedSynchronizer instead of ReentrantLock.
209  // TODO(user): "Port" jsr166 tests for ReentrantLock.
210  //
211  // TODO(user): Change API to make it impossible to use a Guard with the "wrong" monitor,
212  //    by making the monitor implicit, and to eliminate other sources of IMSE.
213  //    Imagine:
214  //    guard.lock();
215  //    try { /* monitor locked and guard satisfied here */ }
216  //    finally { guard.unlock(); }
217  // Here are Justin's design notes about this:
218  //
219  // This idea has come up from time to time, and I think one of my
220  // earlier versions of Monitor even did something like this. I ended
221  // up strongly favoring the current interface.
222  //
223  // I probably can't remember all the reasons (it's possible you
224  // could find them in the code review archives), but here are a few:
225  //
226  // 1. What about leaving/unlocking? Are you going to do
227  //    guard.enter() paired with monitor.leave()? That might get
228  //    confusing. It's nice for the finally block to look as close as
229  //    possible to the thing right before the try. You could have
230  //    guard.leave(), but that's a little odd as well because the
231  //    guard doesn't have anything to do with leaving. You can't
232  //    really enforce that the guard you're leaving is the same one
233  //    you entered with, and it doesn't actually matter.
234  //
235  // 2. Since you can enter the monitor without a guard at all, some
236  //    places you'll have monitor.enter()/monitor.leave() and other
237  //    places you'll have guard.enter()/guard.leave() even though
238  //    it's the same lock being acquired underneath. Always using
239  //    monitor.enterXXX()/monitor.leave() will make it really clear
240  //    which lock is held at any point in the code.
241  //
242  // 3. I think "enterWhen(notEmpty)" reads better than "notEmpty.enter()".
243  //
244  // TODO(user): Implement ReentrantLock features:
245  //    - toString() method
246  //    - getOwner() method
247  //    - getQueuedThreads() method
248  //    - getWaitingThreads(Guard) method
249  //    - implement Serializable
250  //    - redo the API to be as close to identical to ReentrantLock as possible,
251  //      since, after all, this class is also a reentrant mutual exclusion lock!?
252
253  /*
254   * One of the key challenges of this class is to prevent lost signals, while trying hard to
255   * minimize unnecessary signals. One simple and correct algorithm is to signal some other waiter
256   * with a satisfied guard (if one exists) whenever any thread occupying the monitor exits the
257   * monitor, either by unlocking all of its held locks, or by starting to wait for a guard. This
258   * includes exceptional exits, so all control paths involving signalling must be protected by a
259   * finally block.
260   *
261   * Further optimizations of this algorithm become increasingly subtle. A wait that terminates
262   * without the guard being satisfied (due to timeout, but not interrupt) can then immediately exit
263   * the monitor without signalling. If it timed out without being signalled, it does not need to
264   * "pass on" the signal to another thread. If it *was* signalled, then its guard must have been
265   * satisfied at the time of signal, and has since been modified by some other thread to be
266   * non-satisfied before reacquiring the lock, and that other thread takes over the responsibility
267   * of signaling the next waiter.
268   *
269   * Unlike the underlying Condition, if we are not careful, an interrupt *can* cause a signal to be
270   * lost, because the signal may be sent to a condition whose sole waiter has just been
271   * interrupted.
272   *
273   * Imagine a monitor with multiple guards. A thread enters the monitor, satisfies all the guards,
274   * and leaves, calling signalNextWaiter. With traditional locks and conditions, all the conditions
275   * need to be signalled because it is not known which if any of them have waiters (and hasWaiters
276   * can't be used reliably because of a check-then-act race). With our Monitor guards, we only
277   * signal the first active guard that is satisfied. But the corresponding thread may have already
278   * been interrupted and is waiting to reacquire the lock while still registered in activeGuards,
279   * in which case the signal is a no-op, and the bigger-picture signal is lost unless interrupted
280   * threads take special action by participating in the signal-passing game.
281   */
282
283  /*
284   * Timeout handling is intricate, especially given our ambitious goals:
285   * - Avoid underflow and overflow of timeout values when specified timeouts are close to
286   *   Long.MIN_VALUE or Long.MAX_VALUE.
287   * - Favor responding to interrupts over timeouts.
288   * - System.nanoTime() is expensive enough that we want to call it the minimum required number of
289   *   times, typically once before invoking a blocking method. This often requires keeping track of
290   *   the first time in a method that nanoTime() has been invoked, for which the special value 0L
291   *   is reserved to mean "uninitialized". If timeout is non-positive, then nanoTime need never be
292   *   called.
293   * - Keep behavior of fair and non-fair instances consistent.
294   */
295
296  /**
297   * A boolean condition for which a thread may wait. A {@code Guard} is associated with a single
298   * {@code Monitor}. The monitor may check the guard at arbitrary times from any thread occupying
299   * the monitor, so code should not be written to rely on how often a guard might or might not be
300   * checked.
301   *
302   * <p>If a {@code Guard} is passed into any method of a {@code Monitor} other than the one it is
303   * associated with, an {@link IllegalMonitorStateException} is thrown.
304   *
305   * @since 10.0
306   */
307  public abstract static class Guard {
308
309    @Weak final Monitor monitor;
310    final Condition condition;
311
312    @GuardedBy("monitor.lock")
313    int waiterCount = 0;
314
315    /** The next active guard */
316    @GuardedBy("monitor.lock")
317    @CheckForNull
318    Guard next;
319
320    protected Guard(Monitor monitor) {
321      this.monitor = checkNotNull(monitor, "monitor");
322      this.condition = monitor.lock.newCondition();
323    }
324
325    /**
326     * Evaluates this guard's boolean condition. This method is always called with the associated
327     * monitor already occupied. Implementations of this method must depend only on state protected
328     * by the associated monitor, and must not modify that state.
329     */
330    public abstract boolean isSatisfied();
331  }
332
333  /** Whether this monitor is fair. */
334  private final boolean fair;
335
336  /** The lock underlying this monitor. */
337  private final ReentrantLock lock;
338
339  /**
340   * The guards associated with this monitor that currently have waiters ({@code waiterCount > 0}).
341   * A linked list threaded through the Guard.next field.
342   */
343  @GuardedBy("lock")
344  @CheckForNull
345  private Guard activeGuards = null;
346
347  /**
348   * Creates a monitor with a non-fair (but fast) ordering policy. Equivalent to {@code
349   * Monitor(false)}.
350   */
351  public Monitor() {
352    this(false);
353  }
354
355  /**
356   * Creates a monitor with the given ordering policy.
357   *
358   * @param fair whether this monitor should use a fair ordering policy rather than a non-fair (but
359   *     fast) one
360   */
361  public Monitor(boolean fair) {
362    this.fair = fair;
363    this.lock = new ReentrantLock(fair);
364  }
365
366  /**
367   * Creates a new {@linkplain Guard guard} for this monitor.
368   *
369   * @param isSatisfied the new guard's boolean condition (see {@link Guard#isSatisfied
370   *     isSatisfied()})
371   * @since 21.0
372   */
373  public Guard newGuard(final BooleanSupplier isSatisfied) {
374    checkNotNull(isSatisfied, "isSatisfied");
375    return new Guard(this) {
376      @Override
377      public boolean isSatisfied() {
378        return isSatisfied.getAsBoolean();
379      }
380    };
381  }
382
383  /** Enters this monitor. Blocks indefinitely. */
384  public void enter() {
385    lock.lock();
386  }
387
388  /**
389   * Enters this monitor. Blocks at most the given time.
390   *
391   * @return whether the monitor was entered
392   * @since 28.0
393   */
394  public boolean enter(Duration time) {
395    return enter(toNanosSaturated(time), TimeUnit.NANOSECONDS);
396  }
397
398  /**
399   * Enters this monitor. Blocks at most the given time.
400   *
401   * @return whether the monitor was entered
402   */
403  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
404  public boolean enter(long time, TimeUnit unit) {
405    final long timeoutNanos = toSafeNanos(time, unit);
406    final ReentrantLock lock = this.lock;
407    if (!fair && lock.tryLock()) {
408      return true;
409    }
410    boolean interrupted = Thread.interrupted();
411    try {
412      final long startTime = System.nanoTime();
413      for (long remainingNanos = timeoutNanos; ; ) {
414        try {
415          return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS);
416        } catch (InterruptedException interrupt) {
417          interrupted = true;
418          remainingNanos = remainingNanos(startTime, timeoutNanos);
419        }
420      }
421    } finally {
422      if (interrupted) {
423        Thread.currentThread().interrupt();
424      }
425    }
426  }
427
428  /**
429   * Enters this monitor. Blocks indefinitely, but may be interrupted.
430   *
431   * @throws InterruptedException if interrupted while waiting
432   */
433  public void enterInterruptibly() throws InterruptedException {
434    lock.lockInterruptibly();
435  }
436
437  /**
438   * Enters this monitor. Blocks at most the given time, and may be interrupted.
439   *
440   * @return whether the monitor was entered
441   * @throws InterruptedException if interrupted while waiting
442   * @since 28.0
443   */
444  public boolean enterInterruptibly(Duration time) throws InterruptedException {
445    return enterInterruptibly(toNanosSaturated(time), TimeUnit.NANOSECONDS);
446  }
447
448  /**
449   * Enters this monitor. Blocks at most the given time, and may be interrupted.
450   *
451   * @return whether the monitor was entered
452   * @throws InterruptedException if interrupted while waiting
453   */
454  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
455  public boolean enterInterruptibly(long time, TimeUnit unit) throws InterruptedException {
456    return lock.tryLock(time, unit);
457  }
458
459  /**
460   * Enters this monitor if it is possible to do so immediately. Does not block.
461   *
462   * <p><b>Note:</b> This method disregards the fairness setting of this monitor.
463   *
464   * @return whether the monitor was entered
465   */
466  public boolean tryEnter() {
467    return lock.tryLock();
468  }
469
470  /**
471   * Enters this monitor when the guard is satisfied. Blocks indefinitely, but may be interrupted.
472   *
473   * @throws InterruptedException if interrupted while waiting
474   */
475  public void enterWhen(Guard guard) throws InterruptedException {
476    if (guard.monitor != this) {
477      throw new IllegalMonitorStateException();
478    }
479    final ReentrantLock lock = this.lock;
480    boolean signalBeforeWaiting = lock.isHeldByCurrentThread();
481    lock.lockInterruptibly();
482
483    boolean satisfied = false;
484    try {
485      if (!guard.isSatisfied()) {
486        await(guard, signalBeforeWaiting);
487      }
488      satisfied = true;
489    } finally {
490      if (!satisfied) {
491        leave();
492      }
493    }
494  }
495
496  /**
497   * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both
498   * the time to acquire the lock and the time to wait for the guard to be satisfied, and may be
499   * interrupted.
500   *
501   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
502   * @throws InterruptedException if interrupted while waiting
503   * @since 28.0
504   */
505  public boolean enterWhen(Guard guard, Duration time) throws InterruptedException {
506    return enterWhen(guard, toNanosSaturated(time), TimeUnit.NANOSECONDS);
507  }
508
509  /**
510   * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both
511   * the time to acquire the lock and the time to wait for the guard to be satisfied, and may be
512   * interrupted.
513   *
514   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
515   * @throws InterruptedException if interrupted while waiting
516   */
517  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
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
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
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
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
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
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}