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