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