001/*
002 * Copyright (C) 2007 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 com.google.common.util.concurrent.NullnessCasts.uncheckedNull;
019import static java.lang.Integer.toHexString;
020import static java.lang.System.identityHashCode;
021import static java.util.Objects.requireNonNull;
022import static java.util.concurrent.TimeUnit.MILLISECONDS;
023import static java.util.concurrent.TimeUnit.NANOSECONDS;
024import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater;
025
026import com.google.common.annotations.GwtCompatible;
027import com.google.common.base.Strings;
028import com.google.common.util.concurrent.internal.InternalFutureFailureAccess;
029import com.google.common.util.concurrent.internal.InternalFutures;
030import com.google.errorprone.annotations.CanIgnoreReturnValue;
031import com.google.errorprone.annotations.ForOverride;
032import com.google.j2objc.annotations.J2ObjCIncompatible;
033import com.google.j2objc.annotations.ReflectionSupport;
034import com.google.j2objc.annotations.RetainedLocalRef;
035import java.lang.invoke.MethodHandles;
036import java.lang.invoke.VarHandle;
037import java.lang.reflect.Field;
038import java.security.AccessController;
039import java.security.PrivilegedActionException;
040import java.security.PrivilegedExceptionAction;
041import java.util.Locale;
042import java.util.concurrent.CancellationException;
043import java.util.concurrent.ExecutionException;
044import java.util.concurrent.Executor;
045import java.util.concurrent.Future;
046import java.util.concurrent.ScheduledFuture;
047import java.util.concurrent.TimeUnit;
048import java.util.concurrent.TimeoutException;
049import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
050import java.util.concurrent.locks.LockSupport;
051import java.util.logging.Level;
052import org.jspecify.annotations.Nullable;
053import sun.misc.Unsafe;
054
055/**
056 * An abstract implementation of {@link ListenableFuture}, intended for advanced users only. More
057 * common ways to create a {@code ListenableFuture} include instantiating a {@link SettableFuture},
058 * submitting a task to a {@link ListeningExecutorService}, and deriving a {@code Future} from an
059 * existing one, typically using methods like {@link Futures#transform(ListenableFuture,
060 * com.google.common.base.Function, java.util.concurrent.Executor) Futures.transform} and {@link
061 * Futures#catching(ListenableFuture, Class, com.google.common.base.Function,
062 * java.util.concurrent.Executor) Futures.catching}.
063 *
064 * <p>This class implements all methods in {@code ListenableFuture}. Subclasses should provide a way
065 * to set the result of the computation through the protected methods {@link #set(Object)}, {@link
066 * #setFuture(ListenableFuture)} and {@link #setException(Throwable)}. Subclasses may also override
067 * {@link #afterDone()}, which will be invoked automatically when the future completes. Subclasses
068 * should rarely override other methods.
069 *
070 * @author Sven Mawson
071 * @author Luke Sandberg
072 * @since 1.0
073 */
074@SuppressWarnings({
075  // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
076  "ShortCircuitBoolean",
077  "nullness", // TODO(b/147136275): Remove once our checker understands & and |.
078})
079@GwtCompatible(emulated = true)
080@ReflectionSupport(value = ReflectionSupport.Level.FULL)
081public abstract class AbstractFuture<V extends @Nullable Object> extends InternalFutureFailureAccess
082    implements ListenableFuture<V> {
083  static final boolean GENERATE_CANCELLATION_CAUSES;
084
085  static {
086    // System.getProperty may throw if the security policy does not permit access.
087    boolean generateCancellationCauses;
088    try {
089      generateCancellationCauses =
090          Boolean.parseBoolean(
091              System.getProperty("guava.concurrent.generate_cancellation_cause", "false"));
092    } catch (SecurityException e) {
093      generateCancellationCauses = false;
094    }
095    GENERATE_CANCELLATION_CAUSES = generateCancellationCauses;
096  }
097
098  /**
099   * Tag interface marking trusted subclasses. This enables some optimizations. The implementation
100   * of this interface must also be an AbstractFuture and must not override or expose for overriding
101   * any of the public methods of ListenableFuture.
102   */
103  interface Trusted<V extends @Nullable Object> extends ListenableFuture<V> {}
104
105  /**
106   * A less abstract subclass of AbstractFuture. This can be used to optimize setFuture by ensuring
107   * that {@link #get} calls exactly the implementation of {@link AbstractFuture#get}.
108   */
109  abstract static class TrustedFuture<V extends @Nullable Object> extends AbstractFuture<V>
110      implements Trusted<V> {
111    @CanIgnoreReturnValue
112    @Override
113    @ParametricNullness
114    public final V get() throws InterruptedException, ExecutionException {
115      return super.get();
116    }
117
118    @CanIgnoreReturnValue
119    @Override
120    @ParametricNullness
121    public final V get(long timeout, TimeUnit unit)
122        throws InterruptedException, ExecutionException, TimeoutException {
123      return super.get(timeout, unit);
124    }
125
126    @Override
127    public final boolean isDone() {
128      return super.isDone();
129    }
130
131    @Override
132    public final boolean isCancelled() {
133      return super.isCancelled();
134    }
135
136    @Override
137    public final void addListener(Runnable listener, Executor executor) {
138      super.addListener(listener, executor);
139    }
140
141    @CanIgnoreReturnValue
142    @Override
143    public final boolean cancel(boolean mayInterruptIfRunning) {
144      return super.cancel(mayInterruptIfRunning);
145    }
146  }
147
148  static final LazyLogger log = new LazyLogger(AbstractFuture.class);
149
150  // A heuristic for timed gets. If the remaining timeout is less than this, spin instead of
151  // blocking. This value is what AbstractQueuedSynchronizer uses.
152  private static final long SPIN_THRESHOLD_NANOS = 1000L;
153
154  private static final AtomicHelper ATOMIC_HELPER;
155
156  /**
157   * Returns the result of calling {@link MethodHandles#lookup} from inside {@link AbstractFuture}.
158   * By virtue of being created there, it has access to the private fields of {@link
159   * AbstractFuture}, so that access is available to anyone who calls this method—specifically, to
160   * {@link VarHandleAtomicHelper}.
161   *
162   * <p>This "shouldn't" be necessary: {@link VarHandleAtomicHelper} and {@link AbstractFuture}
163   * "should" be nestmates, so a call to {@link MethodHandles#lookup} inside {@link
164   * VarHandleAtomicHelper} "should" have access to each other's private fields. However, our
165   * open-source build uses {@code -source 8 -target 8}, so the class files from that build can't
166   * express nestmates. Thus, when those class files are used from Java 9 or higher (i.e., high
167   * enough to trigger the {@link VarHandle} code path), such a lookup would fail with an {@link
168   * IllegalAccessException}.
169   *
170   * <p>Note that we do not have a similar problem with the fields in {@link Waiter} because those
171   * fields are not private. (We could solve the problem with {@link AbstractFuture} fields in the
172   * same way if we wanted.)
173   */
174  private static MethodHandles.Lookup methodHandlesLookupFromWithinAbstractFuture() {
175    return MethodHandles.lookup();
176  }
177
178  static {
179    AtomicHelper helper;
180    Throwable thrownUnsafeFailure = null;
181    Throwable thrownAtomicReferenceFieldUpdaterFailure = null;
182
183    helper = VarHandleAtomicHelperMaker.INSTANCE.tryMakeVarHandleAtomicHelper();
184    if (helper == null) {
185      try {
186        helper = new UnsafeAtomicHelper();
187      } catch (Exception | Error unsafeFailure) { // sneaky checked exception
188        thrownUnsafeFailure = unsafeFailure;
189        // Catch absolutely everything and fall through to AtomicReferenceFieldUpdaterAtomicHelper.
190        try {
191          helper = new AtomicReferenceFieldUpdaterAtomicHelper();
192        } catch (Exception // sneaky checked exception
193            | Error atomicReferenceFieldUpdaterFailure) {
194          // Some Android 5.0.x Samsung devices have bugs in JDK reflection APIs that cause
195          // getDeclaredField to throw a NoSuchFieldException when the field is definitely there.
196          // For these users fallback to a suboptimal implementation, based on synchronized. This
197          // will be a definite performance hit to those users.
198          thrownAtomicReferenceFieldUpdaterFailure = atomicReferenceFieldUpdaterFailure;
199          helper = new SynchronizedHelper();
200        }
201      }
202    }
203    ATOMIC_HELPER = helper;
204
205    // Prevent rare disastrous classloading in first call to LockSupport.park.
206    // See: https://bugs.openjdk.java.net/browse/JDK-8074773
207    @SuppressWarnings("unused")
208    Class<?> ensureLoaded = LockSupport.class;
209
210    // Log after all static init is finished; if an installed logger uses any Futures methods, it
211    // shouldn't break in cases where reflection is missing/broken.
212    if (thrownAtomicReferenceFieldUpdaterFailure != null) {
213      log.get().log(Level.SEVERE, "UnsafeAtomicHelper is broken!", thrownUnsafeFailure);
214      log.get()
215          .log(
216              Level.SEVERE,
217              "AtomicReferenceFieldUpdaterAtomicHelper is broken!",
218              thrownAtomicReferenceFieldUpdaterFailure);
219    }
220  }
221
222  private enum VarHandleAtomicHelperMaker {
223    INSTANCE {
224      /**
225       * Implementation used by non-J2ObjC environments (aside, of course, from those that have
226       * supersource for the entirety of {@link AbstractFuture}).
227       */
228      @Override
229      @J2ObjCIncompatible
230      @Nullable AtomicHelper tryMakeVarHandleAtomicHelper() {
231        try {
232          /*
233           * We first use reflection to check whether VarHandle exists. If we instead just tried to
234           * load our class directly (which would trigger non-reflective loading of VarHandle) from
235           * within a `try` block, then an error might be thrown even before we enter the `try`
236           * block: https://github.com/google/truth/issues/333#issuecomment-765652454
237           *
238           * Also, it's nice that this approach should let us catch *only* ClassNotFoundException
239           * instead of having to catch more broadly (potentially even including, say, a
240           * StackOverflowError).
241           */
242          Class.forName("java.lang.invoke.VarHandle");
243        } catch (ClassNotFoundException beforeJava9) {
244          return null;
245        }
246        return new VarHandleAtomicHelper();
247      }
248    };
249
250    /** Implementation used by J2ObjC environments, overridden for other environments. */
251    @Nullable AtomicHelper tryMakeVarHandleAtomicHelper() {
252      return null;
253    }
254  }
255
256  /** Waiter links form a Treiber stack, in the {@link #waiters} field. */
257  private static final class Waiter {
258    static final Waiter TOMBSTONE = new Waiter(false /* ignored param */);
259
260    volatile @Nullable Thread thread;
261    volatile @Nullable Waiter next;
262
263    /**
264     * Constructor for the TOMBSTONE, avoids use of ATOMIC_HELPER in case this class is loaded
265     * before the ATOMIC_HELPER. Apparently this is possible on some android platforms.
266     */
267    Waiter(boolean unused) {}
268
269    Waiter() {
270      // avoid volatile write, write is made visible by subsequent CAS on waiters field
271      ATOMIC_HELPER.putThread(this, Thread.currentThread());
272    }
273
274    // non-volatile write to the next field. Should be made visible by subsequent CAS on waiters
275    // field.
276    void setNext(@Nullable Waiter next) {
277      ATOMIC_HELPER.putNext(this, next);
278    }
279
280    void unpark() {
281      // This is racy with removeWaiter. The consequence of the race is that we may spuriously call
282      // unpark even though the thread has already removed itself from the list. But even if we did
283      // use a CAS, that race would still exist (it would just be ever so slightly smaller).
284      Thread w = thread;
285      if (w != null) {
286        thread = null;
287        LockSupport.unpark(w);
288      }
289    }
290  }
291
292  /**
293   * Marks the given node as 'deleted' (null waiter) and then scans the list to unlink all deleted
294   * nodes. This is an O(n) operation in the common case (and O(n^2) in the worst), but we are saved
295   * by two things.
296   *
297   * <ul>
298   *   <li>This is only called when a waiting thread times out or is interrupted. Both of which
299   *       should be rare.
300   *   <li>The waiters list should be very short.
301   * </ul>
302   */
303  private void removeWaiter(Waiter node) {
304    node.thread = null; // mark as 'deleted'
305    restart:
306    while (true) {
307      Waiter pred = null;
308      Waiter curr = waiters;
309      if (curr == Waiter.TOMBSTONE) {
310        return; // give up if someone is calling complete
311      }
312      Waiter succ;
313      while (curr != null) {
314        succ = curr.next;
315        if (curr.thread != null) { // we aren't unlinking this node, update pred.
316          pred = curr;
317        } else if (pred != null) { // We are unlinking this node and it has a predecessor.
318          pred.next = succ;
319          if (pred.thread == null) { // We raced with another node that unlinked pred. Restart.
320            continue restart;
321          }
322        } else if (!ATOMIC_HELPER.casWaiters(this, curr, succ)) { // We are unlinking head
323          continue restart; // We raced with an add or complete
324        }
325        curr = succ;
326      }
327      break;
328    }
329  }
330
331  /** Listeners also form a stack through the {@link #listeners} field. */
332  private static final class Listener {
333    static final Listener TOMBSTONE = new Listener();
334    // null only for TOMBSTONE
335    final @Nullable Runnable task;
336    // null only for TOMBSTONE
337    final @Nullable Executor executor;
338
339    // writes to next are made visible by subsequent CAS's on the listeners field
340    @Nullable Listener next;
341
342    Listener(Runnable task, Executor executor) {
343      this.task = task;
344      this.executor = executor;
345    }
346
347    Listener() {
348      this.task = null;
349      this.executor = null;
350    }
351  }
352
353  /** A special value to represent {@code null}. */
354  private static final Object NULL = new Object();
355
356  /** A special value to represent failure, when {@link #setException} is called successfully. */
357  private static final class Failure {
358    static final Failure FALLBACK_INSTANCE =
359        new Failure(
360            new Throwable("Failure occurred while trying to finish a future.") {
361              @Override
362              public synchronized Throwable fillInStackTrace() {
363                return this; // no stack trace
364              }
365            });
366    final Throwable exception;
367
368    Failure(Throwable exception) {
369      this.exception = checkNotNull(exception);
370    }
371  }
372
373  /** A special value to represent cancellation and the 'wasInterrupted' bit. */
374  private static final class Cancellation {
375    // constants to use when GENERATE_CANCELLATION_CAUSES = false
376    static final @Nullable Cancellation CAUSELESS_INTERRUPTED;
377    static final @Nullable Cancellation CAUSELESS_CANCELLED;
378
379    static {
380      if (GENERATE_CANCELLATION_CAUSES) {
381        CAUSELESS_CANCELLED = null;
382        CAUSELESS_INTERRUPTED = null;
383      } else {
384        CAUSELESS_CANCELLED = new Cancellation(false, null);
385        CAUSELESS_INTERRUPTED = new Cancellation(true, null);
386      }
387    }
388
389    final boolean wasInterrupted;
390    final @Nullable Throwable cause;
391
392    Cancellation(boolean wasInterrupted, @Nullable Throwable cause) {
393      this.wasInterrupted = wasInterrupted;
394      this.cause = cause;
395    }
396  }
397
398  /** A special value that encodes the 'setFuture' state. */
399  private static final class SetFuture<V extends @Nullable Object> implements Runnable {
400    final AbstractFuture<V> owner;
401    final ListenableFuture<? extends V> future;
402
403    SetFuture(AbstractFuture<V> owner, ListenableFuture<? extends V> future) {
404      this.owner = owner;
405      this.future = future;
406    }
407
408    @Override
409    public void run() {
410      if (owner.value != this) {
411        // nothing to do, we must have been cancelled, don't bother inspecting the future.
412        return;
413      }
414      Object valueToSet = getFutureValue(future);
415      if (ATOMIC_HELPER.casValue(owner, this, valueToSet)) {
416        complete(
417            owner,
418            /*
419             * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so
420             * don't invoke interruptTask.
421             */
422            false);
423      }
424    }
425  }
426
427  // TODO(lukes): investigate using the @Contended annotation on these fields when jdk8 is
428  // available.
429  /**
430   * This field encodes the current state of the future.
431   *
432   * <p>The valid values are:
433   *
434   * <ul>
435   *   <li>{@code null} initial state, nothing has happened.
436   *   <li>{@link Cancellation} terminal state, {@code cancel} was called.
437   *   <li>{@link Failure} terminal state, {@code setException} was called.
438   *   <li>{@link SetFuture} intermediate state, {@code setFuture} was called.
439   *   <li>{@link #NULL} terminal state, {@code set(null)} was called.
440   *   <li>Any other non-null value, terminal state, {@code set} was called with a non-null
441   *       argument.
442   * </ul>
443   */
444  private volatile @Nullable Object value;
445
446  /** All listeners. */
447  private volatile @Nullable Listener listeners;
448
449  /** All waiting threads. */
450  private volatile @Nullable Waiter waiters;
451
452  /** Constructor for use by subclasses. */
453  protected AbstractFuture() {}
454
455  // Gets and Timed Gets
456  //
457  // * Be responsive to interruption
458  // * Don't create Waiter nodes if you aren't going to park, this helps reduce contention on the
459  //   waiters field.
460  // * Future completion is defined by when #value becomes non-null/non SetFuture
461  // * Future completion can be observed if the waiters field contains a TOMBSTONE
462
463  // Timed Get
464  // There are a few design constraints to consider
465  // * We want to be responsive to small timeouts, unpark() has non trivial latency overheads (I
466  //   have observed 12 micros on 64-bit linux systems to wake up a parked thread). So if the
467  //   timeout is small we shouldn't park(). This needs to be traded off with the cpu overhead of
468  //   spinning, so we use SPIN_THRESHOLD_NANOS which is what AbstractQueuedSynchronizer uses for
469  //   similar purposes.
470  // * We want to behave reasonably for timeouts of 0
471  // * We are more responsive to completion than timeouts. This is because parkNanos depends on
472  //   system scheduling and as such we could either miss our deadline, or unpark() could be delayed
473  //   so that it looks like we timed out even though we didn't. For comparison FutureTask respects
474  //   completion preferably and AQS is non-deterministic (depends on where in the queue the waiter
475  //   is). If we wanted to be strict about it, we could store the unpark() time in the Waiter node
476  //   and we could use that to make a decision about whether or not we timed out prior to being
477  //   unparked.
478
479  /**
480   * {@inheritDoc}
481   *
482   * <p>The default {@link AbstractFuture} implementation throws {@code InterruptedException} if the
483   * current thread is interrupted during the call, even if the value is already available.
484   *
485   * @throws CancellationException {@inheritDoc}
486   */
487  @SuppressWarnings("LabelledBreakTarget") // TODO(b/345814817): Maybe fix?
488  @CanIgnoreReturnValue
489  @Override
490  @ParametricNullness
491  public V get(long timeout, TimeUnit unit)
492      throws InterruptedException, TimeoutException, ExecutionException {
493    // NOTE: if timeout < 0, remainingNanos will be < 0 and we will fall into the while(true) loop
494    // at the bottom and throw a timeoutexception.
495    final long timeoutNanos = unit.toNanos(timeout); // we rely on the implicit null check on unit.
496    long remainingNanos = timeoutNanos;
497    if (Thread.interrupted()) {
498      throw new InterruptedException();
499    }
500    @RetainedLocalRef Object localValue = value;
501    if (localValue != null & !(localValue instanceof SetFuture)) {
502      return getDoneValue(localValue);
503    }
504    // we delay calling nanoTime until we know we will need to either park or spin
505    final long endNanos = remainingNanos > 0 ? System.nanoTime() + remainingNanos : 0;
506    long_wait_loop:
507    if (remainingNanos >= SPIN_THRESHOLD_NANOS) {
508      Waiter oldHead = waiters;
509      if (oldHead != Waiter.TOMBSTONE) {
510        Waiter node = new Waiter();
511        do {
512          node.setNext(oldHead);
513          if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) {
514            while (true) {
515              OverflowAvoidingLockSupport.parkNanos(this, remainingNanos);
516              // Check interruption first, if we woke up due to interruption we need to honor that.
517              if (Thread.interrupted()) {
518                removeWaiter(node);
519                throw new InterruptedException();
520              }
521
522              // Otherwise re-read and check doneness. If we loop then it must have been a spurious
523              // wakeup
524              localValue = value;
525              if (localValue != null & !(localValue instanceof SetFuture)) {
526                return getDoneValue(localValue);
527              }
528
529              // timed out?
530              remainingNanos = endNanos - System.nanoTime();
531              if (remainingNanos < SPIN_THRESHOLD_NANOS) {
532                // Remove the waiter, one way or another we are done parking this thread.
533                removeWaiter(node);
534                break long_wait_loop; // jump down to the busy wait loop
535              }
536            }
537          }
538          oldHead = waiters; // re-read and loop.
539        } while (oldHead != Waiter.TOMBSTONE);
540      }
541      // re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a
542      // waiter.
543      // requireNonNull is safe because value is always set before TOMBSTONE.
544      return getDoneValue(requireNonNull(value));
545    }
546    // If we get here then we have remainingNanos < SPIN_THRESHOLD_NANOS and there is no node on the
547    // waiters list
548    while (remainingNanos > 0) {
549      localValue = value;
550      if (localValue != null & !(localValue instanceof SetFuture)) {
551        return getDoneValue(localValue);
552      }
553      if (Thread.interrupted()) {
554        throw new InterruptedException();
555      }
556      remainingNanos = endNanos - System.nanoTime();
557    }
558
559    String futureToString = toString();
560    final String unitString = unit.toString().toLowerCase(Locale.ROOT);
561    String message = "Waited " + timeout + " " + unit.toString().toLowerCase(Locale.ROOT);
562    // Only report scheduling delay if larger than our spin threshold - otherwise it's just noise
563    if (remainingNanos + SPIN_THRESHOLD_NANOS < 0) {
564      // We over-waited for our timeout.
565      message += " (plus ";
566      long overWaitNanos = -remainingNanos;
567      long overWaitUnits = unit.convert(overWaitNanos, NANOSECONDS);
568      long overWaitLeftoverNanos = overWaitNanos - unit.toNanos(overWaitUnits);
569      boolean shouldShowExtraNanos =
570          overWaitUnits == 0 || overWaitLeftoverNanos > SPIN_THRESHOLD_NANOS;
571      if (overWaitUnits > 0) {
572        message += overWaitUnits + " " + unitString;
573        if (shouldShowExtraNanos) {
574          message += ",";
575        }
576        message += " ";
577      }
578      if (shouldShowExtraNanos) {
579        message += overWaitLeftoverNanos + " nanoseconds ";
580      }
581
582      message += "delay)";
583    }
584    // It's confusing to see a completed future in a timeout message; if isDone() returns false,
585    // then we know it must have given a pending toString value earlier. If not, then the future
586    // completed after the timeout expired, and the message might be success.
587    if (isDone()) {
588      throw new TimeoutException(message + " but future completed as timeout expired");
589    }
590    throw new TimeoutException(message + " for " + futureToString);
591  }
592
593  /**
594   * {@inheritDoc}
595   *
596   * <p>The default {@link AbstractFuture} implementation throws {@code InterruptedException} if the
597   * current thread is interrupted during the call, even if the value is already available.
598   *
599   * @throws CancellationException {@inheritDoc}
600   */
601  @CanIgnoreReturnValue
602  @Override
603  @ParametricNullness
604  public V get() throws InterruptedException, ExecutionException {
605    if (Thread.interrupted()) {
606      throw new InterruptedException();
607    }
608    @RetainedLocalRef Object localValue = value;
609    if (localValue != null & !(localValue instanceof SetFuture)) {
610      return getDoneValue(localValue);
611    }
612    Waiter oldHead = waiters;
613    if (oldHead != Waiter.TOMBSTONE) {
614      Waiter node = new Waiter();
615      do {
616        node.setNext(oldHead);
617        if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) {
618          // we are on the stack, now wait for completion.
619          while (true) {
620            LockSupport.park(this);
621            // Check interruption first, if we woke up due to interruption we need to honor that.
622            if (Thread.interrupted()) {
623              removeWaiter(node);
624              throw new InterruptedException();
625            }
626            // Otherwise re-read and check doneness. If we loop then it must have been a spurious
627            // wakeup
628            localValue = value;
629            if (localValue != null & !(localValue instanceof SetFuture)) {
630              return getDoneValue(localValue);
631            }
632          }
633        }
634        oldHead = waiters; // re-read and loop.
635      } while (oldHead != Waiter.TOMBSTONE);
636    }
637    // re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a
638    // waiter.
639    // requireNonNull is safe because value is always set before TOMBSTONE.
640    return getDoneValue(requireNonNull(value));
641  }
642
643  /** Unboxes {@code obj}. Assumes that obj is not {@code null} or a {@link SetFuture}. */
644  @ParametricNullness
645  private V getDoneValue(Object obj) throws ExecutionException {
646    // While this seems like it might be too branch-y, simple benchmarking proves it to be
647    // unmeasurable (comparing done AbstractFutures with immediateFuture)
648    if (obj instanceof Cancellation) {
649      Cancellation cancellation = (Cancellation) obj;
650      Throwable cause = cancellation.cause;
651      throw cancellationExceptionWithCause("Task was cancelled.", cause);
652    } else if (obj instanceof Failure) {
653      Failure failure = (Failure) obj;
654      Throwable exception = failure.exception;
655      throw new ExecutionException(exception);
656    } else if (obj == NULL) {
657      /*
658       * It's safe to return null because we would only have stored it in the first place if it were
659       * a valid value for V.
660       */
661      return uncheckedNull();
662    } else {
663      @SuppressWarnings("unchecked") // this is the only other option
664      V asV = (V) obj;
665      return asV;
666    }
667  }
668
669  @Override
670  public boolean isDone() {
671    @RetainedLocalRef Object localValue = value;
672    return localValue != null & !(localValue instanceof SetFuture);
673  }
674
675  @Override
676  public boolean isCancelled() {
677    @RetainedLocalRef Object localValue = value;
678    return localValue instanceof Cancellation;
679  }
680
681  /**
682   * {@inheritDoc}
683   *
684   * <p>If a cancellation attempt succeeds on a {@code Future} that had previously been {@linkplain
685   * #setFuture set asynchronously}, then the cancellation will also be propagated to the delegate
686   * {@code Future} that was supplied in the {@code setFuture} call.
687   *
688   * <p>Rather than override this method to perform additional cancellation work or cleanup,
689   * subclasses should override {@link #afterDone}, consulting {@link #isCancelled} and {@link
690   * #wasInterrupted} as necessary. This ensures that the work is done even if the future is
691   * cancelled without a call to {@code cancel}, such as by calling {@code
692   * setFuture(cancelledFuture)}.
693   *
694   * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or
695   * acquire other locks, risking deadlocks.
696   */
697  @CanIgnoreReturnValue
698  @Override
699  public boolean cancel(boolean mayInterruptIfRunning) {
700    @RetainedLocalRef Object localValue = value;
701    boolean rValue = false;
702    if (localValue == null | localValue instanceof SetFuture) {
703      // Try to delay allocating the exception. At this point we may still lose the CAS, but it is
704      // certainly less likely.
705      Object valueToSet =
706          GENERATE_CANCELLATION_CAUSES
707              ? new Cancellation(
708                  mayInterruptIfRunning, new CancellationException("Future.cancel() was called."))
709              /*
710               * requireNonNull is safe because we've initialized these if
711               * !GENERATE_CANCELLATION_CAUSES.
712               *
713               * TODO(cpovirk): Maybe it would be cleaner to define a CancellationSupplier interface
714               * with two implementations, one that contains causeless Cancellation instances and
715               * the other of which creates new Cancellation instances each time it's called? Yet
716               * another alternative is to fill in a non-null value for each of the fields no matter
717               * what and to just not use it if !GENERATE_CANCELLATION_CAUSES.
718               */
719              : requireNonNull(
720                  mayInterruptIfRunning
721                      ? Cancellation.CAUSELESS_INTERRUPTED
722                      : Cancellation.CAUSELESS_CANCELLED);
723      AbstractFuture<?> abstractFuture = this;
724      while (true) {
725        if (ATOMIC_HELPER.casValue(abstractFuture, localValue, valueToSet)) {
726          rValue = true;
727          complete(abstractFuture, mayInterruptIfRunning);
728          if (localValue instanceof SetFuture) {
729            // propagate cancellation to the future set in setfuture, this is racy, and we don't
730            // care if we are successful or not.
731            ListenableFuture<?> futureToPropagateTo = ((SetFuture) localValue).future;
732            if (futureToPropagateTo instanceof Trusted) {
733              // If the future is a TrustedFuture then we specifically avoid calling cancel()
734              // this has 2 benefits
735              // 1. for long chains of futures strung together with setFuture we consume less stack
736              // 2. we avoid allocating Cancellation objects at every level of the cancellation
737              //    chain
738              // We can only do this for TrustedFuture, because TrustedFuture.cancel is final and
739              // does nothing but delegate to this method.
740              AbstractFuture<?> trusted = (AbstractFuture<?>) futureToPropagateTo;
741              localValue = trusted.value;
742              if (localValue == null | localValue instanceof SetFuture) {
743                abstractFuture = trusted;
744                continue; // loop back up and try to complete the new future
745              }
746            } else {
747              // not a TrustedFuture, call cancel directly.
748              futureToPropagateTo.cancel(mayInterruptIfRunning);
749            }
750          }
751          break;
752        }
753        // obj changed, reread
754        localValue = abstractFuture.value;
755        if (!(localValue instanceof SetFuture)) {
756          // obj cannot be null at this point, because value can only change from null to non-null.
757          // So if value changed (and it did since we lost the CAS), then it cannot be null and
758          // since it isn't a SetFuture, then the future must be done and we should exit the loop
759          break;
760        }
761      }
762    }
763    return rValue;
764  }
765
766  /**
767   * Subclasses can override this method to implement interruption of the future's computation. The
768   * method is invoked automatically by a successful call to {@link #cancel(boolean) cancel(true)}.
769   *
770   * <p>The default implementation does nothing.
771   *
772   * <p>This method is likely to be deprecated. Prefer to override {@link #afterDone}, checking
773   * {@link #wasInterrupted} to decide whether to interrupt your task.
774   *
775   * @since 10.0
776   */
777  protected void interruptTask() {}
778
779  /**
780   * Returns true if this future was cancelled with {@code mayInterruptIfRunning} set to {@code
781   * true}.
782   *
783   * @since 14.0
784   */
785  protected final boolean wasInterrupted() {
786    @RetainedLocalRef Object localValue = value;
787    return (localValue instanceof Cancellation) && ((Cancellation) localValue).wasInterrupted;
788  }
789
790  /**
791   * {@inheritDoc}
792   *
793   * @since 10.0
794   */
795  @Override
796  public void addListener(Runnable listener, Executor executor) {
797    checkNotNull(listener, "Runnable was null.");
798    checkNotNull(executor, "Executor was null.");
799    // Checking isDone and listeners != TOMBSTONE may seem redundant, but our contract for
800    // addListener says that listeners execute 'immediate' if the future isDone(). However, our
801    // protocol for completing a future is to assign the value field (which sets isDone to true) and
802    // then to release waiters, followed by executing afterDone(), followed by releasing listeners.
803    // That means that it is possible to observe that the future isDone and that your listeners
804    // don't execute 'immediately'.  By checking isDone here we avoid that.
805    // A corollary to all that is that we don't need to check isDone inside the loop because if we
806    // get into the loop we know that we weren't done when we entered and therefore we aren't under
807    // an obligation to execute 'immediately'.
808    if (!isDone()) {
809      Listener oldHead = listeners;
810      if (oldHead != Listener.TOMBSTONE) {
811        Listener newNode = new Listener(listener, executor);
812        do {
813          newNode.next = oldHead;
814          if (ATOMIC_HELPER.casListeners(this, oldHead, newNode)) {
815            return;
816          }
817          oldHead = listeners; // re-read
818        } while (oldHead != Listener.TOMBSTONE);
819      }
820    }
821    // If we get here then the Listener TOMBSTONE was set, which means the future is done, call
822    // the listener.
823    executeListener(listener, executor);
824  }
825
826  /**
827   * Sets the result of this {@code Future} unless this {@code Future} has already been cancelled or
828   * set (including {@linkplain #setFuture set asynchronously}). When a call to this method returns,
829   * the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b> the call was
830   * accepted (in which case it returns {@code true}). If it returns {@code false}, the {@code
831   * Future} may have previously been set asynchronously, in which case its result may not be known
832   * yet. That result, though not yet known, cannot be overridden by a call to a {@code set*}
833   * method, only by a call to {@link #cancel}.
834   *
835   * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or
836   * acquire other locks, risking deadlocks.
837   *
838   * @param value the value to be used as the result
839   * @return true if the attempt was accepted, completing the {@code Future}
840   */
841  @CanIgnoreReturnValue
842  protected boolean set(@ParametricNullness V value) {
843    Object valueToSet = value == null ? NULL : value;
844    if (ATOMIC_HELPER.casValue(this, null, valueToSet)) {
845      complete(this, /* callInterruptTask= */ false);
846      return true;
847    }
848    return false;
849  }
850
851  /**
852   * Sets the failed result of this {@code Future} unless this {@code Future} has already been
853   * cancelled or set (including {@linkplain #setFuture set asynchronously}). When a call to this
854   * method returns, the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b>
855   * the call was accepted (in which case it returns {@code true}). If it returns {@code false}, the
856   * {@code Future} may have previously been set asynchronously, in which case its result may not be
857   * known yet. That result, though not yet known, cannot be overridden by a call to a {@code set*}
858   * method, only by a call to {@link #cancel}.
859   *
860   * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or
861   * acquire other locks, risking deadlocks.
862   *
863   * @param throwable the exception to be used as the failed result
864   * @return true if the attempt was accepted, completing the {@code Future}
865   */
866  @CanIgnoreReturnValue
867  protected boolean setException(Throwable throwable) {
868    Object valueToSet = new Failure(checkNotNull(throwable));
869    if (ATOMIC_HELPER.casValue(this, null, valueToSet)) {
870      complete(this, /* callInterruptTask= */ false);
871      return true;
872    }
873    return false;
874  }
875
876  /**
877   * Sets the result of this {@code Future} to match the supplied input {@code Future} once the
878   * supplied {@code Future} is done, unless this {@code Future} has already been cancelled or set
879   * (including "set asynchronously," defined below).
880   *
881   * <p>If the supplied future is {@linkplain #isDone done} when this method is called and the call
882   * is accepted, then this future is guaranteed to have been completed with the supplied future by
883   * the time this method returns. If the supplied future is not done and the call is accepted, then
884   * the future will be <i>set asynchronously</i>. Note that such a result, though not yet known,
885   * cannot be overridden by a call to a {@code set*} method, only by a call to {@link #cancel}.
886   *
887   * <p>If the call {@code setFuture(delegate)} is accepted and this {@code Future} is later
888   * cancelled, cancellation will be propagated to {@code delegate}. Additionally, any call to
889   * {@code setFuture} after any cancellation will propagate cancellation to the supplied {@code
890   * Future}.
891   *
892   * <p>Note that, even if the supplied future is cancelled and it causes this future to complete,
893   * it will never trigger interruption behavior. In particular, it will not cause this future to
894   * invoke the {@link #interruptTask} method, and the {@link #wasInterrupted} method will not
895   * return {@code true}.
896   *
897   * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or
898   * acquire other locks, risking deadlocks.
899   *
900   * @param future the future to delegate to
901   * @return true if the attempt was accepted, indicating that the {@code Future} was not previously
902   *     cancelled or set.
903   * @since 19.0
904   */
905  @CanIgnoreReturnValue
906  @SuppressWarnings("Interruption") // We are propagating an interrupt from a caller.
907  protected boolean setFuture(ListenableFuture<? extends V> future) {
908    checkNotNull(future);
909    @RetainedLocalRef Object localValue = value;
910    if (localValue == null) {
911      if (future.isDone()) {
912        Object value = getFutureValue(future);
913        if (ATOMIC_HELPER.casValue(this, null, value)) {
914          complete(
915              this,
916              /*
917               * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so
918               * don't invoke interruptTask.
919               */
920              false);
921          return true;
922        }
923        return false;
924      }
925      SetFuture<V> valueToSet = new SetFuture<>(this, future);
926      if (ATOMIC_HELPER.casValue(this, null, valueToSet)) {
927        // the listener is responsible for calling completeWithFuture, directExecutor is appropriate
928        // since all we are doing is unpacking a completed future which should be fast.
929        try {
930          future.addListener(valueToSet, DirectExecutor.INSTANCE);
931        } catch (Throwable t) {
932          // Any Exception is either a RuntimeException or sneaky checked exception.
933          //
934          // addListener has thrown an exception! SetFuture.run can't throw any exceptions so this
935          // must have been caused by addListener itself. The most likely explanation is a
936          // misconfigured mock. Try to switch to Failure.
937          Failure failure;
938          try {
939            failure = new Failure(t);
940          } catch (Exception | Error oomMostLikely) { // sneaky checked exception
941            failure = Failure.FALLBACK_INSTANCE;
942          }
943          // Note: The only way this CAS could fail is if cancel() has raced with us. That is ok.
944          boolean unused = ATOMIC_HELPER.casValue(this, valueToSet, failure);
945        }
946        return true;
947      }
948      localValue = value; // we lost the cas, fall through and maybe cancel
949    }
950    // The future has already been set to something. If it is cancellation we should cancel the
951    // incoming future.
952    if (localValue instanceof Cancellation) {
953      // we don't care if it fails, this is best-effort.
954      future.cancel(((Cancellation) localValue).wasInterrupted);
955    }
956    return false;
957  }
958
959  /**
960   * Returns a value that satisfies the contract of the {@link #value} field based on the state of
961   * given future.
962   *
963   * <p>This is approximately the inverse of {@link #getDoneValue(Object)}
964   */
965  private static Object getFutureValue(ListenableFuture<?> future) {
966    if (future instanceof Trusted) {
967      // Break encapsulation for TrustedFuture instances since we know that subclasses cannot
968      // override .get() (since it is final) and therefore this is equivalent to calling .get()
969      // and unpacking the exceptions like we do below (just much faster because it is a single
970      // field read instead of a read, several branches and possibly creating exceptions).
971      Object v = ((AbstractFuture<?>) future).value;
972      if (v instanceof Cancellation) {
973        // If the other future was interrupted, clear the interrupted bit while preserving the cause
974        // this will make it consistent with how non-trustedfutures work which cannot propagate the
975        // wasInterrupted bit
976        Cancellation c = (Cancellation) v;
977        if (c.wasInterrupted) {
978          v =
979              c.cause != null
980                  ? new Cancellation(/* wasInterrupted= */ false, c.cause)
981                  : Cancellation.CAUSELESS_CANCELLED;
982        }
983      }
984      // requireNonNull is safe as long as we call this method only on completed futures.
985      return requireNonNull(v);
986    }
987    if (future instanceof InternalFutureFailureAccess) {
988      Throwable throwable =
989          InternalFutures.tryInternalFastPathGetFailure((InternalFutureFailureAccess) future);
990      if (throwable != null) {
991        return new Failure(throwable);
992      }
993    }
994    boolean wasCancelled = future.isCancelled();
995    // Don't allocate a CancellationException if it's not necessary
996    if (!GENERATE_CANCELLATION_CAUSES & wasCancelled) {
997      /*
998       * requireNonNull is safe because we've initialized CAUSELESS_CANCELLED if
999       * !GENERATE_CANCELLATION_CAUSES.
1000       */
1001      return requireNonNull(Cancellation.CAUSELESS_CANCELLED);
1002    }
1003    // Otherwise calculate the value by calling .get()
1004    try {
1005      Object v = getUninterruptibly(future);
1006      if (wasCancelled) {
1007        return new Cancellation(
1008            false,
1009            new IllegalArgumentException(
1010                "get() did not throw CancellationException, despite reporting "
1011                    + "isCancelled() == true: "
1012                    + future));
1013      }
1014      return v == null ? NULL : v;
1015    } catch (ExecutionException exception) {
1016      if (wasCancelled) {
1017        return new Cancellation(
1018            false,
1019            new IllegalArgumentException(
1020                "get() did not throw CancellationException, despite reporting "
1021                    + "isCancelled() == true: "
1022                    + future,
1023                exception));
1024      }
1025      return new Failure(exception.getCause());
1026    } catch (CancellationException cancellation) {
1027      if (!wasCancelled) {
1028        return new Failure(
1029            new IllegalArgumentException(
1030                "get() threw CancellationException, despite reporting isCancelled() == false: "
1031                    + future,
1032                cancellation));
1033      }
1034      return new Cancellation(false, cancellation);
1035    } catch (Exception | Error t) { // sneaky checked exception
1036      return new Failure(t);
1037    }
1038  }
1039
1040  /**
1041   * An inlined private copy of {@link Uninterruptibles#getUninterruptibly} used to break an
1042   * internal dependency on other /util/concurrent classes.
1043   */
1044  @ParametricNullness
1045  private static <V extends @Nullable Object> V getUninterruptibly(Future<V> future)
1046      throws ExecutionException {
1047    boolean interrupted = false;
1048    try {
1049      while (true) {
1050        try {
1051          return future.get();
1052        } catch (InterruptedException e) {
1053          interrupted = true;
1054        }
1055      }
1056    } finally {
1057      if (interrupted) {
1058        Thread.currentThread().interrupt();
1059      }
1060    }
1061  }
1062
1063  /** Unblocks all threads and runs all listeners. */
1064  private static void complete(AbstractFuture<?> param, boolean callInterruptTask) {
1065    // Declare a "true" local variable so that the Checker Framework will infer nullness.
1066    AbstractFuture<?> future = param;
1067
1068    Listener next = null;
1069    outer:
1070    while (true) {
1071      future.releaseWaiters();
1072      /*
1073       * We call interruptTask() immediately before afterDone() so that migrating between the two
1074       * can be a no-op.
1075       */
1076      if (callInterruptTask) {
1077        future.interruptTask();
1078        /*
1079         * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so don't
1080         * invoke interruptTask on any subsequent futures.
1081         */
1082        callInterruptTask = false;
1083      }
1084      // We call this before the listeners in order to avoid needing to manage a separate stack data
1085      // structure for them.  Also, some implementations rely on this running prior to listeners
1086      // so that the cleanup work is visible to listeners.
1087      // afterDone() should be generally fast and only used for cleanup work... but in theory can
1088      // also be recursive and create StackOverflowErrors
1089      future.afterDone();
1090      // push the current set of listeners onto next
1091      next = future.clearListeners(next);
1092      future = null;
1093      while (next != null) {
1094        Listener curr = next;
1095        next = next.next;
1096        /*
1097         * requireNonNull is safe because the listener stack never contains TOMBSTONE until after
1098         * clearListeners.
1099         */
1100        Runnable task = requireNonNull(curr.task);
1101        if (task instanceof SetFuture) {
1102          SetFuture<?> setFuture = (SetFuture<?>) task;
1103          // We unwind setFuture specifically to avoid StackOverflowErrors in the case of long
1104          // chains of SetFutures
1105          // Handling this special case is important because there is no way to pass an executor to
1106          // setFuture, so a user couldn't break the chain by doing this themselves.  It is also
1107          // potentially common if someone writes a recursive Futures.transformAsync transformer.
1108          future = setFuture.owner;
1109          if (future.value == setFuture) {
1110            Object valueToSet = getFutureValue(setFuture.future);
1111            if (ATOMIC_HELPER.casValue(future, setFuture, valueToSet)) {
1112              continue outer;
1113            }
1114          }
1115          // otherwise the future we were trying to set is already done.
1116        } else {
1117          /*
1118           * requireNonNull is safe because the listener stack never contains TOMBSTONE until after
1119           * clearListeners.
1120           */
1121          executeListener(task, requireNonNull(curr.executor));
1122        }
1123      }
1124      break;
1125    }
1126  }
1127
1128  /**
1129   * Callback method that is called exactly once after the future is completed.
1130   *
1131   * <p>If {@link #interruptTask} is also run during completion, {@link #afterDone} runs after it.
1132   *
1133   * <p>The default implementation of this method in {@code AbstractFuture} does nothing. This is
1134   * intended for very lightweight cleanup work, for example, timing statistics or clearing fields.
1135   * If your task does anything heavier consider, just using a listener with an executor.
1136   *
1137   * @since 20.0
1138   */
1139  @ForOverride
1140  protected void afterDone() {}
1141
1142  // TODO(b/114236866): Inherit doc from InternalFutureFailureAccess. Also, -link to its URL.
1143  /**
1144   * Usually returns {@code null} but, if this {@code Future} has failed, may <i>optionally</i>
1145   * return the cause of the failure. "Failure" means specifically "completed with an exception"; it
1146   * does not include "was cancelled." To be explicit: If this method returns a non-null value,
1147   * then:
1148   *
1149   * <ul>
1150   *   <li>{@code isDone()} must return {@code true}
1151   *   <li>{@code isCancelled()} must return {@code false}
1152   *   <li>{@code get()} must not block, and it must throw an {@code ExecutionException} with the
1153   *       return value of this method as its cause
1154   * </ul>
1155   *
1156   * <p>This method is {@code protected} so that classes like {@code
1157   * com.google.common.util.concurrent.SettableFuture} do not expose it to their users as an
1158   * instance method. In the unlikely event that you need to call this method, call {@link
1159   * InternalFutures#tryInternalFastPathGetFailure(InternalFutureFailureAccess)}.
1160   *
1161   * @since 27.0
1162   */
1163  @Override
1164  /*
1165   * We should annotate the superclass, InternalFutureFailureAccess, to say that its copy of this
1166   * method returns @Nullable, too. However, we're not sure if we want to make any changes to that
1167   * class, since it's in a separate artifact that we planned to release only a single version of.
1168   */
1169  protected final @Nullable Throwable tryInternalFastPathGetFailure() {
1170    if (this instanceof Trusted) {
1171      @RetainedLocalRef Object localValue = value;
1172      if (localValue instanceof Failure) {
1173        return ((Failure) localValue).exception;
1174      }
1175    }
1176    return null;
1177  }
1178
1179  /**
1180   * If this future has been cancelled (and possibly interrupted), cancels (and possibly interrupts)
1181   * the given future (if available).
1182   */
1183  final void maybePropagateCancellationTo(@Nullable Future<?> related) {
1184    if (related != null & isCancelled()) {
1185      related.cancel(wasInterrupted());
1186    }
1187  }
1188
1189  /** Releases all threads in the {@link #waiters} list, and clears the list. */
1190  private void releaseWaiters() {
1191    Waiter head = ATOMIC_HELPER.gasWaiters(this, Waiter.TOMBSTONE);
1192    for (Waiter currentWaiter = head; currentWaiter != null; currentWaiter = currentWaiter.next) {
1193      currentWaiter.unpark();
1194    }
1195  }
1196
1197  /**
1198   * Clears the {@link #listeners} list and prepends its contents to {@code onto}, least recently
1199   * added first.
1200   */
1201  private @Nullable Listener clearListeners(@Nullable Listener onto) {
1202    // We need to
1203    // 1. atomically swap the listeners with TOMBSTONE, this is because addListener uses that
1204    //    to synchronize with us
1205    // 2. reverse the linked list, because despite our rather clear contract, people depend on us
1206    //    executing listeners in the order they were added
1207    // 3. push all the items onto 'onto' and return the new head of the stack
1208    Listener head = ATOMIC_HELPER.gasListeners(this, Listener.TOMBSTONE);
1209    Listener reversedList = onto;
1210    while (head != null) {
1211      Listener tmp = head;
1212      head = head.next;
1213      tmp.next = reversedList;
1214      reversedList = tmp;
1215    }
1216    return reversedList;
1217  }
1218
1219  // TODO(user): move parts into a default method on ListenableFuture?
1220  @Override
1221  public String toString() {
1222    // TODO(cpovirk): Presize to something plausible?
1223    StringBuilder builder = new StringBuilder();
1224    if (getClass().getName().startsWith("com.google.common.util.concurrent.")) {
1225      builder.append(getClass().getSimpleName());
1226    } else {
1227      builder.append(getClass().getName());
1228    }
1229    builder.append('@').append(toHexString(identityHashCode(this))).append("[status=");
1230    if (isCancelled()) {
1231      builder.append("CANCELLED");
1232    } else if (isDone()) {
1233      addDoneString(builder);
1234    } else {
1235      addPendingString(builder); // delegates to addDoneString if future completes midway
1236    }
1237    return builder.append("]").toString();
1238  }
1239
1240  /**
1241   * Provide a human-readable explanation of why this future has not yet completed.
1242   *
1243   * @return null if an explanation cannot be provided (e.g. because the future is done).
1244   * @since 23.0
1245   */
1246  protected @Nullable String pendingToString() {
1247    // TODO(diamondm) consider moving this into addPendingString so it's always in the output
1248    if (this instanceof ScheduledFuture) {
1249      return "remaining delay=[" + ((ScheduledFuture) this).getDelay(MILLISECONDS) + " ms]";
1250    }
1251    return null;
1252  }
1253
1254  @SuppressWarnings("CatchingUnchecked") // sneaky checked exception
1255  private void addPendingString(StringBuilder builder) {
1256    // Capture current builder length so it can be truncated if this future ends up completing while
1257    // the toString is being calculated
1258    int truncateLength = builder.length();
1259
1260    builder.append("PENDING");
1261
1262    @RetainedLocalRef Object localValue = value;
1263    if (localValue instanceof SetFuture) {
1264      builder.append(", setFuture=[");
1265      appendUserObject(builder, ((SetFuture) localValue).future);
1266      builder.append("]");
1267    } else {
1268      String pendingDescription;
1269      try {
1270        pendingDescription = Strings.emptyToNull(pendingToString());
1271      } catch (Exception | StackOverflowError e) {
1272        // Any Exception is either a RuntimeException or sneaky checked exception.
1273        //
1274        // Don't call getMessage or toString() on the exception, in case the exception thrown by the
1275        // subclass is implemented with bugs similar to the subclass.
1276        pendingDescription = "Exception thrown from implementation: " + e.getClass();
1277      }
1278      if (pendingDescription != null) {
1279        builder.append(", info=[").append(pendingDescription).append("]");
1280      }
1281    }
1282
1283    // The future may complete while calculating the toString, so we check once more to see if the
1284    // future is done
1285    if (isDone()) {
1286      // Truncate anything that was appended before realizing this future is done
1287      builder.delete(truncateLength, builder.length());
1288      addDoneString(builder);
1289    }
1290  }
1291
1292  @SuppressWarnings("CatchingUnchecked") // sneaky checked exception
1293  private void addDoneString(StringBuilder builder) {
1294    try {
1295      V value = getUninterruptibly(this);
1296      builder.append("SUCCESS, result=[");
1297      appendResultObject(builder, value);
1298      builder.append("]");
1299    } catch (ExecutionException e) {
1300      builder.append("FAILURE, cause=[").append(e.getCause()).append("]");
1301    } catch (CancellationException e) {
1302      builder.append("CANCELLED"); // shouldn't be reachable
1303    } catch (Exception e) { // sneaky checked exception
1304      builder.append("UNKNOWN, cause=[").append(e.getClass()).append(" thrown from get()]");
1305    }
1306  }
1307
1308  /**
1309   * Any object can be the result of a Future, and not every object has a reasonable toString()
1310   * implementation. Using a reconstruction of the default Object.toString() prevents OOMs and stack
1311   * overflows, and helps avoid sensitive data inadvertently ending up in exception messages.
1312   */
1313  private void appendResultObject(StringBuilder builder, @Nullable Object o) {
1314    if (o == null) {
1315      builder.append("null");
1316    } else if (o == this) {
1317      builder.append("this future");
1318    } else {
1319      builder
1320          .append(o.getClass().getName())
1321          .append("@")
1322          .append(Integer.toHexString(System.identityHashCode(o)));
1323    }
1324  }
1325
1326  /** Helper for printing user supplied objects into our toString method. */
1327  @SuppressWarnings("CatchingUnchecked") // sneaky checked exception
1328  private void appendUserObject(StringBuilder builder, @Nullable Object o) {
1329    // This is some basic recursion detection for when people create cycles via set/setFuture or
1330    // when deep chains of futures exist resulting in a StackOverflowException. We could detect
1331    // arbitrary cycles using a thread local but this should be a good enough solution (it is also
1332    // what jdk collections do in these cases)
1333    try {
1334      if (o == this) {
1335        builder.append("this future");
1336      } else {
1337        builder.append(o);
1338      }
1339    } catch (Exception | StackOverflowError e) {
1340      // Any Exception is either a RuntimeException or sneaky checked exception.
1341      //
1342      // Don't call getMessage or toString() on the exception, in case the exception thrown by the
1343      // user object is implemented with bugs similar to the user object.
1344      builder.append("Exception thrown from implementation: ").append(e.getClass());
1345    }
1346  }
1347
1348  /**
1349   * Submits the given runnable to the given {@link Executor} catching and logging all {@linkplain
1350   * RuntimeException runtime exceptions} thrown by the executor.
1351   */
1352  @SuppressWarnings("CatchingUnchecked") // sneaky checked exception
1353  private static void executeListener(Runnable runnable, Executor executor) {
1354    try {
1355      executor.execute(runnable);
1356    } catch (Exception e) { // sneaky checked exception
1357      // Log it and keep going -- bad runnable and/or executor. Don't punish the other runnables if
1358      // we're given a bad one. We only catch Exception because we want Errors to propagate up.
1359      log.get()
1360          .log(
1361              Level.SEVERE,
1362              "RuntimeException while executing runnable "
1363                  + runnable
1364                  + " with executor "
1365                  + executor,
1366              e);
1367    }
1368  }
1369
1370  private abstract static class AtomicHelper {
1371    /** Non-volatile write of the thread to the {@link Waiter#thread} field. */
1372    abstract void putThread(Waiter waiter, Thread newValue);
1373
1374    /** Non-volatile write of the waiter to the {@link Waiter#next} field. */
1375    abstract void putNext(Waiter waiter, @Nullable Waiter newValue);
1376
1377    /** Performs a CAS operation on the {@link AbstractFuture#waiters} field. */
1378    abstract boolean casWaiters(
1379        AbstractFuture<?> future, @Nullable Waiter expect, @Nullable Waiter update);
1380
1381    /** Performs a CAS operation on the {@link AbstractFuture#listeners} field. */
1382    abstract boolean casListeners(
1383        AbstractFuture<?> future, @Nullable Listener expect, Listener update);
1384
1385    /** Performs a GAS operation on the {@link AbstractFuture#waiters} field. */
1386    abstract Waiter gasWaiters(AbstractFuture<?> future, Waiter update);
1387
1388    /** Performs a GAS operation on the {@link AbstractFuture#listeners} field. */
1389    abstract Listener gasListeners(AbstractFuture<?> future, Listener update);
1390
1391    /** Performs a CAS operation on the {@link AbstractFuture#value} field. */
1392    abstract boolean casValue(AbstractFuture<?> future, @Nullable Object expect, Object update);
1393  }
1394
1395  /** {@link AtomicHelper} based on {@link VarHandle}. */
1396  @J2ObjCIncompatible
1397  // We use this class only after confirming that VarHandle is available at runtime.
1398  @SuppressWarnings("Java8ApiChecker")
1399  @IgnoreJRERequirement
1400  private static final class VarHandleAtomicHelper extends AtomicHelper {
1401    static final VarHandle waiterThreadUpdater;
1402    static final VarHandle waiterNextUpdater;
1403    static final VarHandle waitersUpdater;
1404    static final VarHandle listenersUpdater;
1405    static final VarHandle valueUpdater;
1406
1407    static {
1408      MethodHandles.Lookup lookup = methodHandlesLookupFromWithinAbstractFuture();
1409      try {
1410        waiterThreadUpdater = lookup.findVarHandle(Waiter.class, "thread", Thread.class);
1411        waiterNextUpdater = lookup.findVarHandle(Waiter.class, "next", Waiter.class);
1412        waitersUpdater = lookup.findVarHandle(AbstractFuture.class, "waiters", Waiter.class);
1413        listenersUpdater = lookup.findVarHandle(AbstractFuture.class, "listeners", Listener.class);
1414        valueUpdater = lookup.findVarHandle(AbstractFuture.class, "value", Object.class);
1415      } catch (ReflectiveOperationException e) {
1416        // Those fields exist.
1417        throw newLinkageError(e);
1418      }
1419    }
1420
1421    @Override
1422    void putThread(Waiter waiter, Thread newValue) {
1423      waiterThreadUpdater.setRelease(waiter, newValue);
1424    }
1425
1426    @Override
1427    void putNext(Waiter waiter, @Nullable Waiter newValue) {
1428      waiterNextUpdater.setRelease(waiter, newValue);
1429    }
1430
1431    @Override
1432    boolean casWaiters(AbstractFuture<?> future, @Nullable Waiter expect, @Nullable Waiter update) {
1433      return waitersUpdater.compareAndSet(future, expect, update);
1434    }
1435
1436    @Override
1437    boolean casListeners(AbstractFuture<?> future, @Nullable Listener expect, Listener update) {
1438      return listenersUpdater.compareAndSet(future, expect, update);
1439    }
1440
1441    @Override
1442    Listener gasListeners(AbstractFuture<?> future, Listener update) {
1443      return (Listener) listenersUpdater.getAndSet(future, update);
1444    }
1445
1446    @Override
1447    Waiter gasWaiters(AbstractFuture<?> future, Waiter update) {
1448      return (Waiter) waitersUpdater.getAndSet(future, update);
1449    }
1450
1451    @Override
1452    boolean casValue(AbstractFuture<?> future, @Nullable Object expect, Object update) {
1453      return valueUpdater.compareAndSet(future, expect, update);
1454    }
1455
1456    private static LinkageError newLinkageError(Throwable cause) {
1457      return new LinkageError(cause.toString(), cause);
1458    }
1459  }
1460
1461  /**
1462   * {@link AtomicHelper} based on {@link sun.misc.Unsafe}.
1463   *
1464   * <p>Static initialization of this class will fail if the {@link sun.misc.Unsafe} object cannot
1465   * be accessed.
1466   */
1467  @SuppressWarnings("SunApi") // b/345822163
1468  private static final class UnsafeAtomicHelper extends AtomicHelper {
1469    static final Unsafe UNSAFE;
1470    static final long LISTENERS_OFFSET;
1471    static final long WAITERS_OFFSET;
1472    static final long VALUE_OFFSET;
1473    static final long WAITER_THREAD_OFFSET;
1474    static final long WAITER_NEXT_OFFSET;
1475
1476    static {
1477      Unsafe unsafe = null;
1478      try {
1479        unsafe = Unsafe.getUnsafe();
1480      } catch (SecurityException tryReflectionInstead) {
1481        try {
1482          unsafe =
1483              AccessController.doPrivileged(
1484                  new PrivilegedExceptionAction<Unsafe>() {
1485                    @Override
1486                    public Unsafe run() throws Exception {
1487                      Class<Unsafe> k = Unsafe.class;
1488                      for (Field f : k.getDeclaredFields()) {
1489                        f.setAccessible(true);
1490                        Object x = f.get(null);
1491                        if (k.isInstance(x)) {
1492                          return k.cast(x);
1493                        }
1494                      }
1495                      throw new NoSuchFieldError("the Unsafe");
1496                    }
1497                  });
1498        } catch (PrivilegedActionException e) {
1499          throw new RuntimeException("Could not initialize intrinsics", e.getCause());
1500        }
1501      }
1502      try {
1503        Class<?> abstractFuture = AbstractFuture.class;
1504        WAITERS_OFFSET = unsafe.objectFieldOffset(abstractFuture.getDeclaredField("waiters"));
1505        LISTENERS_OFFSET = unsafe.objectFieldOffset(abstractFuture.getDeclaredField("listeners"));
1506        VALUE_OFFSET = unsafe.objectFieldOffset(abstractFuture.getDeclaredField("value"));
1507        WAITER_THREAD_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("thread"));
1508        WAITER_NEXT_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("next"));
1509        UNSAFE = unsafe;
1510      } catch (NoSuchFieldException e) {
1511        throw new RuntimeException(e);
1512      }
1513    }
1514
1515    @Override
1516    void putThread(Waiter waiter, Thread newValue) {
1517      UNSAFE.putObject(waiter, WAITER_THREAD_OFFSET, newValue);
1518    }
1519
1520    @Override
1521    void putNext(Waiter waiter, @Nullable Waiter newValue) {
1522      UNSAFE.putObject(waiter, WAITER_NEXT_OFFSET, newValue);
1523    }
1524
1525    @Override
1526    boolean casWaiters(AbstractFuture<?> future, @Nullable Waiter expect, @Nullable Waiter update) {
1527      return UNSAFE.compareAndSwapObject(future, WAITERS_OFFSET, expect, update);
1528    }
1529
1530    @Override
1531    boolean casListeners(AbstractFuture<?> future, @Nullable Listener expect, Listener update) {
1532      return UNSAFE.compareAndSwapObject(future, LISTENERS_OFFSET, expect, update);
1533    }
1534
1535    @Override
1536    Listener gasListeners(AbstractFuture<?> future, Listener update) {
1537      return (Listener) UNSAFE.getAndSetObject(future, LISTENERS_OFFSET, update);
1538    }
1539
1540    @Override
1541    Waiter gasWaiters(AbstractFuture<?> future, Waiter update) {
1542      return (Waiter) UNSAFE.getAndSetObject(future, WAITERS_OFFSET, update);
1543    }
1544
1545    @Override
1546    boolean casValue(AbstractFuture<?> future, @Nullable Object expect, Object update) {
1547      return UNSAFE.compareAndSwapObject(future, VALUE_OFFSET, expect, update);
1548    }
1549  }
1550
1551  /** {@link AtomicHelper} based on {@link AtomicReferenceFieldUpdater}. */
1552  private static final class AtomicReferenceFieldUpdaterAtomicHelper extends AtomicHelper {
1553    private static final AtomicReferenceFieldUpdater<Waiter, Thread> waiterThreadUpdater =
1554        newUpdater(Waiter.class, Thread.class, "thread");
1555    private static final AtomicReferenceFieldUpdater<Waiter, Waiter> waiterNextUpdater =
1556        newUpdater(Waiter.class, Waiter.class, "next");
1557    private static final AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Waiter>
1558        waitersUpdater = waitersUpdaterFromWithinAbstractFuture();
1559    private static final AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Listener>
1560        listenersUpdater = listenersUpdaterFromWithinAbstractFuture();
1561    private static final AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Object>
1562        valueUpdater = valueUpdaterFromWithinAbstractFuture();
1563
1564    @Override
1565    void putThread(Waiter waiter, Thread newValue) {
1566      waiterThreadUpdater.lazySet(waiter, newValue);
1567    }
1568
1569    @Override
1570    void putNext(Waiter waiter, @Nullable Waiter newValue) {
1571      waiterNextUpdater.lazySet(waiter, newValue);
1572    }
1573
1574    @Override
1575    boolean casWaiters(AbstractFuture<?> future, @Nullable Waiter expect, @Nullable Waiter update) {
1576      return waitersUpdater.compareAndSet(future, expect, update);
1577    }
1578
1579    @Override
1580    boolean casListeners(AbstractFuture<?> future, @Nullable Listener expect, Listener update) {
1581      return listenersUpdater.compareAndSet(future, expect, update);
1582    }
1583
1584    @Override
1585    Listener gasListeners(AbstractFuture<?> future, Listener update) {
1586      return listenersUpdater.getAndSet(future, update);
1587    }
1588
1589    @Override
1590    Waiter gasWaiters(AbstractFuture<?> future, Waiter update) {
1591      return waitersUpdater.getAndSet(future, update);
1592    }
1593
1594    @Override
1595    boolean casValue(AbstractFuture<?> future, @Nullable Object expect, Object update) {
1596      return valueUpdater.compareAndSet(future, expect, update);
1597    }
1598  }
1599
1600  /** Returns an {@link AtomicReferenceFieldUpdater} for {@link #waiters}. */
1601  private static AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Waiter>
1602      waitersUpdaterFromWithinAbstractFuture() {
1603    return newUpdater(AbstractFuture.class, Waiter.class, "waiters");
1604  }
1605
1606  /** Returns an {@link AtomicReferenceFieldUpdater} for {@link #listeners}. */
1607  private static AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Listener>
1608      listenersUpdaterFromWithinAbstractFuture() {
1609    return newUpdater(AbstractFuture.class, Listener.class, "listeners");
1610  }
1611
1612  /** Returns an {@link AtomicReferenceFieldUpdater} for {@link #value}. */
1613  private static AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Object>
1614      valueUpdaterFromWithinAbstractFuture() {
1615    return newUpdater(AbstractFuture.class, Object.class, "value");
1616  }
1617
1618  /**
1619   * {@link AtomicHelper} based on {@code synchronized} and volatile writes.
1620   *
1621   * <p>This is an implementation of last resort for when certain basic VM features are broken (like
1622   * AtomicReferenceFieldUpdater).
1623   */
1624  private static final class SynchronizedHelper extends AtomicHelper {
1625    @Override
1626    void putThread(Waiter waiter, Thread newValue) {
1627      waiter.thread = newValue;
1628    }
1629
1630    @Override
1631    void putNext(Waiter waiter, @Nullable Waiter newValue) {
1632      waiter.next = newValue;
1633    }
1634
1635    @Override
1636    boolean casWaiters(AbstractFuture<?> future, @Nullable Waiter expect, @Nullable Waiter update) {
1637      synchronized (future) {
1638        if (future.waiters == expect) {
1639          future.waiters = update;
1640          return true;
1641        }
1642        return false;
1643      }
1644    }
1645
1646    @Override
1647    boolean casListeners(AbstractFuture<?> future, @Nullable Listener expect, Listener update) {
1648      synchronized (future) {
1649        if (future.listeners == expect) {
1650          future.listeners = update;
1651          return true;
1652        }
1653        return false;
1654      }
1655    }
1656
1657    @Override
1658    Listener gasListeners(AbstractFuture<?> future, Listener update) {
1659      synchronized (future) {
1660        Listener old = future.listeners;
1661        if (old != update) {
1662          future.listeners = update;
1663        }
1664        return old;
1665      }
1666    }
1667
1668    @Override
1669    Waiter gasWaiters(AbstractFuture<?> future, Waiter update) {
1670      synchronized (future) {
1671        Waiter old = future.waiters;
1672        if (old != update) {
1673          future.waiters = update;
1674        }
1675        return old;
1676      }
1677    }
1678
1679    @Override
1680    boolean casValue(AbstractFuture<?> future, @Nullable Object expect, Object update) {
1681      synchronized (future) {
1682        if (future.value == expect) {
1683          future.value = update;
1684          return true;
1685        }
1686        return false;
1687      }
1688    }
1689  }
1690
1691  private static CancellationException cancellationExceptionWithCause(
1692      String message, @Nullable Throwable cause) {
1693    CancellationException exception = new CancellationException(message);
1694    exception.initCause(cause);
1695    return exception;
1696  }
1697}