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