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