001/*
002 * Copyright (C) 2011 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;
018import static java.util.Objects.requireNonNull;
019
020import com.google.common.annotations.GwtIncompatible;
021import com.google.common.annotations.J2ktIncompatible;
022import com.google.common.annotations.VisibleForTesting;
023import com.google.common.base.MoreObjects;
024import com.google.common.base.Preconditions;
025import com.google.common.collect.ImmutableSet;
026import com.google.common.collect.Lists;
027import com.google.common.collect.MapMaker;
028import com.google.common.collect.Maps;
029import com.google.common.collect.Sets;
030import com.google.j2objc.annotations.Weak;
031import java.util.ArrayList;
032import java.util.Arrays;
033import java.util.Collections;
034import java.util.EnumMap;
035import java.util.List;
036import java.util.Map;
037import java.util.Map.Entry;
038import java.util.Set;
039import java.util.concurrent.ConcurrentMap;
040import java.util.concurrent.TimeUnit;
041import java.util.concurrent.locks.ReentrantLock;
042import java.util.concurrent.locks.ReentrantReadWriteLock;
043import java.util.logging.Level;
044import org.checkerframework.checker.nullness.qual.Nullable;
045
046/**
047 * The {@code CycleDetectingLockFactory} creates {@link ReentrantLock} instances and {@link
048 * ReentrantReadWriteLock} instances that detect potential deadlock by checking for cycles in lock
049 * acquisition order.
050 *
051 * <p>Potential deadlocks detected when calling the {@code lock()}, {@code lockInterruptibly()}, or
052 * {@code tryLock()} methods will result in the execution of the {@link Policy} specified when
053 * creating the factory. The currently available policies are:
054 *
055 * <ul>
056 *   <li>DISABLED
057 *   <li>WARN
058 *   <li>THROW
059 * </ul>
060 *
061 * <p>The locks created by a factory instance will detect lock acquisition cycles with locks created
062 * by other {@code CycleDetectingLockFactory} instances (except those with {@code Policy.DISABLED}).
063 * A lock's behavior when a cycle is detected, however, is defined by the {@code Policy} of the
064 * factory that created it. This allows detection of cycles across components while delegating
065 * control over lock behavior to individual components.
066 *
067 * <p>Applications are encouraged to use a {@code CycleDetectingLockFactory} to create any locks for
068 * which external/unmanaged code is executed while the lock is held. (See caveats under
069 * <strong>Performance</strong>).
070 *
071 * <p><strong>Cycle Detection</strong>
072 *
073 * <p>Deadlocks can arise when locks are acquired in an order that forms a cycle. In a simple
074 * example involving two locks and two threads, deadlock occurs when one thread acquires Lock A, and
075 * then Lock B, while another thread acquires Lock B, and then Lock A:
076 *
077 * <pre>
078 * Thread1: acquire(LockA) --X acquire(LockB)
079 * Thread2: acquire(LockB) --X acquire(LockA)
080 * </pre>
081 *
082 * <p>Neither thread will progress because each is waiting for the other. In more complex
083 * applications, cycles can arise from interactions among more than 2 locks:
084 *
085 * <pre>
086 * Thread1: acquire(LockA) --X acquire(LockB)
087 * Thread2: acquire(LockB) --X acquire(LockC)
088 * ...
089 * ThreadN: acquire(LockN) --X acquire(LockA)
090 * </pre>
091 *
092 * <p>The implementation detects cycles by constructing a directed graph in which each lock
093 * represents a node and each edge represents an acquisition ordering between two locks.
094 *
095 * <ul>
096 *   <li>Each lock adds (and removes) itself to/from a ThreadLocal Set of acquired locks when the
097 *       Thread acquires its first hold (and releases its last remaining hold).
098 *   <li>Before the lock is acquired, the lock is checked against the current set of acquired
099 *       locks---to each of the acquired locks, an edge from the soon-to-be-acquired lock is either
100 *       verified or created.
101 *   <li>If a new edge needs to be created, the outgoing edges of the acquired locks are traversed
102 *       to check for a cycle that reaches the lock to be acquired. If no cycle is detected, a new
103 *       "safe" edge is created.
104 *   <li>If a cycle is detected, an "unsafe" (cyclic) edge is created to represent a potential
105 *       deadlock situation, and the appropriate Policy is executed.
106 * </ul>
107 *
108 * <p>Note that detection of potential deadlock does not necessarily indicate that deadlock will
109 * happen, as it is possible that higher level application logic prevents the cyclic lock
110 * acquisition from occurring. One example of a false positive is:
111 *
112 * <pre>
113 * LockA -&gt; LockB -&gt; LockC
114 * LockA -&gt; LockC -&gt; LockB
115 * </pre>
116 *
117 * <p><strong>ReadWriteLocks</strong>
118 *
119 * <p>While {@code ReadWriteLock} instances have different properties and can form cycles without
120 * potential deadlock, this class treats {@code ReadWriteLock} instances as equivalent to
121 * traditional exclusive locks. Although this increases the false positives that the locks detect
122 * (i.e. cycles that will not actually result in deadlock), it simplifies the algorithm and
123 * implementation considerably. The assumption is that a user of this factory wishes to eliminate
124 * any cyclic acquisition ordering.
125 *
126 * <p><strong>Explicit Lock Acquisition Ordering</strong>
127 *
128 * <p>The {@link CycleDetectingLockFactory.WithExplicitOrdering} class can be used to enforce an
129 * application-specific ordering in addition to performing general cycle detection.
130 *
131 * <p><strong>Garbage Collection</strong>
132 *
133 * <p>In order to allow proper garbage collection of unused locks, the edges of the lock graph are
134 * weak references.
135 *
136 * <p><strong>Performance</strong>
137 *
138 * <p>The extra bookkeeping done by cycle detecting locks comes at some cost to performance.
139 * Benchmarks (as of December 2011) show that:
140 *
141 * <ul>
142 *   <li>for an unnested {@code lock()} and {@code unlock()}, a cycle detecting lock takes 38ns as
143 *       opposed to the 24ns taken by a plain lock.
144 *   <li>for nested locking, the cost increases with the depth of the nesting:
145 *       <ul>
146 *         <li>2 levels: average of 64ns per lock()/unlock()
147 *         <li>3 levels: average of 77ns per lock()/unlock()
148 *         <li>4 levels: average of 99ns per lock()/unlock()
149 *         <li>5 levels: average of 103ns per lock()/unlock()
150 *         <li>10 levels: average of 184ns per lock()/unlock()
151 *         <li>20 levels: average of 393ns per lock()/unlock()
152 *       </ul>
153 * </ul>
154 *
155 * <p>As such, the CycleDetectingLockFactory may not be suitable for performance-critical
156 * applications which involve tightly-looped or deeply-nested locking algorithms.
157 *
158 * @author Darick Tong
159 * @since 13.0
160 */
161@J2ktIncompatible
162@GwtIncompatible
163public class CycleDetectingLockFactory {
164
165  /**
166   * Encapsulates the action to be taken when a potential deadlock is encountered. Clients can use
167   * one of the predefined {@link Policies} or specify a custom implementation. Implementations must
168   * be thread-safe.
169   *
170   * @since 13.0
171   */
172  public interface Policy {
173
174    /**
175     * Called when a potential deadlock is encountered. Implementations can throw the given {@code
176     * exception} and/or execute other desired logic.
177     *
178     * <p>Note that the method will be called even upon an invocation of {@code tryLock()}. Although
179     * {@code tryLock()} technically recovers from deadlock by eventually timing out, this behavior
180     * is chosen based on the assumption that it is the application's wish to prohibit any cyclical
181     * lock acquisitions.
182     */
183    void handlePotentialDeadlock(PotentialDeadlockException exception);
184  }
185
186  /**
187   * Pre-defined {@link Policy} implementations.
188   *
189   * @since 13.0
190   */
191  public enum Policies implements Policy {
192    /**
193     * When potential deadlock is detected, this policy results in the throwing of the {@code
194     * PotentialDeadlockException} indicating the potential deadlock, which includes stack traces
195     * illustrating the cycle in lock acquisition order.
196     */
197    THROW {
198      @Override
199      public void handlePotentialDeadlock(PotentialDeadlockException e) {
200        throw e;
201      }
202    },
203
204    /**
205     * When potential deadlock is detected, this policy results in the logging of a {@link
206     * Level#SEVERE} message indicating the potential deadlock, which includes stack traces
207     * illustrating the cycle in lock acquisition order.
208     */
209    WARN {
210      @Override
211      public void handlePotentialDeadlock(PotentialDeadlockException e) {
212        logger.get().log(Level.SEVERE, "Detected potential deadlock", e);
213      }
214    },
215
216    /**
217     * Disables cycle detection. This option causes the factory to return unmodified lock
218     * implementations provided by the JDK, and is provided to allow applications to easily
219     * parameterize when cycle detection is enabled.
220     *
221     * <p>Note that locks created by a factory with this policy will <em>not</em> participate the
222     * cycle detection performed by locks created by other factories.
223     */
224    DISABLED {
225      @Override
226      public void handlePotentialDeadlock(PotentialDeadlockException e) {}
227    };
228  }
229
230  /** Creates a new factory with the specified policy. */
231  public static CycleDetectingLockFactory newInstance(Policy policy) {
232    return new CycleDetectingLockFactory(policy);
233  }
234
235  /** Equivalent to {@code newReentrantLock(lockName, false)}. */
236  public ReentrantLock newReentrantLock(String lockName) {
237    return newReentrantLock(lockName, false);
238  }
239
240  /**
241   * Creates a {@link ReentrantLock} with the given fairness policy. The {@code lockName} is used in
242   * the warning or exception output to help identify the locks involved in the detected deadlock.
243   */
244  public ReentrantLock newReentrantLock(String lockName, boolean fair) {
245    return policy == Policies.DISABLED
246        ? new ReentrantLock(fair)
247        : new CycleDetectingReentrantLock(new LockGraphNode(lockName), fair);
248  }
249
250  /** Equivalent to {@code newReentrantReadWriteLock(lockName, false)}. */
251  public ReentrantReadWriteLock newReentrantReadWriteLock(String lockName) {
252    return newReentrantReadWriteLock(lockName, false);
253  }
254
255  /**
256   * Creates a {@link ReentrantReadWriteLock} with the given fairness policy. The {@code lockName}
257   * is used in the warning or exception output to help identify the locks involved in the detected
258   * deadlock.
259   */
260  public ReentrantReadWriteLock newReentrantReadWriteLock(String lockName, boolean fair) {
261    return policy == Policies.DISABLED
262        ? new ReentrantReadWriteLock(fair)
263        : new CycleDetectingReentrantReadWriteLock(new LockGraphNode(lockName), fair);
264  }
265
266  // A static mapping from an Enum type to its set of LockGraphNodes.
267  private static final ConcurrentMap<
268          Class<? extends Enum<?>>, Map<? extends Enum<?>, LockGraphNode>>
269      lockGraphNodesPerType = new MapMaker().weakKeys().makeMap();
270
271  /** Creates a {@code CycleDetectingLockFactory.WithExplicitOrdering<E>}. */
272  public static <E extends Enum<E>> WithExplicitOrdering<E> newInstanceWithExplicitOrdering(
273      Class<E> enumClass, Policy policy) {
274    // createNodes maps each enumClass to a Map with the corresponding enum key
275    // type.
276    checkNotNull(enumClass);
277    checkNotNull(policy);
278    @SuppressWarnings("unchecked")
279    Map<E, LockGraphNode> lockGraphNodes = (Map<E, LockGraphNode>) getOrCreateNodes(enumClass);
280    return new WithExplicitOrdering<>(policy, lockGraphNodes);
281  }
282
283  @SuppressWarnings("unchecked")
284  private static <E extends Enum<E>> Map<? extends E, LockGraphNode> getOrCreateNodes(
285      Class<E> clazz) {
286    Map<E, LockGraphNode> existing = (Map<E, LockGraphNode>) lockGraphNodesPerType.get(clazz);
287    if (existing != null) {
288      return existing;
289    }
290    Map<E, LockGraphNode> created = createNodes(clazz);
291    existing = (Map<E, LockGraphNode>) lockGraphNodesPerType.putIfAbsent(clazz, created);
292    return MoreObjects.firstNonNull(existing, created);
293  }
294
295  /**
296   * For a given Enum type, creates an immutable map from each of the Enum's values to a
297   * corresponding LockGraphNode, with the {@code allowedPriorLocks} and {@code
298   * disallowedPriorLocks} prepopulated with nodes according to the natural ordering of the
299   * associated Enum values.
300   */
301  @VisibleForTesting
302  static <E extends Enum<E>> Map<E, LockGraphNode> createNodes(Class<E> clazz) {
303    EnumMap<E, LockGraphNode> map = Maps.newEnumMap(clazz);
304    E[] keys = clazz.getEnumConstants();
305    int numKeys = keys.length;
306    ArrayList<LockGraphNode> nodes = Lists.newArrayListWithCapacity(numKeys);
307    // Create a LockGraphNode for each enum value.
308    for (E key : keys) {
309      LockGraphNode node = new LockGraphNode(getLockName(key));
310      nodes.add(node);
311      map.put(key, node);
312    }
313    // Pre-populate all allowedPriorLocks with nodes of smaller ordinal.
314    for (int i = 1; i < numKeys; i++) {
315      nodes.get(i).checkAcquiredLocks(Policies.THROW, nodes.subList(0, i));
316    }
317    // Pre-populate all disallowedPriorLocks with nodes of larger ordinal.
318    for (int i = 0; i < numKeys - 1; i++) {
319      nodes.get(i).checkAcquiredLocks(Policies.DISABLED, nodes.subList(i + 1, numKeys));
320    }
321    return Collections.unmodifiableMap(map);
322  }
323
324  /**
325   * For the given Enum value {@code rank}, returns the value's {@code "EnumClass.name"}, which is
326   * used in exception and warning output.
327   */
328  private static String getLockName(Enum<?> rank) {
329    return rank.getDeclaringClass().getSimpleName() + "." + rank.name();
330  }
331
332  /**
333   * A {@code CycleDetectingLockFactory.WithExplicitOrdering} provides the additional enforcement of
334   * an application-specified ordering of lock acquisitions. The application defines the allowed
335   * ordering with an {@code Enum} whose values each correspond to a lock type. The order in which
336   * the values are declared dictates the allowed order of lock acquisition. In other words, locks
337   * corresponding to smaller values of {@link Enum#ordinal()} should only be acquired before locks
338   * with larger ordinals. Example:
339   *
340   * <pre>{@code
341   * enum MyLockOrder {
342   *   FIRST, SECOND, THIRD;
343   * }
344   *
345   * CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory =
346   *   CycleDetectingLockFactory.newInstanceWithExplicitOrdering(Policies.THROW);
347   *
348   * Lock lock1 = factory.newReentrantLock(MyLockOrder.FIRST);
349   * Lock lock2 = factory.newReentrantLock(MyLockOrder.SECOND);
350   * Lock lock3 = factory.newReentrantLock(MyLockOrder.THIRD);
351   *
352   * lock1.lock();
353   * lock3.lock();
354   * lock2.lock();  // will throw an IllegalStateException
355   * }</pre>
356   *
357   * <p>As with all locks created by instances of {@code CycleDetectingLockFactory} explicitly
358   * ordered locks participate in general cycle detection with all other cycle detecting locks, and
359   * a lock's behavior when detecting a cyclic lock acquisition is defined by the {@code Policy} of
360   * the factory that created it.
361   *
362   * <p>Note, however, that although multiple locks can be created for a given Enum value, whether
363   * it be through separate factory instances or through multiple calls to the same factory,
364   * attempting to acquire multiple locks with the same Enum value (within the same thread) will
365   * result in an IllegalStateException regardless of the factory's policy. For example:
366   *
367   * <pre>{@code
368   * CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory1 =
369   *   CycleDetectingLockFactory.newInstanceWithExplicitOrdering(...);
370   * CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory2 =
371   *   CycleDetectingLockFactory.newInstanceWithExplicitOrdering(...);
372   *
373   * Lock lockA = factory1.newReentrantLock(MyLockOrder.FIRST);
374   * Lock lockB = factory1.newReentrantLock(MyLockOrder.FIRST);
375   * Lock lockC = factory2.newReentrantLock(MyLockOrder.FIRST);
376   *
377   * lockA.lock();
378   *
379   * lockB.lock();  // will throw an IllegalStateException
380   * lockC.lock();  // will throw an IllegalStateException
381   *
382   * lockA.lock();  // reentrant acquisition is okay
383   * }</pre>
384   *
385   * <p>It is the responsibility of the application to ensure that multiple lock instances with the
386   * same rank are never acquired in the same thread.
387   *
388   * @param <E> The Enum type representing the explicit lock ordering.
389   * @since 13.0
390   */
391  public static final class WithExplicitOrdering<E extends Enum<E>>
392      extends CycleDetectingLockFactory {
393
394    private final Map<E, LockGraphNode> lockGraphNodes;
395
396    @VisibleForTesting
397    WithExplicitOrdering(Policy policy, Map<E, LockGraphNode> lockGraphNodes) {
398      super(policy);
399      this.lockGraphNodes = lockGraphNodes;
400    }
401
402    /** Equivalent to {@code newReentrantLock(rank, false)}. */
403    public ReentrantLock newReentrantLock(E rank) {
404      return newReentrantLock(rank, false);
405    }
406
407    /**
408     * Creates a {@link ReentrantLock} with the given fairness policy and rank. The values returned
409     * by {@link Enum#getDeclaringClass()} and {@link Enum#name()} are used to describe the lock in
410     * warning or exception output.
411     *
412     * @throws IllegalStateException If the factory has already created a {@code Lock} with the
413     *     specified rank.
414     */
415    public ReentrantLock newReentrantLock(E rank, boolean fair) {
416      return policy == Policies.DISABLED
417          ? new ReentrantLock(fair)
418          // requireNonNull is safe because createNodes inserts an entry for every E.
419          // (If the caller passes `null` for the `rank` parameter, this will throw, but that's OK.)
420          : new CycleDetectingReentrantLock(requireNonNull(lockGraphNodes.get(rank)), fair);
421    }
422
423    /** Equivalent to {@code newReentrantReadWriteLock(rank, false)}. */
424    public ReentrantReadWriteLock newReentrantReadWriteLock(E rank) {
425      return newReentrantReadWriteLock(rank, false);
426    }
427
428    /**
429     * Creates a {@link ReentrantReadWriteLock} with the given fairness policy and rank. The values
430     * returned by {@link Enum#getDeclaringClass()} and {@link Enum#name()} are used to describe the
431     * lock in warning or exception output.
432     *
433     * @throws IllegalStateException If the factory has already created a {@code Lock} with the
434     *     specified rank.
435     */
436    public ReentrantReadWriteLock newReentrantReadWriteLock(E rank, boolean fair) {
437      return policy == Policies.DISABLED
438          ? new ReentrantReadWriteLock(fair)
439          // requireNonNull is safe because createNodes inserts an entry for every E.
440          // (If the caller passes `null` for the `rank` parameter, this will throw, but that's OK.)
441          : new CycleDetectingReentrantReadWriteLock(
442              requireNonNull(lockGraphNodes.get(rank)), fair);
443    }
444  }
445
446  //////// Implementation /////////
447
448  private static final LazyLogger logger = new LazyLogger(CycleDetectingLockFactory.class);
449
450  final Policy policy;
451
452  private CycleDetectingLockFactory(Policy policy) {
453    this.policy = checkNotNull(policy);
454  }
455
456  /**
457   * Tracks the currently acquired locks for each Thread, kept up to date by calls to {@link
458   * #aboutToAcquire(CycleDetectingLock)} and {@link #lockStateChanged(CycleDetectingLock)}.
459   */
460  // This is logically a Set, but an ArrayList is used to minimize the amount
461  // of allocation done on lock()/unlock().
462  private static final ThreadLocal<ArrayList<LockGraphNode>> acquiredLocks =
463      new ThreadLocal<ArrayList<LockGraphNode>>() {
464        @Override
465        protected ArrayList<LockGraphNode> initialValue() {
466          return Lists.<LockGraphNode>newArrayListWithCapacity(3);
467        }
468      };
469
470  /**
471   * A Throwable used to record a stack trace that illustrates an example of a specific lock
472   * acquisition ordering. The top of the stack trace is truncated such that it starts with the
473   * acquisition of the lock in question, e.g.
474   *
475   * <pre>
476   * com...ExampleStackTrace: LockB -&gt; LockC
477   *   at com...CycleDetectingReentrantLock.lock(CycleDetectingLockFactory.java:443)
478   *   at ...
479   *   at ...
480   *   at com...MyClass.someMethodThatAcquiresLockB(MyClass.java:123)
481   * </pre>
482   */
483  private static class ExampleStackTrace extends IllegalStateException {
484
485    static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0];
486
487    static final ImmutableSet<String> EXCLUDED_CLASS_NAMES =
488        ImmutableSet.of(
489            CycleDetectingLockFactory.class.getName(),
490            ExampleStackTrace.class.getName(),
491            LockGraphNode.class.getName());
492
493    ExampleStackTrace(LockGraphNode node1, LockGraphNode node2) {
494      super(node1.getLockName() + " -> " + node2.getLockName());
495      StackTraceElement[] origStackTrace = getStackTrace();
496      for (int i = 0, n = origStackTrace.length; i < n; i++) {
497        if (WithExplicitOrdering.class.getName().equals(origStackTrace[i].getClassName())) {
498          // For pre-populated disallowedPriorLocks edges, omit the stack trace.
499          setStackTrace(EMPTY_STACK_TRACE);
500          break;
501        }
502        if (!EXCLUDED_CLASS_NAMES.contains(origStackTrace[i].getClassName())) {
503          setStackTrace(Arrays.copyOfRange(origStackTrace, i, n));
504          break;
505        }
506      }
507    }
508  }
509
510  /**
511   * Represents a detected cycle in lock acquisition ordering. The exception includes a causal chain
512   * of {@code ExampleStackTrace} instances to illustrate the cycle, e.g.
513   *
514   * <pre>
515   * com....PotentialDeadlockException: Potential Deadlock from LockC -&gt; ReadWriteA
516   *   at ...
517   *   at ...
518   * Caused by: com...ExampleStackTrace: LockB -&gt; LockC
519   *   at ...
520   *   at ...
521   * Caused by: com...ExampleStackTrace: ReadWriteA -&gt; LockB
522   *   at ...
523   *   at ...
524   * </pre>
525   *
526   * <p>Instances are logged for the {@code Policies.WARN}, and thrown for {@code Policies.THROW}.
527   *
528   * @since 13.0
529   */
530  public static final class PotentialDeadlockException extends ExampleStackTrace {
531
532    private final ExampleStackTrace conflictingStackTrace;
533
534    private PotentialDeadlockException(
535        LockGraphNode node1, LockGraphNode node2, ExampleStackTrace conflictingStackTrace) {
536      super(node1, node2);
537      this.conflictingStackTrace = conflictingStackTrace;
538      initCause(conflictingStackTrace);
539    }
540
541    public ExampleStackTrace getConflictingStackTrace() {
542      return conflictingStackTrace;
543    }
544
545    /**
546     * Appends the chain of messages from the {@code conflictingStackTrace} to the original {@code
547     * message}.
548     */
549    @Override
550    public String getMessage() {
551      // requireNonNull is safe because ExampleStackTrace sets a non-null message.
552      StringBuilder message = new StringBuilder(requireNonNull(super.getMessage()));
553      for (Throwable t = conflictingStackTrace; t != null; t = t.getCause()) {
554        message.append(", ").append(t.getMessage());
555      }
556      return message.toString();
557    }
558  }
559
560  /**
561   * Internal Lock implementations implement the {@code CycleDetectingLock} interface, allowing the
562   * detection logic to treat all locks in the same manner.
563   */
564  private interface CycleDetectingLock {
565
566    /** @return the {@link LockGraphNode} associated with this lock. */
567    LockGraphNode getLockGraphNode();
568
569    /** @return {@code true} if the current thread has acquired this lock. */
570    boolean isAcquiredByCurrentThread();
571  }
572
573  /**
574   * A {@code LockGraphNode} associated with each lock instance keeps track of the directed edges in
575   * the lock acquisition graph.
576   */
577  private static class LockGraphNode {
578
579    /**
580     * The map tracking the locks that are known to be acquired before this lock, each associated
581     * with an example stack trace. Locks are weakly keyed to allow proper garbage collection when
582     * they are no longer referenced.
583     */
584    final Map<LockGraphNode, ExampleStackTrace> allowedPriorLocks =
585        new MapMaker().weakKeys().makeMap();
586
587    /**
588     * The map tracking lock nodes that can cause a lock acquisition cycle if acquired before this
589     * node.
590     */
591    final Map<LockGraphNode, PotentialDeadlockException> disallowedPriorLocks =
592        new MapMaker().weakKeys().makeMap();
593
594    final String lockName;
595
596    LockGraphNode(String lockName) {
597      this.lockName = Preconditions.checkNotNull(lockName);
598    }
599
600    String getLockName() {
601      return lockName;
602    }
603
604    void checkAcquiredLocks(Policy policy, List<LockGraphNode> acquiredLocks) {
605      for (LockGraphNode acquiredLock : acquiredLocks) {
606        checkAcquiredLock(policy, acquiredLock);
607      }
608    }
609
610    /**
611     * Checks the acquisition-ordering between {@code this}, which is about to be acquired, and the
612     * specified {@code acquiredLock}.
613     *
614     * <p>When this method returns, the {@code acquiredLock} should be in either the {@code
615     * preAcquireLocks} map, for the case in which it is safe to acquire {@code this} after the
616     * {@code acquiredLock}, or in the {@code disallowedPriorLocks} map, in which case it is not
617     * safe.
618     */
619    void checkAcquiredLock(Policy policy, LockGraphNode acquiredLock) {
620      // checkAcquiredLock() should never be invoked by a lock that has already
621      // been acquired. For unordered locks, aboutToAcquire() ensures this by
622      // checking isAcquiredByCurrentThread(). For ordered locks, however, this
623      // can happen because multiple locks may share the same LockGraphNode. In
624      // this situation, throw an IllegalStateException as defined by contract
625      // described in the documentation of WithExplicitOrdering.
626      Preconditions.checkState(
627          this != acquiredLock,
628          "Attempted to acquire multiple locks with the same rank %s",
629          acquiredLock.getLockName());
630
631      if (allowedPriorLocks.containsKey(acquiredLock)) {
632        // The acquisition ordering from "acquiredLock" to "this" has already
633        // been verified as safe. In a properly written application, this is
634        // the common case.
635        return;
636      }
637      PotentialDeadlockException previousDeadlockException = disallowedPriorLocks.get(acquiredLock);
638      if (previousDeadlockException != null) {
639        // Previously determined to be an unsafe lock acquisition.
640        // Create a new PotentialDeadlockException with the same causal chain
641        // (the example cycle) as that of the cached exception.
642        PotentialDeadlockException exception =
643            new PotentialDeadlockException(
644                acquiredLock, this, previousDeadlockException.getConflictingStackTrace());
645        policy.handlePotentialDeadlock(exception);
646        return;
647      }
648      // Otherwise, it's the first time seeing this lock relationship. Look for
649      // a path from the acquiredLock to this.
650      Set<LockGraphNode> seen = Sets.newIdentityHashSet();
651      ExampleStackTrace path = acquiredLock.findPathTo(this, seen);
652
653      if (path == null) {
654        // this can be safely acquired after the acquiredLock.
655        //
656        // Note that there is a race condition here which can result in missing
657        // a cyclic edge: it's possible for two threads to simultaneous find
658        // "safe" edges which together form a cycle. Preventing this race
659        // condition efficiently without _introducing_ deadlock is probably
660        // tricky. For now, just accept the race condition---missing a warning
661        // now and then is still better than having no deadlock detection.
662        allowedPriorLocks.put(acquiredLock, new ExampleStackTrace(acquiredLock, this));
663      } else {
664        // Unsafe acquisition order detected. Create and cache a
665        // PotentialDeadlockException.
666        PotentialDeadlockException exception =
667            new PotentialDeadlockException(acquiredLock, this, path);
668        disallowedPriorLocks.put(acquiredLock, exception);
669        policy.handlePotentialDeadlock(exception);
670      }
671    }
672
673    /**
674     * Performs a depth-first traversal of the graph edges defined by each node's {@code
675     * allowedPriorLocks} to find a path between {@code this} and the specified {@code lock}.
676     *
677     * @return If a path was found, a chained {@link ExampleStackTrace} illustrating the path to the
678     *     {@code lock}, or {@code null} if no path was found.
679     */
680    private @Nullable ExampleStackTrace findPathTo(LockGraphNode node, Set<LockGraphNode> seen) {
681      if (!seen.add(this)) {
682        return null; // Already traversed this node.
683      }
684      ExampleStackTrace found = allowedPriorLocks.get(node);
685      if (found != null) {
686        return found; // Found a path ending at the node!
687      }
688      // Recurse the edges.
689      for (Entry<LockGraphNode, ExampleStackTrace> entry : allowedPriorLocks.entrySet()) {
690        LockGraphNode preAcquiredLock = entry.getKey();
691        found = preAcquiredLock.findPathTo(node, seen);
692        if (found != null) {
693          // One of this node's allowedPriorLocks found a path. Prepend an
694          // ExampleStackTrace(preAcquiredLock, this) to the returned chain of
695          // ExampleStackTraces.
696          ExampleStackTrace path = new ExampleStackTrace(preAcquiredLock, this);
697          path.setStackTrace(entry.getValue().getStackTrace());
698          path.initCause(found);
699          return path;
700        }
701      }
702      return null;
703    }
704  }
705
706  /**
707   * CycleDetectingLock implementations must call this method before attempting to acquire the lock.
708   */
709  private void aboutToAcquire(CycleDetectingLock lock) {
710    if (!lock.isAcquiredByCurrentThread()) {
711      // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get
712      ArrayList<LockGraphNode> acquiredLockList = requireNonNull(acquiredLocks.get());
713      LockGraphNode node = lock.getLockGraphNode();
714      node.checkAcquiredLocks(policy, acquiredLockList);
715      acquiredLockList.add(node);
716    }
717  }
718
719  /**
720   * CycleDetectingLock implementations must call this method in a {@code finally} clause after any
721   * attempt to change the lock state, including both lock and unlock attempts. Failure to do so can
722   * result in corrupting the acquireLocks set.
723   */
724  private static void lockStateChanged(CycleDetectingLock lock) {
725    if (!lock.isAcquiredByCurrentThread()) {
726      // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get
727      ArrayList<LockGraphNode> acquiredLockList = requireNonNull(acquiredLocks.get());
728      LockGraphNode node = lock.getLockGraphNode();
729      // Iterate in reverse because locks are usually locked/unlocked in a
730      // LIFO order.
731      for (int i = acquiredLockList.size() - 1; i >= 0; i--) {
732        if (acquiredLockList.get(i) == node) {
733          acquiredLockList.remove(i);
734          break;
735        }
736      }
737    }
738  }
739
740  final class CycleDetectingReentrantLock extends ReentrantLock implements CycleDetectingLock {
741
742    private final LockGraphNode lockGraphNode;
743
744    private CycleDetectingReentrantLock(LockGraphNode lockGraphNode, boolean fair) {
745      super(fair);
746      this.lockGraphNode = Preconditions.checkNotNull(lockGraphNode);
747    }
748
749    ///// CycleDetectingLock methods. /////
750
751    @Override
752    public LockGraphNode getLockGraphNode() {
753      return lockGraphNode;
754    }
755
756    @Override
757    public boolean isAcquiredByCurrentThread() {
758      return isHeldByCurrentThread();
759    }
760
761    ///// Overridden ReentrantLock methods. /////
762
763    @Override
764    public void lock() {
765      aboutToAcquire(this);
766      try {
767        super.lock();
768      } finally {
769        lockStateChanged(this);
770      }
771    }
772
773    @Override
774    public void lockInterruptibly() throws InterruptedException {
775      aboutToAcquire(this);
776      try {
777        super.lockInterruptibly();
778      } finally {
779        lockStateChanged(this);
780      }
781    }
782
783    @Override
784    public boolean tryLock() {
785      aboutToAcquire(this);
786      try {
787        return super.tryLock();
788      } finally {
789        lockStateChanged(this);
790      }
791    }
792
793    @Override
794    public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
795      aboutToAcquire(this);
796      try {
797        return super.tryLock(timeout, unit);
798      } finally {
799        lockStateChanged(this);
800      }
801    }
802
803    @Override
804    public void unlock() {
805      try {
806        super.unlock();
807      } finally {
808        lockStateChanged(this);
809      }
810    }
811  }
812
813  final class CycleDetectingReentrantReadWriteLock extends ReentrantReadWriteLock
814      implements CycleDetectingLock {
815
816    // These ReadLock/WriteLock implementations shadow those in the
817    // ReentrantReadWriteLock superclass. They are simply wrappers around the
818    // internal Sync object, so this is safe since the shadowed locks are never
819    // exposed or used.
820    private final CycleDetectingReentrantReadLock readLock;
821    private final CycleDetectingReentrantWriteLock writeLock;
822
823    private final LockGraphNode lockGraphNode;
824
825    private CycleDetectingReentrantReadWriteLock(LockGraphNode lockGraphNode, boolean fair) {
826      super(fair);
827      this.readLock = new CycleDetectingReentrantReadLock(this);
828      this.writeLock = new CycleDetectingReentrantWriteLock(this);
829      this.lockGraphNode = Preconditions.checkNotNull(lockGraphNode);
830    }
831
832    ///// Overridden ReentrantReadWriteLock methods. /////
833
834    @Override
835    public ReadLock readLock() {
836      return readLock;
837    }
838
839    @Override
840    public WriteLock writeLock() {
841      return writeLock;
842    }
843
844    ///// CycleDetectingLock methods. /////
845
846    @Override
847    public LockGraphNode getLockGraphNode() {
848      return lockGraphNode;
849    }
850
851    @Override
852    public boolean isAcquiredByCurrentThread() {
853      return isWriteLockedByCurrentThread() || getReadHoldCount() > 0;
854    }
855  }
856
857  private class CycleDetectingReentrantReadLock extends ReentrantReadWriteLock.ReadLock {
858
859    @Weak final CycleDetectingReentrantReadWriteLock readWriteLock;
860
861    CycleDetectingReentrantReadLock(CycleDetectingReentrantReadWriteLock readWriteLock) {
862      super(readWriteLock);
863      this.readWriteLock = readWriteLock;
864    }
865
866    @Override
867    public void lock() {
868      aboutToAcquire(readWriteLock);
869      try {
870        super.lock();
871      } finally {
872        lockStateChanged(readWriteLock);
873      }
874    }
875
876    @Override
877    public void lockInterruptibly() throws InterruptedException {
878      aboutToAcquire(readWriteLock);
879      try {
880        super.lockInterruptibly();
881      } finally {
882        lockStateChanged(readWriteLock);
883      }
884    }
885
886    @Override
887    public boolean tryLock() {
888      aboutToAcquire(readWriteLock);
889      try {
890        return super.tryLock();
891      } finally {
892        lockStateChanged(readWriteLock);
893      }
894    }
895
896    @Override
897    public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
898      aboutToAcquire(readWriteLock);
899      try {
900        return super.tryLock(timeout, unit);
901      } finally {
902        lockStateChanged(readWriteLock);
903      }
904    }
905
906    @Override
907    public void unlock() {
908      try {
909        super.unlock();
910      } finally {
911        lockStateChanged(readWriteLock);
912      }
913    }
914  }
915
916  private class CycleDetectingReentrantWriteLock extends ReentrantReadWriteLock.WriteLock {
917
918    @Weak final CycleDetectingReentrantReadWriteLock readWriteLock;
919
920    CycleDetectingReentrantWriteLock(CycleDetectingReentrantReadWriteLock readWriteLock) {
921      super(readWriteLock);
922      this.readWriteLock = readWriteLock;
923    }
924
925    @Override
926    public void lock() {
927      aboutToAcquire(readWriteLock);
928      try {
929        super.lock();
930      } finally {
931        lockStateChanged(readWriteLock);
932      }
933    }
934
935    @Override
936    public void lockInterruptibly() throws InterruptedException {
937      aboutToAcquire(readWriteLock);
938      try {
939        super.lockInterruptibly();
940      } finally {
941        lockStateChanged(readWriteLock);
942      }
943    }
944
945    @Override
946    public boolean tryLock() {
947      aboutToAcquire(readWriteLock);
948      try {
949        return super.tryLock();
950      } finally {
951        lockStateChanged(readWriteLock);
952      }
953    }
954
955    @Override
956    public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
957      aboutToAcquire(readWriteLock);
958      try {
959        return super.tryLock(timeout, unit);
960      } finally {
961        lockStateChanged(readWriteLock);
962      }
963    }
964
965    @Override
966    public void unlock() {
967      try {
968        super.unlock();
969      } finally {
970        lockStateChanged(readWriteLock);
971      }
972    }
973  }
974}