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