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