001/*
002 * Copyright (C) 2010 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.util.concurrent;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.Beta;
020import com.google.common.annotations.GwtIncompatible;
021import com.google.common.primitives.Longs;
022import com.google.errorprone.annotations.concurrent.GuardedBy;
023import com.google.j2objc.annotations.Weak;
024import java.util.concurrent.TimeUnit;
025import java.util.concurrent.locks.Condition;
026import java.util.concurrent.locks.ReentrantLock;
027import org.checkerframework.checker.nullness.compatqual.NullableDecl;
028
029/**
030 * A synchronization abstraction supporting waiting on arbitrary boolean conditions.
031 *
032 * <p>This class is intended as a replacement for {@link ReentrantLock}. Code using {@code Monitor}
033 * is less error-prone and more readable than code using {@code ReentrantLock}, without significant
034 * performance loss. {@code Monitor} even has the potential for performance gain by optimizing the
035 * evaluation and signaling of conditions. Signaling is entirely <a
036 * href="http://en.wikipedia.org/wiki/Monitor_(synchronization)#Implicit_signaling">implicit</a>. By
037 * eliminating explicit signaling, this class can guarantee that only one thread is awakened when a
038 * condition becomes true (no "signaling storms" due to use of {@link
039 * java.util.concurrent.locks.Condition#signalAll Condition.signalAll}) and that no signals are lost
040 * (no "hangs" due to incorrect use of {@link java.util.concurrent.locks.Condition#signal
041 * Condition.signal}).
042 *
043 * <p>A thread is said to <i>occupy</i> a monitor if it has <i>entered</i> the monitor but not yet
044 * <i>left</i>. Only one thread may occupy a given monitor at any moment. A monitor is also
045 * reentrant, so a thread may enter a monitor any number of times, and then must leave the same
046 * number of times. The <i>enter</i> and <i>leave</i> operations have the same synchronization
047 * semantics as the built-in Java language synchronization primitives.
048 *
049 * <p>A call to any of the <i>enter</i> methods with <b>void</b> return type should always be
050 * followed immediately by a <i>try/finally</i> block to ensure that the current thread leaves the
051 * monitor cleanly:
052 *
053 * <pre>{@code
054 * monitor.enter();
055 * try {
056 *   // do things while occupying the monitor
057 * } finally {
058 *   monitor.leave();
059 * }
060 * }</pre>
061 *
062 * <p>A call to any of the <i>enter</i> methods with <b>boolean</b> return type should always appear
063 * as the condition of an <i>if</i> statement containing a <i>try/finally</i> block to ensure that
064 * the current thread leaves the monitor cleanly:
065 *
066 * <pre>{@code
067 * if (monitor.tryEnter()) {
068 *   try {
069 *     // do things while occupying the monitor
070 *   } finally {
071 *     monitor.leave();
072 *   }
073 * } else {
074 *   // do other things since the monitor was not available
075 * }
076 * }</pre>
077 *
078 * <h2>Comparison with {@code synchronized} and {@code ReentrantLock}</h2>
079 *
080 * <p>The following examples show a simple threadsafe holder expressed using {@code synchronized},
081 * {@link ReentrantLock}, and {@code Monitor}.
082 *
083 * <h3>{@code synchronized}</h3>
084 *
085 * <p>This version is the fewest lines of code, largely because the synchronization mechanism used
086 * is built into the language and runtime. But the programmer has to remember to avoid a couple of
087 * common bugs: The {@code wait()} must be inside a {@code while} instead of an {@code if}, and
088 * {@code notifyAll()} must be used instead of {@code notify()} because there are two different
089 * logical conditions being awaited.
090 *
091 * <pre>{@code
092 * public class SafeBox<V> {
093 *   private V value;
094 *
095 *   public synchronized V get() throws InterruptedException {
096 *     while (value == null) {
097 *       wait();
098 *     }
099 *     V result = value;
100 *     value = null;
101 *     notifyAll();
102 *     return result;
103 *   }
104 *
105 *   public synchronized void set(V newValue) throws InterruptedException {
106 *     while (value != null) {
107 *       wait();
108 *     }
109 *     value = newValue;
110 *     notifyAll();
111 *   }
112 * }
113 * }</pre>
114 *
115 * <h3>{@code ReentrantLock}</h3>
116 *
117 * <p>This version is much more verbose than the {@code synchronized} version, and still suffers
118 * from the need for the programmer to remember to use {@code while} instead of {@code if}. However,
119 * one advantage is that we can introduce two separate {@code Condition} objects, which allows us to
120 * use {@code signal()} instead of {@code signalAll()}, which may be a performance benefit.
121 *
122 * <pre>{@code
123 * public class SafeBox<V> {
124 *   private V value;
125 *   private final ReentrantLock lock = new ReentrantLock();
126 *   private final Condition valuePresent = lock.newCondition();
127 *   private final Condition valueAbsent = lock.newCondition();
128 *
129 *   public V get() throws InterruptedException {
130 *     lock.lock();
131 *     try {
132 *       while (value == null) {
133 *         valuePresent.await();
134 *       }
135 *       V result = value;
136 *       value = null;
137 *       valueAbsent.signal();
138 *       return result;
139 *     } finally {
140 *       lock.unlock();
141 *     }
142 *   }
143 *
144 *   public void set(V newValue) throws InterruptedException {
145 *     lock.lock();
146 *     try {
147 *       while (value != null) {
148 *         valueAbsent.await();
149 *       }
150 *       value = newValue;
151 *       valuePresent.signal();
152 *     } finally {
153 *       lock.unlock();
154 *     }
155 *   }
156 * }
157 * }</pre>
158 *
159 * <h3>{@code Monitor}</h3>
160 *
161 * <p>This version adds some verbosity around the {@code Guard} objects, but removes that same
162 * verbosity, and more, from the {@code get} and {@code set} methods. {@code Monitor} implements the
163 * same efficient signaling as we had to hand-code in the {@code ReentrantLock} version above.
164 * Finally, the programmer no longer has to hand-code the wait loop, and therefore doesn't have to
165 * remember to use {@code while} instead of {@code if}.
166 *
167 * <pre>{@code
168 * public class SafeBox<V> {
169 *   private V value;
170 *   private final Monitor monitor = new Monitor();
171 *   private final Monitor.Guard valuePresent = monitor.newGuard(() -> value != null);
172 *   private final Monitor.Guard valueAbsent = monitor.newGuard(() -> value == null);
173 *
174 *   public V get() throws InterruptedException {
175 *     monitor.enterWhen(valuePresent);
176 *     try {
177 *       V result = value;
178 *       value = null;
179 *       return result;
180 *     } finally {
181 *       monitor.leave();
182 *     }
183 *   }
184 *
185 *   public void set(V newValue) throws InterruptedException {
186 *     monitor.enterWhen(valueAbsent);
187 *     try {
188 *       value = newValue;
189 *     } finally {
190 *       monitor.leave();
191 *     }
192 *   }
193 * }
194 * }</pre>
195 *
196 * @author Justin T. Sampson
197 * @author Martin Buchholz
198 * @since 10.0
199 */
200@Beta
201@GwtIncompatible
202@SuppressWarnings("GuardedBy") // TODO(b/35466881): Fix or suppress.
203public final class Monitor {
204  // TODO(user): Use raw LockSupport or AbstractQueuedSynchronizer instead of ReentrantLock.
205  // TODO(user): "Port" jsr166 tests for ReentrantLock.
206  //
207  // TODO(user): Change API to make it impossible to use a Guard with the "wrong" monitor,
208  //    by making the monitor implicit, and to eliminate other sources of IMSE.
209  //    Imagine:
210  //    guard.lock();
211  //    try { /* monitor locked and guard satisfied here */ }
212  //    finally { guard.unlock(); }
213  // Here are Justin's design notes about this:
214  //
215  // This idea has come up from time to time, and I think one of my
216  // earlier versions of Monitor even did something like this. I ended
217  // up strongly favoring the current interface.
218  //
219  // I probably can't remember all the reasons (it's possible you
220  // could find them in the code review archives), but here are a few:
221  //
222  // 1. What about leaving/unlocking? Are you going to do
223  //    guard.enter() paired with monitor.leave()? That might get
224  //    confusing. It's nice for the finally block to look as close as
225  //    possible to the thing right before the try. You could have
226  //    guard.leave(), but that's a little odd as well because the
227  //    guard doesn't have anything to do with leaving. You can't
228  //    really enforce that the guard you're leaving is the same one
229  //    you entered with, and it doesn't actually matter.
230  //
231  // 2. Since you can enter the monitor without a guard at all, some
232  //    places you'll have monitor.enter()/monitor.leave() and other
233  //    places you'll have guard.enter()/guard.leave() even though
234  //    it's the same lock being acquired underneath. Always using
235  //    monitor.enterXXX()/monitor.leave() will make it really clear
236  //    which lock is held at any point in the code.
237  //
238  // 3. I think "enterWhen(notEmpty)" reads better than "notEmpty.enter()".
239  //
240  // TODO(user): Implement ReentrantLock features:
241  //    - toString() method
242  //    - getOwner() method
243  //    - getQueuedThreads() method
244  //    - getWaitingThreads(Guard) method
245  //    - implement Serializable
246  //    - redo the API to be as close to identical to ReentrantLock as possible,
247  //      since, after all, this class is also a reentrant mutual exclusion lock!?
248
249  /*
250   * One of the key challenges of this class is to prevent lost signals, while trying hard to
251   * minimize unnecessary signals. One simple and correct algorithm is to signal some other waiter
252   * with a satisfied guard (if one exists) whenever any thread occupying the monitor exits the
253   * monitor, either by unlocking all of its held locks, or by starting to wait for a guard. This
254   * includes exceptional exits, so all control paths involving signalling must be protected by a
255   * finally block.
256   *
257   * Further optimizations of this algorithm become increasingly subtle. A wait that terminates
258   * without the guard being satisfied (due to timeout, but not interrupt) can then immediately exit
259   * the monitor without signalling. If it timed out without being signalled, it does not need to
260   * "pass on" the signal to another thread. If it *was* signalled, then its guard must have been
261   * satisfied at the time of signal, and has since been modified by some other thread to be
262   * non-satisfied before reacquiring the lock, and that other thread takes over the responsibility
263   * of signaling the next waiter.
264   *
265   * Unlike the underlying Condition, if we are not careful, an interrupt *can* cause a signal to be
266   * lost, because the signal may be sent to a condition whose sole waiter has just been
267   * interrupted.
268   *
269   * Imagine a monitor with multiple guards. A thread enters the monitor, satisfies all the guards,
270   * and leaves, calling signalNextWaiter. With traditional locks and conditions, all the conditions
271   * need to be signalled because it is not known which if any of them have waiters (and hasWaiters
272   * can't be used reliably because of a check-then-act race). With our Monitor guards, we only
273   * signal the first active guard that is satisfied. But the corresponding thread may have already
274   * been interrupted and is waiting to reacquire the lock while still registered in activeGuards,
275   * in which case the signal is a no-op, and the bigger-picture signal is lost unless interrupted
276   * threads take special action by 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 of
286   *   the first time in a method that nanoTime() has been invoked, for which the special value 0L
287   *   is reserved to mean "uninitialized". If timeout is non-positive, then nanoTime need never be
288   *   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    @Weak 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    @NullableDecl
315    Guard next;
316
317    protected Guard(Monitor monitor) {
318      this.monitor = checkNotNull(monitor, "monitor");
319      this.condition = monitor.lock.newCondition();
320    }
321
322    /**
323     * Evaluates this guard's boolean condition. This method is always called with the associated
324     * monitor already occupied. Implementations of this method must depend only on state protected
325     * by the associated monitor, and must not modify that state.
326     */
327    public abstract boolean isSatisfied();
328  }
329
330  /** Whether this monitor is fair. */
331  private final boolean fair;
332
333  /** The lock underlying this monitor. */
334  private final ReentrantLock lock;
335
336  /**
337   * The guards associated with this monitor that currently have waiters ({@code waiterCount > 0}).
338   * A linked list threaded through the Guard.next field.
339   */
340  @GuardedBy("lock")
341  private Guard activeGuards = null;
342
343  /**
344   * Creates a monitor with a non-fair (but fast) ordering policy. Equivalent to {@code
345   * Monitor(false)}.
346   */
347  public Monitor() {
348    this(false);
349  }
350
351  /**
352   * Creates a monitor with the given ordering policy.
353   *
354   * @param fair whether this monitor should use a fair ordering policy rather than a non-fair (but
355   *     fast) one
356   */
357  public Monitor(boolean fair) {
358    this.fair = fair;
359    this.lock = new ReentrantLock(fair);
360  }
361
362  /** Enters this monitor. Blocks indefinitely. */
363  public void enter() {
364    lock.lock();
365  }
366
367  /**
368   * Enters this monitor. Blocks at most the given time.
369   *
370   * @return whether the monitor was entered
371   */
372  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
373  public boolean enter(long time, TimeUnit unit) {
374    final long timeoutNanos = toSafeNanos(time, unit);
375    final ReentrantLock lock = this.lock;
376    if (!fair && lock.tryLock()) {
377      return true;
378    }
379    boolean interrupted = Thread.interrupted();
380    try {
381      final long startTime = System.nanoTime();
382      for (long remainingNanos = timeoutNanos; ; ) {
383        try {
384          return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS);
385        } catch (InterruptedException interrupt) {
386          interrupted = true;
387          remainingNanos = remainingNanos(startTime, timeoutNanos);
388        }
389      }
390    } finally {
391      if (interrupted) {
392        Thread.currentThread().interrupt();
393      }
394    }
395  }
396
397  /**
398   * Enters this monitor. Blocks indefinitely, but may be interrupted.
399   *
400   * @throws InterruptedException if interrupted while waiting
401   */
402  public void enterInterruptibly() throws InterruptedException {
403    lock.lockInterruptibly();
404  }
405
406  /**
407   * Enters this monitor. Blocks at most the given time, and may be interrupted.
408   *
409   * @return whether the monitor was entered
410   * @throws InterruptedException if interrupted while waiting
411   */
412  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
413  public boolean enterInterruptibly(long time, TimeUnit unit) throws InterruptedException {
414    return lock.tryLock(time, unit);
415  }
416
417  /**
418   * Enters this monitor if it is possible to do so immediately. Does not block.
419   *
420   * <p><b>Note:</b> This method disregards the fairness setting of this monitor.
421   *
422   * @return whether the monitor was entered
423   */
424  public boolean tryEnter() {
425    return lock.tryLock();
426  }
427
428  /**
429   * Enters this monitor when the guard is satisfied. Blocks indefinitely, but may be interrupted.
430   *
431   * @throws InterruptedException if interrupted while waiting
432   */
433  public void enterWhen(Guard guard) throws InterruptedException {
434    if (guard.monitor != this) {
435      throw new IllegalMonitorStateException();
436    }
437    final ReentrantLock lock = this.lock;
438    boolean signalBeforeWaiting = lock.isHeldByCurrentThread();
439    lock.lockInterruptibly();
440
441    boolean satisfied = false;
442    try {
443      if (!guard.isSatisfied()) {
444        await(guard, signalBeforeWaiting);
445      }
446      satisfied = true;
447    } finally {
448      if (!satisfied) {
449        leave();
450      }
451    }
452  }
453
454  /**
455   * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both
456   * the time to acquire the lock and the time to wait for the guard to be satisfied, and may be
457   * interrupted.
458   *
459   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
460   * @throws InterruptedException if interrupted while waiting
461   */
462  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
463  public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException {
464    final long timeoutNanos = toSafeNanos(time, unit);
465    if (guard.monitor != this) {
466      throw new IllegalMonitorStateException();
467    }
468    final ReentrantLock lock = this.lock;
469    boolean reentrant = lock.isHeldByCurrentThread();
470    long startTime = 0L;
471
472    locked:
473    {
474      if (!fair) {
475        // Check interrupt status to get behavior consistent with fair case.
476        if (Thread.interrupted()) {
477          throw new InterruptedException();
478        }
479        if (lock.tryLock()) {
480          break locked;
481        }
482      }
483      startTime = initNanoTime(timeoutNanos);
484      if (!lock.tryLock(time, unit)) {
485        return false;
486      }
487    }
488
489    boolean satisfied = false;
490    boolean threw = true;
491    try {
492      satisfied =
493          guard.isSatisfied()
494              || awaitNanos(
495                  guard,
496                  (startTime == 0L) ? timeoutNanos : remainingNanos(startTime, timeoutNanos),
497                  reentrant);
498      threw = false;
499      return satisfied;
500    } finally {
501      if (!satisfied) {
502        try {
503          // Don't need to signal if timed out, but do if interrupted
504          if (threw && !reentrant) {
505            signalNextWaiter();
506          }
507        } finally {
508          lock.unlock();
509        }
510      }
511    }
512  }
513
514  /** Enters this monitor when the guard is satisfied. Blocks indefinitely. */
515  public void enterWhenUninterruptibly(Guard guard) {
516    if (guard.monitor != this) {
517      throw new IllegalMonitorStateException();
518    }
519    final ReentrantLock lock = this.lock;
520    boolean signalBeforeWaiting = lock.isHeldByCurrentThread();
521    lock.lock();
522
523    boolean satisfied = false;
524    try {
525      if (!guard.isSatisfied()) {
526        awaitUninterruptibly(guard, signalBeforeWaiting);
527      }
528      satisfied = true;
529    } finally {
530      if (!satisfied) {
531        leave();
532      }
533    }
534  }
535
536  /**
537   * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both
538   * the time to acquire the lock and the time to wait for the guard to be satisfied.
539   *
540   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
541   */
542  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
543  public boolean enterWhenUninterruptibly(Guard guard, long time, TimeUnit unit) {
544    final long timeoutNanos = toSafeNanos(time, unit);
545    if (guard.monitor != this) {
546      throw new IllegalMonitorStateException();
547    }
548    final ReentrantLock lock = this.lock;
549    long startTime = 0L;
550    boolean signalBeforeWaiting = lock.isHeldByCurrentThread();
551    boolean interrupted = Thread.interrupted();
552    try {
553      if (fair || !lock.tryLock()) {
554        startTime = initNanoTime(timeoutNanos);
555        for (long remainingNanos = timeoutNanos; ; ) {
556          try {
557            if (lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS)) {
558              break;
559            } else {
560              return false;
561            }
562          } catch (InterruptedException interrupt) {
563            interrupted = true;
564            remainingNanos = remainingNanos(startTime, timeoutNanos);
565          }
566        }
567      }
568
569      boolean satisfied = false;
570      try {
571        while (true) {
572          try {
573            if (guard.isSatisfied()) {
574              satisfied = true;
575            } else {
576              final long remainingNanos;
577              if (startTime == 0L) {
578                startTime = initNanoTime(timeoutNanos);
579                remainingNanos = timeoutNanos;
580              } else {
581                remainingNanos = remainingNanos(startTime, timeoutNanos);
582              }
583              satisfied = awaitNanos(guard, remainingNanos, signalBeforeWaiting);
584            }
585            return satisfied;
586          } catch (InterruptedException interrupt) {
587            interrupted = true;
588            signalBeforeWaiting = false;
589          }
590        }
591      } finally {
592        if (!satisfied) {
593          lock.unlock(); // No need to signal if timed out
594        }
595      }
596    } finally {
597      if (interrupted) {
598        Thread.currentThread().interrupt();
599      }
600    }
601  }
602
603  /**
604   * Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does
605   * not wait for the guard to be satisfied.
606   *
607   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
608   */
609  public boolean enterIf(Guard guard) {
610    if (guard.monitor != this) {
611      throw new IllegalMonitorStateException();
612    }
613    final ReentrantLock lock = this.lock;
614    lock.lock();
615
616    boolean satisfied = false;
617    try {
618      return satisfied = guard.isSatisfied();
619    } finally {
620      if (!satisfied) {
621        lock.unlock();
622      }
623    }
624  }
625
626  /**
627   * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
628   * lock, but does not wait for the guard to be satisfied.
629   *
630   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
631   */
632  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
633  public boolean enterIf(Guard guard, long time, TimeUnit unit) {
634    if (guard.monitor != this) {
635      throw new IllegalMonitorStateException();
636    }
637    if (!enter(time, unit)) {
638      return false;
639    }
640
641    boolean satisfied = false;
642    try {
643      return satisfied = guard.isSatisfied();
644    } finally {
645      if (!satisfied) {
646        lock.unlock();
647      }
648    }
649  }
650
651  /**
652   * Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does
653   * not wait for the guard to be satisfied, and may be interrupted.
654   *
655   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
656   * @throws InterruptedException if interrupted while waiting
657   */
658  public boolean enterIfInterruptibly(Guard guard) throws InterruptedException {
659    if (guard.monitor != this) {
660      throw new IllegalMonitorStateException();
661    }
662    final ReentrantLock lock = this.lock;
663    lock.lockInterruptibly();
664
665    boolean satisfied = false;
666    try {
667      return satisfied = guard.isSatisfied();
668    } finally {
669      if (!satisfied) {
670        lock.unlock();
671      }
672    }
673  }
674
675  /**
676   * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
677   * lock, but does not wait for the guard to be satisfied, and may be interrupted.
678   *
679   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
680   */
681  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
682  public boolean enterIfInterruptibly(Guard guard, long time, TimeUnit unit)
683      throws InterruptedException {
684    if (guard.monitor != this) {
685      throw new IllegalMonitorStateException();
686    }
687    final ReentrantLock lock = this.lock;
688    if (!lock.tryLock(time, unit)) {
689      return false;
690    }
691
692    boolean satisfied = false;
693    try {
694      return satisfied = guard.isSatisfied();
695    } finally {
696      if (!satisfied) {
697        lock.unlock();
698      }
699    }
700  }
701
702  /**
703   * Enters this monitor if it is possible to do so immediately and the guard is satisfied. Does not
704   * block acquiring the lock and does not wait for the guard to be satisfied.
705   *
706   * <p><b>Note:</b> This method disregards the fairness setting of this monitor.
707   *
708   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
709   */
710  public boolean tryEnterIf(Guard guard) {
711    if (guard.monitor != this) {
712      throw new IllegalMonitorStateException();
713    }
714    final ReentrantLock lock = this.lock;
715    if (!lock.tryLock()) {
716      return false;
717    }
718
719    boolean satisfied = false;
720    try {
721      return satisfied = guard.isSatisfied();
722    } finally {
723      if (!satisfied) {
724        lock.unlock();
725      }
726    }
727  }
728
729  /**
730   * Waits for the guard to be satisfied. Waits indefinitely, but may be interrupted. May be called
731   * only by a thread currently occupying this monitor.
732   *
733   * @throws InterruptedException if interrupted while waiting
734   */
735  public void waitFor(Guard guard) throws InterruptedException {
736    if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) {
737      throw new IllegalMonitorStateException();
738    }
739    if (!guard.isSatisfied()) {
740      await(guard, true);
741    }
742  }
743
744  /**
745   * Waits for the guard to be satisfied. Waits at most the given time, and may be interrupted. May
746   * be called only by a thread currently occupying this monitor.
747   *
748   * @return whether the guard is now satisfied
749   * @throws InterruptedException if interrupted while waiting
750   */
751  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
752  public boolean waitFor(Guard guard, long time, TimeUnit unit) throws InterruptedException {
753    final long timeoutNanos = toSafeNanos(time, unit);
754    if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) {
755      throw new IllegalMonitorStateException();
756    }
757    if (guard.isSatisfied()) {
758      return true;
759    }
760    if (Thread.interrupted()) {
761      throw new InterruptedException();
762    }
763    return awaitNanos(guard, timeoutNanos, true);
764  }
765
766  /**
767   * Waits for the guard to be satisfied. Waits indefinitely. May be called only by a thread
768   * currently occupying this monitor.
769   */
770  public void waitForUninterruptibly(Guard guard) {
771    if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) {
772      throw new IllegalMonitorStateException();
773    }
774    if (!guard.isSatisfied()) {
775      awaitUninterruptibly(guard, true);
776    }
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  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
786  public boolean waitForUninterruptibly(Guard guard, long time, TimeUnit unit) {
787    final long timeoutNanos = toSafeNanos(time, unit);
788    if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) {
789      throw new IllegalMonitorStateException();
790    }
791    if (guard.isSatisfied()) {
792      return true;
793    }
794    boolean signalBeforeWaiting = true;
795    final long startTime = initNanoTime(timeoutNanos);
796    boolean interrupted = Thread.interrupted();
797    try {
798      for (long remainingNanos = timeoutNanos; ; ) {
799        try {
800          return awaitNanos(guard, remainingNanos, signalBeforeWaiting);
801        } catch (InterruptedException interrupt) {
802          interrupted = true;
803          if (guard.isSatisfied()) {
804            return true;
805          }
806          signalBeforeWaiting = false;
807          remainingNanos = remainingNanos(startTime, timeoutNanos);
808        }
809      }
810    } finally {
811      if (interrupted) {
812        Thread.currentThread().interrupt();
813      }
814    }
815  }
816
817  /** Leaves this monitor. May be called only by a thread currently occupying this monitor. */
818  public void leave() {
819    final ReentrantLock lock = this.lock;
820    try {
821      // No need to signal if we will still be holding the lock when we return
822      if (lock.getHoldCount() == 1) {
823        signalNextWaiter();
824      }
825    } finally {
826      lock.unlock(); // Will throw IllegalMonitorStateException if not held
827    }
828  }
829
830  /** Returns whether this monitor is using a fair ordering policy. */
831  public boolean isFair() {
832    return fair;
833  }
834
835  /**
836   * Returns whether this monitor is occupied by any thread. This method is designed for use in
837   * monitoring of the system state, not for synchronization control.
838   */
839  public boolean isOccupied() {
840    return lock.isLocked();
841  }
842
843  /**
844   * Returns whether the current thread is occupying this monitor (has entered more times than it
845   * has left).
846   */
847  public boolean isOccupiedByCurrentThread() {
848    return lock.isHeldByCurrentThread();
849  }
850
851  /**
852   * Returns the number of times the current thread has entered this monitor in excess of the number
853   * of times it has left. Returns 0 if the current thread is not occupying this monitor.
854   */
855  public int getOccupiedDepth() {
856    return lock.getHoldCount();
857  }
858
859  /**
860   * Returns an estimate of the number of threads waiting to enter this monitor. The value is only
861   * an estimate because the number of threads may change dynamically while this method traverses
862   * internal data structures. This method is designed for use in monitoring of the system state,
863   * not for synchronization control.
864   */
865  public int getQueueLength() {
866    return lock.getQueueLength();
867  }
868
869  /**
870   * Returns whether any threads are waiting to enter this monitor. Note that because cancellations
871   * may occur at any time, a {@code true} return does not guarantee that any other thread will ever
872   * enter this monitor. This method is designed primarily for use in monitoring of the system
873   * state.
874   */
875  public boolean hasQueuedThreads() {
876    return lock.hasQueuedThreads();
877  }
878
879  /**
880   * Queries whether the given thread is waiting to enter this monitor. Note that because
881   * cancellations may occur at any time, a {@code true} return does not guarantee that this thread
882   * will ever enter this monitor. This method is designed primarily for use in monitoring of the
883   * system state.
884   */
885  public boolean hasQueuedThread(Thread thread) {
886    return lock.hasQueuedThread(thread);
887  }
888
889  /**
890   * Queries whether any threads are waiting for the given guard to become satisfied. Note that
891   * because timeouts and interrupts may occur at any time, a {@code true} return does not guarantee
892   * that the guard becoming satisfied in the future will awaken any threads. This method is
893   * designed primarily for use in monitoring of the system state.
894   */
895  public boolean hasWaiters(Guard guard) {
896    return getWaitQueueLength(guard) > 0;
897  }
898
899  /**
900   * Returns an estimate of the number of threads waiting for the given guard to become satisfied.
901   * Note that because timeouts and interrupts may occur at any time, the estimate serves only as an
902   * upper bound on the actual number of waiters. This method is designed for use in monitoring of
903   * the system state, not for synchronization control.
904   */
905  public int getWaitQueueLength(Guard guard) {
906    if (guard.monitor != this) {
907      throw new IllegalMonitorStateException();
908    }
909    lock.lock();
910    try {
911      return guard.waiterCount;
912    } finally {
913      lock.unlock();
914    }
915  }
916
917  /**
918   * Returns unit.toNanos(time), additionally ensuring the returned value is not at risk of
919   * overflowing or underflowing, by bounding the value between 0 and (Long.MAX_VALUE / 4) * 3.
920   * Actually waiting for more than 219 years is not supported!
921   */
922  private static long toSafeNanos(long time, TimeUnit unit) {
923    long timeoutNanos = unit.toNanos(time);
924    return Longs.constrainToRange(timeoutNanos, 0L, (Long.MAX_VALUE / 4) * 3);
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}