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