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