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