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