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