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.base.Strings.emptyToNull;
019import static com.google.common.util.concurrent.NullnessCasts.uncheckedNull;
020import static com.google.common.util.concurrent.Platform.interruptCurrentThread;
021import static com.google.common.util.concurrent.Platform.rethrowIfErrorOtherThanStackOverflow;
022import static java.lang.Integer.toHexString;
023import static java.lang.System.identityHashCode;
024import static java.util.Objects.requireNonNull;
025import static java.util.concurrent.TimeUnit.MILLISECONDS;
026import static java.util.logging.Level.SEVERE;
027
028import com.google.common.annotations.GwtCompatible;
029import com.google.common.util.concurrent.internal.InternalFutureFailureAccess;
030import com.google.common.util.concurrent.internal.InternalFutures;
031import com.google.errorprone.annotations.CanIgnoreReturnValue;
032import com.google.errorprone.annotations.ForOverride;
033import com.google.j2objc.annotations.ReflectionSupport;
034import com.google.j2objc.annotations.RetainedLocalRef;
035import java.util.concurrent.CancellationException;
036import java.util.concurrent.ExecutionException;
037import java.util.concurrent.Executor;
038import java.util.concurrent.Future;
039import java.util.concurrent.ScheduledFuture;
040import java.util.concurrent.TimeUnit;
041import java.util.concurrent.TimeoutException;
042import org.jspecify.annotations.Nullable;
043
044/**
045 * An abstract implementation of {@link ListenableFuture}, intended for advanced users only. More
046 * common ways to create a {@code ListenableFuture} include instantiating a {@link SettableFuture},
047 * submitting a task to a {@link ListeningExecutorService}, and deriving a {@code Future} from an
048 * existing one, typically using methods like {@link Futures#transform(ListenableFuture,
049 * com.google.common.base.Function, java.util.concurrent.Executor) Futures.transform} and {@link
050 * Futures#catching(ListenableFuture, Class, com.google.common.base.Function,
051 * java.util.concurrent.Executor) Futures.catching}.
052 *
053 * <p>This class implements all methods in {@code ListenableFuture}. Subclasses should provide a way
054 * to set the result of the computation through the protected methods {@link #set(Object)}, {@link
055 * #setFuture(ListenableFuture)} and {@link #setException(Throwable)}. Subclasses may also override
056 * {@link #afterDone()}, which will be invoked automatically when the future completes. Subclasses
057 * should rarely override other methods.
058 *
059 * @author Sven Mawson
060 * @author Luke Sandberg
061 * @since 1.0
062 */
063// Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
064@SuppressWarnings("ShortCircuitBoolean")
065@GwtCompatible
066/*
067 * TODO(cpovirk): Do we still need @ReflectionSupport on *this* class now that the fields live in
068 * the superclass? Note that Listener (which we also reflect on) still lives here.
069 */
070@ReflectionSupport(value = ReflectionSupport.Level.FULL)
071public abstract class AbstractFuture<V extends @Nullable Object> extends AbstractFutureState<V> {
072  /*
073   * All static initialization should be performed in AbstractFutureState: AbstractFutureState's
074   * initialization may trigger logging, which may assume that AbstractFuture is initialized.
075   *
076   * TODO(cpovirk): Write a test that asserts that AbstractFuture has no clinit?
077   */
078
079  /**
080   * Tag interface marking trusted subclasses. This enables some optimizations. The implementation
081   * of this interface must also be an AbstractFuture and must not override or expose for overriding
082   * any of the public methods of ListenableFuture.
083   */
084  interface Trusted<V extends @Nullable Object> extends ListenableFuture<V> {}
085
086  /**
087   * A less abstract subclass of AbstractFuture. This can be used to optimize setFuture by ensuring
088   * that {@link #get} calls exactly the implementation of {@link AbstractFuture#get}.
089   */
090  abstract static class TrustedFuture<V extends @Nullable Object> extends AbstractFuture<V>
091      implements Trusted<V> {
092    @CanIgnoreReturnValue
093    @Override
094    @ParametricNullness
095    public final V get() throws InterruptedException, ExecutionException {
096      return super.get();
097    }
098
099    @CanIgnoreReturnValue
100    @Override
101    @ParametricNullness
102    public final V get(long timeout, TimeUnit unit)
103        throws InterruptedException, ExecutionException, TimeoutException {
104      return super.get(timeout, unit);
105    }
106
107    @Override
108    public final boolean isDone() {
109      return super.isDone();
110    }
111
112    @Override
113    public final boolean isCancelled() {
114      return super.isCancelled();
115    }
116
117    @Override
118    public final void addListener(Runnable listener, Executor executor) {
119      super.addListener(listener, executor);
120    }
121
122    @CanIgnoreReturnValue
123    @Override
124    public final boolean cancel(boolean mayInterruptIfRunning) {
125      return super.cancel(mayInterruptIfRunning);
126    }
127  }
128
129  /** Listeners form a Treiber stack through the {@link #listeners} field. */
130  static final class Listener {
131    static final Listener TOMBSTONE = new Listener();
132    // null only for TOMBSTONE
133    final @Nullable Runnable task;
134    // null only for TOMBSTONE
135    final @Nullable Executor executor;
136
137    // writes to next are made visible by subsequent CAS's on the listeners field
138    @Nullable Listener next;
139
140    Listener(Runnable task, Executor executor) {
141      this.task = task;
142      this.executor = executor;
143    }
144
145    Listener() {
146      this.task = null;
147      this.executor = null;
148    }
149  }
150
151  /** A special value to represent failure, when {@link #setException} is called successfully. */
152  private static final class Failure {
153    static final Failure FALLBACK_INSTANCE =
154        new Failure(
155            new Throwable("Failure occurred while trying to finish a future.") {
156              @Override
157              public Throwable fillInStackTrace() {
158                return this; // no stack trace
159              }
160            });
161    final Throwable exception;
162
163    Failure(Throwable exception) {
164      this.exception = checkNotNull(exception);
165    }
166
167    ExecutionException newExecutionException() {
168      return new ExecutionException(exception);
169    }
170  }
171
172  /** A special value to represent cancellation and the 'wasInterrupted' bit. */
173  private static final class Cancellation {
174    // constants to use when GENERATE_CANCELLATION_CAUSES = false
175    static final @Nullable Cancellation CAUSELESS_INTERRUPTED;
176    static final @Nullable Cancellation CAUSELESS_CANCELLED;
177
178    static {
179      if (GENERATE_CANCELLATION_CAUSES) {
180        CAUSELESS_CANCELLED = null;
181        CAUSELESS_INTERRUPTED = null;
182      } else {
183        CAUSELESS_CANCELLED = new Cancellation(false, null);
184        CAUSELESS_INTERRUPTED = new Cancellation(true, null);
185      }
186    }
187
188    final boolean wasInterrupted;
189    final @Nullable Throwable cause;
190
191    Cancellation(boolean wasInterrupted, @Nullable Throwable cause) {
192      this.wasInterrupted = wasInterrupted;
193      this.cause = cause;
194    }
195
196    CancellationException newCancellationException() {
197      CancellationException exception = new CancellationException("Task was cancelled.");
198      exception.initCause(cause);
199      return exception;
200    }
201  }
202
203  /** A special value that encodes the 'setFuture' state. */
204  private static final class DelegatingToFuture<V extends @Nullable Object> implements Runnable {
205    final AbstractFuture<V> owner;
206    final ListenableFuture<? extends V> future;
207
208    DelegatingToFuture(AbstractFuture<V> owner, ListenableFuture<? extends V> future) {
209      this.owner = owner;
210      this.future = future;
211    }
212
213    @Override
214    public void run() {
215      if (owner.value() != this) {
216        // nothing to do, we must have been cancelled, don't bother inspecting the future.
217        return;
218      }
219      Object valueToSet = getFutureValue(future);
220      if (casValue(owner, this, valueToSet)) {
221        complete(
222            owner,
223            /*
224             * Interruption doesn't propagate through a DelegatingToFuture chain (see
225             * getFutureValue), so don't invoke interruptTask.
226             */
227            false);
228      }
229    }
230  }
231
232  /** Constructor for use by subclasses. */
233  protected AbstractFuture() {}
234
235  /**
236   * {@inheritDoc}
237   *
238   * <p>The default {@link AbstractFuture} implementation throws {@code InterruptedException} if the
239   * current thread is interrupted during the call, even if the value is already available.
240   *
241   * @throws CancellationException if the computation was cancelled
242   */
243  @CanIgnoreReturnValue
244  @Override
245  @ParametricNullness
246  public V get(long timeout, TimeUnit unit)
247      throws InterruptedException, TimeoutException, ExecutionException {
248    return Platform.get(this, timeout, unit);
249  }
250
251  /**
252   * {@inheritDoc}
253   *
254   * <p>The default {@link AbstractFuture} implementation throws {@code InterruptedException} if the
255   * current thread is interrupted during the call, even if the value is already available.
256   *
257   * @throws CancellationException if the computation was cancelled
258   */
259  @CanIgnoreReturnValue
260  @Override
261  @ParametricNullness
262  public V get() throws InterruptedException, ExecutionException {
263    return Platform.get(this);
264  }
265
266  /**
267   * Returns the result of this future or throws in case of failure, just like {@link #get()} except
268   * that this method <i>also</i> throws if this future is not done.
269   *
270   * <p>This method computes its result based on the internal state of {@link AbstractFuture}, so it
271   * does not necessarily return the same result as {@link #get()} if {@link #get()} has been
272   * overridden. Thus, it should be called only on instances of {@link Trusted} or from within
273   * {@link #get()} itself.
274   */
275  @ParametricNullness
276  @SuppressWarnings("nullness") // TODO(b/147136275): Remove once our checker understands & and |.
277  /*
278   * TODO(b/112550045): Use this from Futures.getDone when applicable? Note the small difference in
279   * failure message between the two at present.
280   */
281  final V getFromAlreadyDoneTrustedFuture() throws ExecutionException {
282    @RetainedLocalRef Object localValue = value();
283    if (localValue == null | localValue instanceof DelegatingToFuture) {
284      throw new IllegalStateException("Cannot get() on a pending future.");
285    }
286    return getDoneValue(localValue);
287  }
288
289  /** Unboxes {@code obj}. Assumes that obj is not {@code null} or a {@link DelegatingToFuture}. */
290  @ParametricNullness
291  @SuppressWarnings("TypeParameterUnusedInFormals") // sorry not sorry
292  static <V extends @Nullable Object> V getDoneValue(Object obj) throws ExecutionException {
293    // While this seems like it might be too branch-y, simple benchmarking proves it to be
294    // unmeasurable (comparing done AbstractFutures with immediateFuture)
295    if (obj instanceof Cancellation) {
296      throw ((Cancellation) obj).newCancellationException();
297    } else if (obj instanceof Failure) {
298      throw ((Failure) obj).newExecutionException();
299    } else {
300      return getKnownSuccessfulDoneValue(obj);
301    }
302  }
303
304  /**
305   * Unboxes {@code obj}. Assumes that obj is not {@code null}, a {@link DelegatingToFuture}, a
306   * {@link Cancellation}, or a {@link Failure}.
307   */
308  @SuppressWarnings("TypeParameterUnusedInFormals") // sorry not sorry
309  private static <V extends @Nullable Object> V getKnownSuccessfulDoneValue(Object obj) {
310    if (obj == NULL) {
311      /*
312       * It's safe to return null because we would only have stored it in the first place if it were
313       * a valid value for V.
314       */
315      return uncheckedNull();
316    } else {
317      @SuppressWarnings("unchecked") // this is the only other option
318      V asV = (V) obj;
319      return asV;
320    }
321  }
322
323  /** Returns whether {@code obj} is <b>not</b> an instance of {@code DelegatingToFuture}. */
324  // This method lets us:
325  // - avoid exposing DelegatingToFuture to the whole package
326  // - avoid fighting with the relative operator precedence of `instanceof` and `!`
327  static boolean notInstanceOfDelegatingToFuture(@Nullable Object obj) {
328    return !(obj instanceof DelegatingToFuture);
329  }
330
331  @Override
332  public boolean isDone() {
333    @RetainedLocalRef Object localValue = value();
334    return localValue != null & notInstanceOfDelegatingToFuture(localValue);
335  }
336
337  @Override
338  public boolean isCancelled() {
339    @RetainedLocalRef Object localValue = value();
340    return localValue instanceof Cancellation;
341  }
342
343  /**
344   * {@inheritDoc}
345   *
346   * <p>If a cancellation attempt succeeds on a {@code Future} that had previously been {@linkplain
347   * #setFuture set asynchronously}, then the cancellation will also be propagated to the delegate
348   * {@code Future} that was supplied in the {@code setFuture} call.
349   *
350   * <p>Rather than override this method to perform additional cancellation work or cleanup,
351   * subclasses should override {@link #afterDone}, consulting {@link #isCancelled} and {@link
352   * #wasInterrupted} as necessary. This ensures that the work is done even if the future is
353   * cancelled without a call to {@code cancel}, such as by calling {@code
354   * setFuture(cancelledFuture)}.
355   *
356   * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or
357   * acquire other locks, risking deadlocks.
358   */
359  @CanIgnoreReturnValue
360  @Override
361  public boolean cancel(boolean mayInterruptIfRunning) {
362    @RetainedLocalRef Object localValue = value();
363    boolean rValue = false;
364    if (localValue == null | localValue instanceof DelegatingToFuture) {
365      // Try to delay allocating the exception. At this point we may still lose the CAS, but it is
366      // certainly less likely.
367      Object valueToSet =
368          GENERATE_CANCELLATION_CAUSES
369              ? new Cancellation(
370                  mayInterruptIfRunning, new CancellationException("Future.cancel() was called."))
371              /*
372               * requireNonNull is safe because we've initialized these if
373               * !GENERATE_CANCELLATION_CAUSES.
374               *
375               * TODO(cpovirk): Maybe it would be cleaner to define a CancellationSupplier interface
376               * with two implementations, one that contains causeless Cancellation instances and
377               * the other of which creates new Cancellation instances each time it's called? Yet
378               * another alternative is to fill in a non-null value for each of the fields no matter
379               * what and to just not use it if !GENERATE_CANCELLATION_CAUSES.
380               */
381              : requireNonNull(
382                  mayInterruptIfRunning
383                      ? Cancellation.CAUSELESS_INTERRUPTED
384                      : Cancellation.CAUSELESS_CANCELLED);
385      AbstractFuture<?> abstractFuture = this;
386      while (true) {
387        if (casValue(abstractFuture, localValue, valueToSet)) {
388          rValue = true;
389          complete(abstractFuture, mayInterruptIfRunning);
390          if (localValue instanceof DelegatingToFuture) {
391            // propagate cancellation to the future set in setfuture, this is racy, and we don't
392            // care if we are successful or not.
393            ListenableFuture<?> futureToPropagateTo = ((DelegatingToFuture<?>) localValue).future;
394            if (futureToPropagateTo instanceof Trusted) {
395              // If the future is a Trusted instance then we specifically avoid calling cancel()
396              // this has 2 benefits
397              // 1. for long chains of futures strung together with setFuture we consume less stack
398              // 2. we avoid allocating Cancellation objects at every level of the cancellation
399              //    chain
400              // We can only do this for Trusted, because Trusted implementations of cancel do
401              // nothing but delegate to this method and do not permit user overrides.
402              AbstractFuture<?> trusted = (AbstractFuture<?>) futureToPropagateTo;
403              localValue = trusted.value();
404              if (localValue == null | localValue instanceof DelegatingToFuture) {
405                abstractFuture = trusted;
406                continue; // loop back up and try to complete the new future
407              }
408            } else {
409              // not a Trusted instance, call cancel directly.
410              futureToPropagateTo.cancel(mayInterruptIfRunning);
411            }
412          }
413          break;
414        }
415        // obj changed, reread
416        localValue = abstractFuture.value();
417        if (notInstanceOfDelegatingToFuture(localValue)) {
418          // obj cannot be null at this point, because value can only change from null to non-null.
419          // So if value changed (and it did since we lost the CAS), then it cannot be null and
420          // since it isn't a DelegatingToFuture, then the future must be done and we should exit
421          // the loop
422          break;
423        }
424      }
425    }
426    return rValue;
427  }
428
429  /**
430   * Subclasses can override this method to implement interruption of the future's computation. The
431   * method is invoked automatically by a successful call to {@link #cancel(boolean) cancel(true)}.
432   *
433   * <p>The default implementation does nothing.
434   *
435   * <p>This method is likely to be deprecated. Prefer to override {@link #afterDone}, checking
436   * {@link #wasInterrupted} to decide whether to interrupt your task.
437   *
438   * @since 10.0
439   */
440  protected void interruptTask() {}
441
442  /**
443   * Returns true if this future was cancelled with {@code mayInterruptIfRunning} set to {@code
444   * true}.
445   *
446   * @since 14.0
447   */
448  protected final boolean wasInterrupted() {
449    @RetainedLocalRef Object localValue = value();
450    return (localValue instanceof Cancellation) && ((Cancellation) localValue).wasInterrupted;
451  }
452
453  final boolean wasInterruptedInternal() {
454    return wasInterrupted();
455  }
456
457  /**
458   * {@inheritDoc}
459   *
460   * @since 10.0
461   */
462  @Override
463  public void addListener(Runnable listener, Executor executor) {
464    checkNotNull(listener, "Runnable was null.");
465    checkNotNull(executor, "Executor was null.");
466    // Checking isDone and listeners != TOMBSTONE may seem redundant, but our contract for
467    // addListener says that listeners execute 'immediate' if the future isDone(). However, our
468    // protocol for completing a future is to assign the value field (which sets isDone to true) and
469    // then to release waiters, followed by executing afterDone(), followed by releasing listeners.
470    // That means that it is possible to observe that the future isDone and that your listeners
471    // don't execute 'immediately'.  By checking isDone here we avoid that.
472    // A corollary to all that is that we don't need to check isDone inside the loop because if we
473    // get into the loop we know that we weren't done when we entered and therefore we aren't under
474    // an obligation to execute 'immediately'.
475    if (!isDone()) {
476      Listener oldHead = listeners();
477      if (oldHead != Listener.TOMBSTONE) {
478        Listener newNode = new Listener(listener, executor);
479        do {
480          newNode.next = oldHead;
481          if (casListeners(oldHead, newNode)) {
482            return;
483          }
484          oldHead = listeners(); // re-read
485        } while (oldHead != Listener.TOMBSTONE);
486      }
487    }
488    // If we get here then the Listener TOMBSTONE was set, which means the future is done, call
489    // the listener.
490    executeListener(listener, executor);
491  }
492
493  /**
494   * Sets the result of this {@code Future} unless this {@code Future} has already been cancelled or
495   * set (including {@linkplain #setFuture set asynchronously}). When a call to this method returns,
496   * the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b> the call was
497   * accepted (in which case it returns {@code true}). If it returns {@code false}, the {@code
498   * Future} may have previously been set asynchronously, in which case its result may not be known
499   * yet. That result, though not yet known, cannot be overridden by a call to a {@code set*}
500   * method, only by a call to {@link #cancel}.
501   *
502   * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or
503   * acquire other locks, risking deadlocks.
504   *
505   * @param value the value to be used as the result
506   * @return true if the attempt was accepted, completing the {@code Future}
507   */
508  @CanIgnoreReturnValue
509  protected boolean set(@ParametricNullness V value) {
510    Object valueToSet = maskNull(value);
511    if (casValue(this, null, valueToSet)) {
512      complete(this, /* callInterruptTask= */ false);
513      return true;
514    }
515    return false;
516  }
517
518  @CanIgnoreReturnValue
519  final boolean setInternal(@ParametricNullness V value) {
520    return set(value);
521  }
522
523  /**
524   * Sets the failed result of this {@code Future} unless this {@code Future} has already been
525   * cancelled or set (including {@linkplain #setFuture set asynchronously}). When a call to this
526   * method returns, the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b>
527   * the call was accepted (in which case it returns {@code true}). If it returns {@code false}, the
528   * {@code Future} may have previously been set asynchronously, in which case its result may not be
529   * known yet. That result, though not yet known, cannot be overridden by a call to a {@code set*}
530   * method, only by a call to {@link #cancel}.
531   *
532   * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or
533   * acquire other locks, risking deadlocks.
534   *
535   * @param throwable the exception to be used as the failed result
536   * @return true if the attempt was accepted, completing the {@code Future}
537   */
538  @CanIgnoreReturnValue
539  protected boolean setException(Throwable throwable) {
540    Object valueToSet = new Failure(throwable);
541    if (casValue(this, null, valueToSet)) {
542      complete(this, /* callInterruptTask= */ false);
543      return true;
544    }
545    return false;
546  }
547
548  @CanIgnoreReturnValue
549  final boolean setExceptionInternal(Throwable throwable) {
550    return setException(throwable);
551  }
552
553  /**
554   * Sets the result of this {@code Future} to match the supplied input {@code Future} once the
555   * supplied {@code Future} is done, unless this {@code Future} has already been cancelled or set
556   * (including "set asynchronously," defined below).
557   *
558   * <p>If the supplied future is {@linkplain #isDone done} when this method is called and the call
559   * is accepted, then this future is guaranteed to have been completed with the supplied future by
560   * the time this method returns. If the supplied future is not done and the call is accepted, then
561   * the future will be <i>set asynchronously</i>. Note that such a result, though not yet known,
562   * cannot be overridden by a call to a {@code set*} method, only by a call to {@link #cancel}.
563   *
564   * <p>If the call {@code setFuture(delegate)} is accepted and this {@code Future} is later
565   * cancelled, cancellation will be propagated to {@code delegate}. Additionally, any call to
566   * {@code setFuture} after any cancellation will propagate cancellation to the supplied {@code
567   * Future}.
568   *
569   * <p>Note that, even if the supplied future is cancelled and it causes this future to complete,
570   * it will never trigger interruption behavior. In particular, it will not cause this future to
571   * invoke the {@link #interruptTask} method, and the {@link #wasInterrupted} method will not
572   * return {@code true}.
573   *
574   * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or
575   * acquire other locks, risking deadlocks.
576   *
577   * @param future the future to delegate to
578   * @return true if the attempt was accepted, indicating that the {@code Future} was not previously
579   *     cancelled or set.
580   * @since 19.0
581   */
582  @CanIgnoreReturnValue
583  @SuppressWarnings("Interruption") // We are propagating an interrupt from a caller.
584  protected boolean setFuture(ListenableFuture<? extends V> future) {
585    checkNotNull(future);
586    @RetainedLocalRef Object localValue = value();
587    if (localValue == null) {
588      if (future.isDone()) {
589        Object value = getFutureValue(future);
590        if (casValue(this, null, value)) {
591          complete(
592              this,
593              /*
594               * Interruption doesn't propagate through a DelegatingToFuture chain (see
595               * getFutureValue), so don't invoke interruptTask.
596               */
597              false);
598          return true;
599        }
600        return false;
601      }
602      DelegatingToFuture<V> valueToSet = new DelegatingToFuture<>(this, future);
603      if (casValue(this, null, valueToSet)) {
604        // the listener is responsible for calling completeWithFuture, directExecutor is appropriate
605        // since all we are doing is unpacking a completed future which should be fast.
606        try {
607          future.addListener(valueToSet, DirectExecutor.INSTANCE);
608        } catch (Throwable t) {
609          // Any Exception is either a RuntimeException or sneaky checked exception.
610          //
611          // addListener has thrown an exception! DelegatingToFuture.run can't throw any exceptions
612          // so this must have been caused by addListener itself. The most likely explanation is a
613          // misconfigured mock. Try to switch to Failure.
614          Failure failure;
615          try {
616            failure = new Failure(t);
617          } catch (Exception | Error oomMostLikely) { // sneaky checked exception
618            failure = Failure.FALLBACK_INSTANCE;
619          }
620          // Note: The only way this CAS could fail is if cancel() has raced with us. That is ok.
621          boolean unused = casValue(this, valueToSet, failure);
622        }
623        return true;
624      }
625      localValue = value(); // we lost the cas, fall through and maybe cancel
626    }
627    // The future has already been set to something. If it is cancellation we should cancel the
628    // incoming future.
629    if (localValue instanceof Cancellation) {
630      // we don't care if it fails, this is best-effort.
631      future.cancel(((Cancellation) localValue).wasInterrupted);
632    }
633    return false;
634  }
635
636  @CanIgnoreReturnValue
637  final boolean setFutureInternal(ListenableFuture<? extends V> future) {
638    return setFuture(future);
639  }
640
641  /**
642   * Returns a value that satisfies the contract of the {@link #value} field based on the state of
643   * given future.
644   *
645   * <p>This is approximately the inverse of {@link #getDoneValue(Object)}
646   */
647  private static Object getFutureValue(ListenableFuture<?> future) {
648    if (future instanceof Trusted) {
649      // Break encapsulation for Trusted instances since we know that subclasses cannot override
650      // .get() and therefore this is equivalent to calling .get() and unpacking the exceptions like
651      // we do below (just much faster because it is a single field read instead of a read, several
652      // branches and possibly creating exceptions).
653      Object v = ((AbstractFuture<?>) future).value();
654      if (v instanceof Cancellation) {
655        // If the other future was interrupted, clear the interrupted bit while preserving the cause
656        // this will make it consistent with how non-trustedfutures work which cannot propagate the
657        // wasInterrupted bit
658        Cancellation c = (Cancellation) v;
659        if (c.wasInterrupted) {
660          v =
661              c.cause != null
662                  ? new Cancellation(/* wasInterrupted= */ false, c.cause)
663                  : Cancellation.CAUSELESS_CANCELLED;
664        }
665      }
666      // requireNonNull is safe as long as we call this method only on completed futures.
667      return requireNonNull(v);
668    }
669    if (future instanceof InternalFutureFailureAccess) {
670      Throwable throwable =
671          InternalFutures.tryInternalFastPathGetFailure((InternalFutureFailureAccess) future);
672      if (throwable != null) {
673        return new Failure(throwable);
674      }
675    }
676    boolean wasCancelled = future.isCancelled();
677    // Don't allocate a CancellationException if it's not necessary
678    if (!GENERATE_CANCELLATION_CAUSES & wasCancelled) {
679      /*
680       * requireNonNull is safe because we've initialized CAUSELESS_CANCELLED if
681       * !GENERATE_CANCELLATION_CAUSES.
682       */
683      return requireNonNull(Cancellation.CAUSELESS_CANCELLED);
684    }
685    // Otherwise calculate the value by calling .get()
686    try {
687      Object v = getUninterruptibly(future);
688      if (wasCancelled) {
689        return new Cancellation(
690            false,
691            new IllegalArgumentException(
692                "get() did not throw CancellationException, despite reporting "
693                    + "isCancelled() == true: "
694                    + future));
695      }
696      return maskNull(v);
697    } catch (ExecutionException exception) {
698      if (wasCancelled) {
699        return new Cancellation(
700            false,
701            new IllegalArgumentException(
702                "get() did not throw CancellationException, despite reporting "
703                    + "isCancelled() == true: "
704                    + future,
705                exception));
706      }
707      return new Failure(exception.getCause());
708    } catch (CancellationException cancellation) {
709      if (!wasCancelled) {
710        return new Failure(
711            new IllegalArgumentException(
712                "get() threw CancellationException, despite reporting isCancelled() == false: "
713                    + future,
714                cancellation));
715      }
716      return new Cancellation(false, cancellation);
717    } catch (Exception | Error t) { // sneaky checked exception
718      return new Failure(t);
719    }
720  }
721
722  /**
723   * An inlined private copy of {@link Uninterruptibles#getUninterruptibly} used to break an
724   * internal dependency on other /util/concurrent classes.
725   */
726  @ParametricNullness
727  private static <V extends @Nullable Object> V getUninterruptibly(Future<V> future)
728      throws ExecutionException {
729    boolean interrupted = false;
730    try {
731      while (true) {
732        try {
733          return future.get();
734        } catch (InterruptedException e) {
735          interrupted = true;
736        }
737      }
738    } finally {
739      if (interrupted) {
740        interruptCurrentThread();
741      }
742    }
743  }
744
745  /** Unblocks all threads and runs all listeners. */
746  private static void complete(AbstractFuture<?> param, boolean callInterruptTask) {
747    // Declare a "true" local variable so that the Checker Framework will infer nullness.
748    @RetainedLocalRef AbstractFuture<?> future = param;
749
750    @RetainedLocalRef Listener next = null;
751    outer:
752    while (true) {
753      future.releaseWaiters();
754      /*
755       * We call interruptTask() immediately before afterDone() so that migrating between the two
756       * can be a no-op.
757       */
758      if (callInterruptTask) {
759        future.interruptTask();
760        /*
761         * Interruption doesn't propagate through a DelegatingToFuture chain (see getFutureValue),
762         * so don't invoke interruptTask on any subsequent futures.
763         */
764        callInterruptTask = false;
765      }
766      // We call this before the listeners in order to avoid needing to manage a separate stack data
767      // structure for them.  Also, some implementations rely on this running prior to listeners
768      // so that the cleanup work is visible to listeners.
769      // afterDone() should be generally fast and only used for cleanup work... but in theory can
770      // also be recursive and create StackOverflowErrors
771      future.afterDone();
772      // push the current set of listeners onto next
773      next = future.clearListeners(next);
774      future = null;
775      while (next != null) {
776        @RetainedLocalRef Listener curr = next;
777        next = next.next;
778        /*
779         * requireNonNull is safe because the listener stack never contains TOMBSTONE until after
780         * clearListeners.
781         */
782        Runnable task = requireNonNull(curr.task);
783        if (task instanceof DelegatingToFuture) {
784          DelegatingToFuture<?> setFuture = (DelegatingToFuture<?>) task;
785          // We unwind setFuture specifically to avoid StackOverflowErrors in the case of long
786          // chains of DelegatingToFutures
787          // Handling this special case is important because there is no way to pass an executor to
788          // setFuture, so a user couldn't break the chain by doing this themselves.  It is also
789          // potentially common if someone writes a recursive Futures.transformAsync transformer.
790          future = setFuture.owner;
791          if (future.value() == setFuture) {
792            Object valueToSet = getFutureValue(setFuture.future);
793            if (casValue(future, setFuture, valueToSet)) {
794              continue outer;
795            }
796          }
797          // otherwise the future we were trying to set is already done.
798        } else {
799          /*
800           * requireNonNull is safe because the listener stack never contains TOMBSTONE until after
801           * clearListeners.
802           */
803          executeListener(task, requireNonNull(curr.executor));
804        }
805      }
806      break;
807    }
808  }
809
810  /**
811   * Callback method that is called exactly once after the future is completed.
812   *
813   * <p>If {@link #interruptTask} is also run during completion, {@link #afterDone} runs after it.
814   *
815   * <p>The default implementation of this method in {@code AbstractFuture} does nothing. This is
816   * intended for very lightweight cleanup work, for example, timing statistics or clearing fields.
817   * If your task does anything heavier consider, just using a listener with an executor.
818   *
819   * @since 20.0
820   */
821  @ForOverride
822  protected void afterDone() {}
823
824  // TODO(b/114236866): Inherit doc from InternalFutureFailureAccess. Also, -link to its URL.
825  /**
826   * Usually returns {@code null} but, if this {@code Future} has failed, may <i>optionally</i>
827   * return the cause of the failure. "Failure" means specifically "completed with an exception"; it
828   * does not include "was cancelled." To be explicit: If this method returns a non-null value,
829   * then:
830   *
831   * <ul>
832   *   <li>{@code isDone()} must return {@code true}
833   *   <li>{@code isCancelled()} must return {@code false}
834   *   <li>{@code get()} must not block, and it must throw an {@code ExecutionException} with the
835   *       return value of this method as its cause
836   * </ul>
837   *
838   * <p>This method is {@code protected} so that classes like {@code
839   * com.google.common.util.concurrent.SettableFuture} do not expose it to their users as an
840   * instance method. In the unlikely event that you need to call this method, call {@link
841   * InternalFutures#tryInternalFastPathGetFailure(InternalFutureFailureAccess)}.
842   *
843   * @since 27.0
844   */
845  @Override
846  /*
847   * We should annotate the superclass, InternalFutureFailureAccess, to say that its copy of this
848   * method returns @Nullable, too. However, we're not sure if we want to make any changes to that
849   * class, since it's in a separate artifact that we planned to release only a single version of.
850   */
851  protected final @Nullable Throwable tryInternalFastPathGetFailure() {
852    if (this instanceof Trusted) {
853      @RetainedLocalRef Object localValue = value();
854      if (localValue instanceof Failure) {
855        return ((Failure) localValue).exception;
856      }
857    }
858    return null;
859  }
860
861  /**
862   * If this future has been cancelled (and possibly interrupted), cancels (and possibly interrupts)
863   * the given future (if available).
864   */
865  @SuppressWarnings("nullness") // TODO(b/147136275): Remove once our checker understands & and |.
866  final void maybePropagateCancellationTo(@Nullable Future<?> related) {
867    if (related != null & isCancelled()) {
868      related.cancel(wasInterrupted());
869    }
870  }
871
872  /**
873   * Clears the {@link #listeners} list and prepends its contents to {@code onto}, least recently
874   * added first.
875   */
876  private @Nullable Listener clearListeners(@Nullable Listener onto) {
877    // We need to
878    // 1. atomically swap the listeners with TOMBSTONE, this is because addListener uses that
879    //    to synchronize with us
880    // 2. reverse the linked list, because despite our rather clear contract, people depend on us
881    //    executing listeners in the order they were added
882    // 3. push all the items onto 'onto' and return the new head of the stack
883    Listener head = gasListeners(Listener.TOMBSTONE);
884    Listener reversedList = onto;
885    while (head != null) {
886      Listener tmp = head;
887      head = head.next;
888      tmp.next = reversedList;
889      reversedList = tmp;
890    }
891    return reversedList;
892  }
893
894  // TODO(user): move parts into a default method on ListenableFuture?
895  @Override
896  public String toString() {
897    // TODO(cpovirk): Presize to something plausible?
898    StringBuilder builder = new StringBuilder();
899    if (getClass().getName().startsWith("com.google.common.util.concurrent.")) {
900      builder.append(getClass().getSimpleName());
901    } else {
902      builder.append(getClass().getName());
903    }
904    builder.append('@').append(toHexString(identityHashCode(this))).append("[status=");
905    if (isCancelled()) {
906      builder.append("CANCELLED");
907    } else if (isDone()) {
908      addDoneString(builder);
909    } else {
910      addPendingString(builder); // delegates to addDoneString if future completes midway
911    }
912    return builder.append("]").toString();
913  }
914
915  /**
916   * Provide a human-readable explanation of why this future has not yet completed.
917   *
918   * @return null if an explanation cannot be provided (e.g. because the future is done).
919   * @since 23.0
920   */
921  protected @Nullable String pendingToString() {
922    // TODO(diamondm) consider moving this into addPendingString so it's always in the output
923    if (this instanceof ScheduledFuture) {
924      return "remaining delay=[" + ((ScheduledFuture<?>) this).getDelay(MILLISECONDS) + " ms]";
925    }
926    return null;
927  }
928
929  @SuppressWarnings("CatchingUnchecked") // sneaky checked exception
930  private void addPendingString(StringBuilder builder) {
931    // Capture current builder length so it can be truncated if this future ends up completing while
932    // the toString is being calculated
933    int truncateLength = builder.length();
934
935    builder.append("PENDING");
936
937    @RetainedLocalRef Object localValue = value();
938    if (localValue instanceof DelegatingToFuture) {
939      builder.append(", setFuture=[");
940      appendUserObject(builder, ((DelegatingToFuture<?>) localValue).future);
941      builder.append("]");
942    } else {
943      String pendingDescription;
944      try {
945        pendingDescription = emptyToNull(pendingToString());
946      } catch (Throwable e) {
947        /*
948         * We want to catch (Exception | StackOverflowError), but we can't under environments where
949         * StackOverflowError doesn't exist.
950         */
951        rethrowIfErrorOtherThanStackOverflow(e);
952        // The Throwable is either a RuntimeException, an Error, or sneaky checked exception.
953        //
954        // Don't call getMessage or toString() on the exception, in case the exception thrown by the
955        // subclass is implemented with bugs similar to the subclass.
956        pendingDescription = "Exception thrown from implementation: " + e.getClass();
957      }
958      if (pendingDescription != null) {
959        builder.append(", info=[").append(pendingDescription).append("]");
960      }
961    }
962
963    // The future may complete while calculating the toString, so we check once more to see if the
964    // future is done
965    if (isDone()) {
966      // Truncate anything that was appended before realizing this future is done
967      builder.delete(truncateLength, builder.length());
968      addDoneString(builder);
969    }
970  }
971
972  @SuppressWarnings("CatchingUnchecked") // sneaky checked exception
973  private void addDoneString(StringBuilder builder) {
974    try {
975      V value = getUninterruptibly(this);
976      builder.append("SUCCESS, result=[");
977      appendResultObject(builder, value);
978      builder.append("]");
979    } catch (ExecutionException e) {
980      builder.append("FAILURE, cause=[").append(e.getCause()).append("]");
981    } catch (CancellationException e) {
982      builder.append("CANCELLED"); // shouldn't be reachable
983    } catch (Exception e) { // sneaky checked exception
984      builder.append("UNKNOWN, cause=[").append(e.getClass()).append(" thrown from get()]");
985    }
986  }
987
988  /**
989   * Any object can be the result of a Future, and not every object has a reasonable toString()
990   * implementation. Using a reconstruction of the default Object.toString() prevents OOMs and stack
991   * overflows, and helps avoid sensitive data inadvertently ending up in exception messages.
992   */
993  private void appendResultObject(StringBuilder builder, @Nullable Object o) {
994    if (o == null) {
995      builder.append("null");
996    } else if (o == this) {
997      builder.append("this future");
998    } else {
999      builder
1000          .append(o.getClass().getName())
1001          .append("@")
1002          .append(Integer.toHexString(System.identityHashCode(o)));
1003    }
1004  }
1005
1006  /** Helper for printing user supplied objects into our toString method. */
1007  @SuppressWarnings("CatchingUnchecked") // sneaky checked exception
1008  private void appendUserObject(StringBuilder builder, @Nullable Object o) {
1009    // This is some basic recursion detection for when people create cycles via set/setFuture or
1010    // when deep chains of futures exist resulting in a StackOverflowError. We could detect
1011    // arbitrary cycles using a thread local but this should be a good enough solution (it is also
1012    // what jdk collections do in these cases)
1013    try {
1014      if (o == this) {
1015        builder.append("this future");
1016      } else {
1017        builder.append(o);
1018      }
1019    } catch (Throwable e) {
1020      /*
1021       * We want to catch (Exception | StackOverflowError), but we can't under environments where
1022       * StackOverflowError doesn't exist.
1023       */
1024      rethrowIfErrorOtherThanStackOverflow(e);
1025      // The Throwable is either a RuntimeException, an Error, or sneaky checked exception.
1026      //
1027      // Don't call getMessage or toString() on the exception, in case the exception thrown by the
1028      // user object is implemented with bugs similar to the user object.
1029      builder.append("Exception thrown from implementation: ").append(e.getClass());
1030    }
1031  }
1032
1033  /**
1034   * Submits the given runnable to the given {@link Executor} catching and logging all {@linkplain
1035   * RuntimeException runtime exceptions} thrown by the executor.
1036   */
1037  @SuppressWarnings("CatchingUnchecked") // sneaky checked exception
1038  private static void executeListener(Runnable runnable, Executor executor) {
1039    try {
1040      executor.execute(runnable);
1041    } catch (Exception e) { // sneaky checked exception
1042      // Log it and keep going -- bad runnable and/or executor. Don't punish the other runnables if
1043      // we're given a bad one. We only catch Exception because we want Errors to propagate up.
1044      log.get()
1045          .log(
1046              SEVERE,
1047              "RuntimeException while executing runnable "
1048                  + runnable
1049                  + " with executor "
1050                  + executor,
1051              e);
1052    }
1053  }
1054
1055  private static Object maskNull(@Nullable Object v) {
1056    return v == null ? NULL : v;
1057  }
1058}