001/*
002 * Copyright (C) 2006 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.Preconditions.checkState;
019import static com.google.common.util.concurrent.Internal.toNanosSaturated;
020import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
021import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
022import static java.util.Objects.requireNonNull;
023
024import com.google.common.annotations.GwtCompatible;
025import com.google.common.annotations.GwtIncompatible;
026import com.google.common.annotations.J2ktIncompatible;
027import com.google.common.base.Function;
028import com.google.common.base.MoreObjects;
029import com.google.common.base.Preconditions;
030import com.google.common.collect.ImmutableList;
031import com.google.common.util.concurrent.CollectionFuture.ListFuture;
032import com.google.common.util.concurrent.ImmediateFuture.ImmediateCancelledFuture;
033import com.google.common.util.concurrent.ImmediateFuture.ImmediateFailedFuture;
034import com.google.common.util.concurrent.internal.InternalFutureFailureAccess;
035import com.google.common.util.concurrent.internal.InternalFutures;
036import com.google.errorprone.annotations.CanIgnoreReturnValue;
037import com.google.errorprone.annotations.concurrent.LazyInit;
038import java.time.Duration;
039import java.util.Collection;
040import java.util.List;
041import java.util.concurrent.Callable;
042import java.util.concurrent.CancellationException;
043import java.util.concurrent.ExecutionException;
044import java.util.concurrent.Executor;
045import java.util.concurrent.Future;
046import java.util.concurrent.RejectedExecutionException;
047import java.util.concurrent.ScheduledExecutorService;
048import java.util.concurrent.TimeUnit;
049import java.util.concurrent.TimeoutException;
050import java.util.concurrent.atomic.AtomicInteger;
051import javax.annotation.CheckForNull;
052import org.checkerframework.checker.nullness.qual.Nullable;
053
054/**
055 * Static utility methods pertaining to the {@link Future} interface.
056 *
057 * <p>Many of these methods use the {@link ListenableFuture} API; consult the Guava User Guide
058 * article on <a href="https://github.com/google/guava/wiki/ListenableFutureExplained">{@code
059 * ListenableFuture}</a>.
060 *
061 * <p>The main purpose of {@code ListenableFuture} is to help you chain together a graph of
062 * asynchronous operations. You can chain them together manually with calls to methods like {@link
063 * Futures#transform(ListenableFuture, Function, Executor) Futures.transform}, but you will often
064 * find it easier to use a framework. Frameworks automate the process, often adding features like
065 * monitoring, debugging, and cancellation. Examples of frameworks include:
066 *
067 * <ul>
068 *   <li><a href="https://dagger.dev/producers.html">Dagger Producers</a>
069 * </ul>
070 *
071 * <p>If you do chain your operations manually, you may want to use {@link FluentFuture}.
072 *
073 * @author Kevin Bourrillion
074 * @author Nishant Thakkar
075 * @author Sven Mawson
076 * @since 1.0
077 */
078@GwtCompatible(emulated = true)
079@ElementTypesAreNonnullByDefault
080public final class Futures extends GwtFuturesCatchingSpecialization {
081
082  // A note on memory visibility.
083  // Many of the utilities in this class (transform, withFallback, withTimeout, asList, combine)
084  // have two requirements that significantly complicate their design.
085  // 1. Cancellation should propagate from the returned future to the input future(s).
086  // 2. The returned futures shouldn't unnecessarily 'pin' their inputs after completion.
087  //
088  // A consequence of these requirements is that the delegate futures cannot be stored in
089  // final fields.
090  //
091  // For simplicity the rest of this description will discuss Futures.catching since it is the
092  // simplest instance, though very similar descriptions apply to many other classes in this file.
093  //
094  // In the constructor of AbstractCatchingFuture, the delegate future is assigned to a field
095  // 'inputFuture'. That field is non-final and non-volatile. There are 2 places where the
096  // 'inputFuture' field is read and where we will have to consider visibility of the write
097  // operation in the constructor.
098  //
099  // 1. In the listener that performs the callback. In this case it is fine since inputFuture is
100  //    assigned prior to calling addListener, and addListener happens-before any invocation of the
101  //    listener. Notably, this means that 'volatile' is unnecessary to make 'inputFuture' visible
102  //    to the listener.
103  //
104  // 2. In done() where we may propagate cancellation to the input. In this case it is _not_ fine.
105  //    There is currently nothing that enforces that the write to inputFuture in the constructor is
106  //    visible to done(). This is because there is no happens before edge between the write and a
107  //    (hypothetical) unsafe read by our caller. Note: adding 'volatile' does not fix this issue,
108  //    it would just add an edge such that if done() observed non-null, then it would also
109  //    definitely observe all earlier writes, but we still have no guarantee that done() would see
110  //    the initial write (just stronger guarantees if it does).
111  //
112  // See: http://cs.oswego.edu/pipermail/concurrency-interest/2015-January/013800.html
113  // For a (long) discussion about this specific issue and the general futility of life.
114  //
115  // For the time being we are OK with the problem discussed above since it requires a caller to
116  // introduce a very specific kind of data-race. And given the other operations performed by these
117  // methods that involve volatile read/write operations, in practice there is no issue. Also, the
118  // way in such a visibility issue would surface is most likely as a failure of cancel() to
119  // propagate to the input. Cancellation propagation is fundamentally racy so this is fine.
120  //
121  // Future versions of the JMM may revise safe construction semantics in such a way that we can
122  // safely publish these objects and we won't need this whole discussion.
123  // TODO(user,lukes): consider adding volatile to all these fields since in current known JVMs
124  // that should resolve the issue. This comes at the cost of adding more write barriers to the
125  // implementations.
126
127  private Futures() {}
128
129  /**
130   * Creates a {@code ListenableFuture} which has its value set immediately upon construction. The
131   * getters just return the value. This {@code Future} can't be canceled or timed out and its
132   * {@code isDone()} method always returns {@code true}.
133   */
134  public static <V extends @Nullable Object> ListenableFuture<V> immediateFuture(
135      @ParametricNullness V value) {
136    if (value == null) {
137      // This cast is safe because null is assignable to V for all V (i.e. it is bivariant)
138      @SuppressWarnings("unchecked")
139      ListenableFuture<V> typedNull = (ListenableFuture<V>) ImmediateFuture.NULL;
140      return typedNull;
141    }
142    return new ImmediateFuture<>(value);
143  }
144
145  /**
146   * Returns a successful {@code ListenableFuture<Void>}. This method is equivalent to {@code
147   * immediateFuture(null)} except that it is restricted to produce futures of type {@code Void}.
148   *
149   * @since 29.0
150   */
151  @SuppressWarnings("unchecked")
152  public static ListenableFuture<@Nullable Void> immediateVoidFuture() {
153    return (ListenableFuture<@Nullable Void>) ImmediateFuture.NULL;
154  }
155
156  /**
157   * Returns a {@code ListenableFuture} which has an exception set immediately upon construction.
158   *
159   * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()} method always
160   * returns {@code true}. Calling {@code get()} will immediately throw the provided {@code
161   * Throwable} wrapped in an {@code ExecutionException}.
162   */
163  public static <V extends @Nullable Object> ListenableFuture<V> immediateFailedFuture(
164      Throwable throwable) {
165    checkNotNull(throwable);
166    return new ImmediateFailedFuture<>(throwable);
167  }
168
169  /**
170   * Creates a {@code ListenableFuture} which is cancelled immediately upon construction, so that
171   * {@code isCancelled()} always returns {@code true}.
172   *
173   * @since 14.0
174   */
175  @SuppressWarnings("unchecked") // ImmediateCancelledFuture can work with any type
176  public static <V extends @Nullable Object> ListenableFuture<V> immediateCancelledFuture() {
177    ListenableFuture<Object> instance = ImmediateCancelledFuture.INSTANCE;
178    if (instance != null) {
179      return (ListenableFuture<V>) instance;
180    }
181    return new ImmediateCancelledFuture<>();
182  }
183
184  /**
185   * Executes {@code callable} on the specified {@code executor}, returning a {@code Future}.
186   *
187   * @throws RejectedExecutionException if the task cannot be scheduled for execution
188   * @since 28.2
189   */
190  public static <O extends @Nullable Object> ListenableFuture<O> submit(
191      Callable<O> callable, Executor executor) {
192    TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
193    executor.execute(task);
194    return task;
195  }
196
197  /**
198   * Executes {@code runnable} on the specified {@code executor}, returning a {@code Future} that
199   * will complete after execution.
200   *
201   * @throws RejectedExecutionException if the task cannot be scheduled for execution
202   * @since 28.2
203   */
204  public static ListenableFuture<@Nullable Void> submit(Runnable runnable, Executor executor) {
205    TrustedListenableFutureTask<@Nullable Void> task =
206        TrustedListenableFutureTask.create(runnable, null);
207    executor.execute(task);
208    return task;
209  }
210
211  /**
212   * Executes {@code callable} on the specified {@code executor}, returning a {@code Future}.
213   *
214   * @throws RejectedExecutionException if the task cannot be scheduled for execution
215   * @since 23.0
216   */
217  public static <O extends @Nullable Object> ListenableFuture<O> submitAsync(
218      AsyncCallable<O> callable, Executor executor) {
219    TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
220    executor.execute(task);
221    return task;
222  }
223
224  /**
225   * Schedules {@code callable} on the specified {@code executor}, returning a {@code Future}.
226   *
227   * @throws RejectedExecutionException if the task cannot be scheduled for execution
228   * @since 28.0
229   */
230  @J2ktIncompatible
231  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
232  // TODO(cpovirk): Return ListenableScheduledFuture?
233  public static <O extends @Nullable Object> ListenableFuture<O> scheduleAsync(
234      AsyncCallable<O> callable, Duration delay, ScheduledExecutorService executorService) {
235    return scheduleAsync(callable, toNanosSaturated(delay), TimeUnit.NANOSECONDS, executorService);
236  }
237
238  /**
239   * Schedules {@code callable} on the specified {@code executor}, returning a {@code Future}.
240   *
241   * @throws RejectedExecutionException if the task cannot be scheduled for execution
242   * @since 23.0
243   */
244  @J2ktIncompatible
245  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
246  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
247  // TODO(cpovirk): Return ListenableScheduledFuture?
248  public static <O extends @Nullable Object> ListenableFuture<O> scheduleAsync(
249      AsyncCallable<O> callable,
250      long delay,
251      TimeUnit timeUnit,
252      ScheduledExecutorService executorService) {
253    TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
254    Future<?> scheduled = executorService.schedule(task, delay, timeUnit);
255    /*
256     * Even when the user interrupts the task, we pass `false` to `cancel` so that we don't
257     * interrupt a second time after the interruption performed by TrustedListenableFutureTask.
258     */
259    task.addListener(() -> scheduled.cancel(false), directExecutor());
260    return task;
261  }
262
263  /**
264   * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
265   * primary input fails with the given {@code exceptionType}, from the result provided by the
266   * {@code fallback}. {@link Function#apply} is not invoked until the primary input has failed, so
267   * if the primary input succeeds, it is never invoked. If, during the invocation of {@code
268   * fallback}, an exception is thrown, this exception is used as the result of the output {@code
269   * Future}.
270   *
271   * <p>Usage example:
272   *
273   * <pre>{@code
274   * ListenableFuture<Integer> fetchCounterFuture = ...;
275   *
276   * // Falling back to a zero counter in case an exception happens when
277   * // processing the RPC to fetch counters.
278   * ListenableFuture<Integer> faultTolerantFuture = Futures.catching(
279   *     fetchCounterFuture, FetchException.class, x -> 0, directExecutor());
280   * }</pre>
281   *
282   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
283   * the warnings the {@link MoreExecutors#directExecutor} documentation.
284   *
285   * @param input the primary input {@code Future}
286   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
287   *     type is matched against the input's exception. "The input's exception" means the cause of
288   *     the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
289   *     different kind of exception, that exception itself. To avoid hiding bugs and other
290   *     unrecoverable errors, callers should prefer more specific types, avoiding {@code
291   *     Throwable.class} in particular.
292   * @param fallback the {@link Function} to be called if {@code input} fails with the expected
293   *     exception type. The function's argument is the input's exception. "The input's exception"
294   *     means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
295   *     {@code get()} throws a different kind of exception, that exception itself.
296   * @param executor the executor that runs {@code fallback} if {@code input} fails
297   * @since 19.0
298   */
299  @J2ktIncompatible
300  @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
301  public static <V extends @Nullable Object, X extends Throwable> ListenableFuture<V> catching(
302      ListenableFuture<? extends V> input,
303      Class<X> exceptionType,
304      Function<? super X, ? extends V> fallback,
305      Executor executor) {
306    return AbstractCatchingFuture.create(input, exceptionType, fallback, executor);
307  }
308
309  /**
310   * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
311   * primary input fails with the given {@code exceptionType}, from the result provided by the
312   * {@code fallback}. {@link AsyncFunction#apply} is not invoked until the primary input has
313   * failed, so if the primary input succeeds, it is never invoked. If, during the invocation of
314   * {@code fallback}, an exception is thrown, this exception is used as the result of the output
315   * {@code Future}.
316   *
317   * <p>Usage examples:
318   *
319   * <pre>{@code
320   * ListenableFuture<Integer> fetchCounterFuture = ...;
321   *
322   * // Falling back to a zero counter in case an exception happens when
323   * // processing the RPC to fetch counters.
324   * ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
325   *     fetchCounterFuture, FetchException.class, x -> immediateFuture(0), directExecutor());
326   * }</pre>
327   *
328   * <p>The fallback can also choose to propagate the original exception when desired:
329   *
330   * <pre>{@code
331   * ListenableFuture<Integer> fetchCounterFuture = ...;
332   *
333   * // Falling back to a zero counter only in case the exception was a
334   * // TimeoutException.
335   * ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
336   *     fetchCounterFuture,
337   *     FetchException.class,
338   *     e -> {
339   *       if (omitDataOnFetchFailure) {
340   *         return immediateFuture(0);
341   *       }
342   *       throw e;
343   *     },
344   *     directExecutor());
345   * }</pre>
346   *
347   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
348   * the warnings the {@link MoreExecutors#directExecutor} documentation.
349   *
350   * @param input the primary input {@code Future}
351   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
352   *     type is matched against the input's exception. "The input's exception" means the cause of
353   *     the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
354   *     different kind of exception, that exception itself. To avoid hiding bugs and other
355   *     unrecoverable errors, callers should prefer more specific types, avoiding {@code
356   *     Throwable.class} in particular.
357   * @param fallback the {@link AsyncFunction} to be called if {@code input} fails with the expected
358   *     exception type. The function's argument is the input's exception. "The input's exception"
359   *     means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
360   *     {@code get()} throws a different kind of exception, that exception itself.
361   * @param executor the executor that runs {@code fallback} if {@code input} fails
362   * @since 19.0 (similar functionality in 14.0 as {@code withFallback})
363   */
364  @J2ktIncompatible
365  @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
366  public static <V extends @Nullable Object, X extends Throwable> ListenableFuture<V> catchingAsync(
367      ListenableFuture<? extends V> input,
368      Class<X> exceptionType,
369      AsyncFunction<? super X, ? extends V> fallback,
370      Executor executor) {
371    return AbstractCatchingFuture.createAsync(input, exceptionType, fallback, executor);
372  }
373
374  /**
375   * Returns a future that delegates to another but will finish early (via a {@link
376   * TimeoutException} wrapped in an {@link ExecutionException}) if the specified duration expires.
377   *
378   * <p>The delegate future is interrupted and cancelled if it times out.
379   *
380   * @param delegate The future to delegate to.
381   * @param time when to time out the future
382   * @param scheduledExecutor The executor service to enforce the timeout.
383   * @since 28.0
384   */
385  @J2ktIncompatible
386  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
387  public static <V extends @Nullable Object> ListenableFuture<V> withTimeout(
388      ListenableFuture<V> delegate, Duration time, ScheduledExecutorService scheduledExecutor) {
389    return withTimeout(delegate, toNanosSaturated(time), TimeUnit.NANOSECONDS, scheduledExecutor);
390  }
391
392  /**
393   * Returns a future that delegates to another but will finish early (via a {@link
394   * TimeoutException} wrapped in an {@link ExecutionException}) if the specified duration expires.
395   *
396   * <p>The delegate future is interrupted and cancelled if it times out.
397   *
398   * @param delegate The future to delegate to.
399   * @param time when to time out the future
400   * @param unit the time unit of the time parameter
401   * @param scheduledExecutor The executor service to enforce the timeout.
402   * @since 19.0
403   */
404  @J2ktIncompatible
405  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
406  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
407  public static <V extends @Nullable Object> ListenableFuture<V> withTimeout(
408      ListenableFuture<V> delegate,
409      long time,
410      TimeUnit unit,
411      ScheduledExecutorService scheduledExecutor) {
412    if (delegate.isDone()) {
413      return delegate;
414    }
415    return TimeoutFuture.create(delegate, time, unit, scheduledExecutor);
416  }
417
418  /**
419   * Returns a new {@code Future} whose result is asynchronously derived from the result of the
420   * given {@code Future}. If the given {@code Future} fails, the returned {@code Future} fails with
421   * the same exception (and the function is not invoked).
422   *
423   * <p>More precisely, the returned {@code Future} takes its result from a {@code Future} produced
424   * by applying the given {@code AsyncFunction} to the result of the original {@code Future}.
425   * Example usage:
426   *
427   * <pre>{@code
428   * ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
429   * ListenableFuture<QueryResult> queryFuture =
430   *     transformAsync(rowKeyFuture, dataService::readFuture, executor);
431   * }</pre>
432   *
433   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
434   * the warnings the {@link MoreExecutors#directExecutor} documentation.
435   *
436   * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
437   * input future and that of the future returned by the chain function. That is, if the returned
438   * {@code Future} is cancelled, it will attempt to cancel the other two, and if either of the
439   * other two is cancelled, the returned {@code Future} will receive a callback in which it will
440   * attempt to cancel itself.
441   *
442   * @param input The future to transform
443   * @param function A function to transform the result of the input future to the result of the
444   *     output future
445   * @param executor Executor to run the function in.
446   * @return A future that holds result of the function (if the input succeeded) or the original
447   *     input's failure (if not)
448   * @since 19.0 (in 11.0 as {@code transform})
449   */
450  public static <I extends @Nullable Object, O extends @Nullable Object>
451      ListenableFuture<O> transformAsync(
452          ListenableFuture<I> input,
453          AsyncFunction<? super I, ? extends O> function,
454          Executor executor) {
455    return AbstractTransformFuture.createAsync(input, function, executor);
456  }
457
458  /**
459   * Returns a new {@code Future} whose result is derived from the result of the given {@code
460   * Future}. If {@code input} fails, the returned {@code Future} fails with the same exception (and
461   * the function is not invoked). Example usage:
462   *
463   * <pre>{@code
464   * ListenableFuture<QueryResult> queryFuture = ...;
465   * ListenableFuture<List<Row>> rowsFuture =
466   *     transform(queryFuture, QueryResult::getRows, executor);
467   * }</pre>
468   *
469   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
470   * the warnings the {@link MoreExecutors#directExecutor} documentation.
471   *
472   * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
473   * input future. That is, if the returned {@code Future} is cancelled, it will attempt to cancel
474   * the input, and if the input is cancelled, the returned {@code Future} will receive a callback
475   * in which it will attempt to cancel itself.
476   *
477   * <p>An example use of this method is to convert a serializable object returned from an RPC into
478   * a POJO.
479   *
480   * @param input The future to transform
481   * @param function A Function to transform the results of the provided future to the results of
482   *     the returned future.
483   * @param executor Executor to run the function in.
484   * @return A future that holds result of the transformation.
485   * @since 9.0 (in 2.0 as {@code compose})
486   */
487  public static <I extends @Nullable Object, O extends @Nullable Object>
488      ListenableFuture<O> transform(
489          ListenableFuture<I> input, Function<? super I, ? extends O> function, Executor executor) {
490    return AbstractTransformFuture.create(input, function, executor);
491  }
492
493  /**
494   * Like {@link #transform(ListenableFuture, Function, Executor)} except that the transformation
495   * {@code function} is invoked on each call to {@link Future#get() get()} on the returned future.
496   *
497   * <p>The returned {@code Future} reflects the input's cancellation state directly, and any
498   * attempt to cancel the returned Future is likewise passed through to the input Future.
499   *
500   * <p>Note that calls to {@linkplain Future#get(long, TimeUnit) timed get} only apply the timeout
501   * to the execution of the underlying {@code Future}, <em>not</em> to the execution of the
502   * transformation function.
503   *
504   * <p>The primary audience of this method is callers of {@code transform} who don't have a {@code
505   * ListenableFuture} available and do not mind repeated, lazy function evaluation.
506   *
507   * @param input The future to transform
508   * @param function A Function to transform the results of the provided future to the results of
509   *     the returned future.
510   * @return A future that returns the result of the transformation.
511   * @since 10.0
512   */
513  @J2ktIncompatible
514  @GwtIncompatible // TODO
515  public static <I extends @Nullable Object, O extends @Nullable Object> Future<O> lazyTransform(
516      final Future<I> input, final Function<? super I, ? extends O> function) {
517    checkNotNull(input);
518    checkNotNull(function);
519    return new Future<O>() {
520
521      @Override
522      public boolean cancel(boolean mayInterruptIfRunning) {
523        return input.cancel(mayInterruptIfRunning);
524      }
525
526      @Override
527      public boolean isCancelled() {
528        return input.isCancelled();
529      }
530
531      @Override
532      public boolean isDone() {
533        return input.isDone();
534      }
535
536      @Override
537      public O get() throws InterruptedException, ExecutionException {
538        return applyTransformation(input.get());
539      }
540
541      @Override
542      public O get(long timeout, TimeUnit unit)
543          throws InterruptedException, ExecutionException, TimeoutException {
544        return applyTransformation(input.get(timeout, unit));
545      }
546
547      private O applyTransformation(I input) throws ExecutionException {
548        try {
549          return function.apply(input);
550        } catch (Throwable t) {
551          // Any Exception is either a RuntimeException or sneaky checked exception.
552          throw new ExecutionException(t);
553        }
554      }
555    };
556  }
557
558  /**
559   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
560   * input futures, if all succeed.
561   *
562   * <p>The list of results is in the same order as the input list.
563   *
564   * <p>This differs from {@link #successfulAsList(ListenableFuture[])} in that it will return a
565   * failed future if any of the items fails.
566   *
567   * <p>Canceling this future will attempt to cancel all the component futures, and if any of the
568   * provided futures fails or is canceled, this one is, too.
569   *
570   * @param futures futures to combine
571   * @return a future that provides a list of the results of the component futures
572   * @since 10.0
573   */
574  @SafeVarargs
575  public static <V extends @Nullable Object> ListenableFuture<List<V>> allAsList(
576      ListenableFuture<? extends V>... futures) {
577    ListenableFuture<List<@Nullable V>> nullable =
578        new ListFuture<V>(ImmutableList.copyOf(futures), true);
579    // allAsList ensures that it fills the output list with V instances.
580    @SuppressWarnings("nullness")
581    ListenableFuture<List<V>> nonNull = nullable;
582    return nonNull;
583  }
584
585  /**
586   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
587   * input futures, if all succeed.
588   *
589   * <p>The list of results is in the same order as the input list.
590   *
591   * <p>This differs from {@link #successfulAsList(Iterable)} in that it will return a failed future
592   * if any of the items fails.
593   *
594   * <p>Canceling this future will attempt to cancel all the component futures, and if any of the
595   * provided futures fails or is canceled, this one is, too.
596   *
597   * @param futures futures to combine
598   * @return a future that provides a list of the results of the component futures
599   * @since 10.0
600   */
601  public static <V extends @Nullable Object> ListenableFuture<List<V>> allAsList(
602      Iterable<? extends ListenableFuture<? extends V>> futures) {
603    ListenableFuture<List<@Nullable V>> nullable =
604        new ListFuture<V>(ImmutableList.copyOf(futures), true);
605    // allAsList ensures that it fills the output list with V instances.
606    @SuppressWarnings("nullness")
607    ListenableFuture<List<V>> nonNull = nullable;
608    return nonNull;
609  }
610
611  /**
612   * Creates a {@link FutureCombiner} that processes the completed futures whether or not they're
613   * successful.
614   *
615   * <p>Any failures from the input futures will not be propagated to the returned future.
616   *
617   * @since 20.0
618   */
619  @SafeVarargs
620  public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
621      ListenableFuture<? extends V>... futures) {
622    return new FutureCombiner<>(false, ImmutableList.copyOf(futures));
623  }
624
625  /**
626   * Creates a {@link FutureCombiner} that processes the completed futures whether or not they're
627   * successful.
628   *
629   * <p>Any failures from the input futures will not be propagated to the returned future.
630   *
631   * @since 20.0
632   */
633  public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
634      Iterable<? extends ListenableFuture<? extends V>> futures) {
635    return new FutureCombiner<>(false, ImmutableList.copyOf(futures));
636  }
637
638  /**
639   * Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
640   *
641   * <p>If any input fails, the returned future fails immediately.
642   *
643   * @since 20.0
644   */
645  @SafeVarargs
646  public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
647      ListenableFuture<? extends V>... futures) {
648    return new FutureCombiner<>(true, ImmutableList.copyOf(futures));
649  }
650
651  /**
652   * Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
653   *
654   * <p>If any input fails, the returned future fails immediately.
655   *
656   * @since 20.0
657   */
658  public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
659      Iterable<? extends ListenableFuture<? extends V>> futures) {
660    return new FutureCombiner<>(true, ImmutableList.copyOf(futures));
661  }
662
663  /**
664   * A helper to create a new {@code ListenableFuture} whose result is generated from a combination
665   * of input futures.
666   *
667   * <p>See {@link #whenAllComplete} and {@link #whenAllSucceed} for how to instantiate this class.
668   *
669   * <p>Example:
670   *
671   * <pre>{@code
672   * final ListenableFuture<Instant> loginDateFuture =
673   *     loginService.findLastLoginDate(username);
674   * final ListenableFuture<List<String>> recentCommandsFuture =
675   *     recentCommandsService.findRecentCommands(username);
676   * ListenableFuture<UsageHistory> usageFuture =
677   *     Futures.whenAllSucceed(loginDateFuture, recentCommandsFuture)
678   *         .call(
679   *             () ->
680   *                 new UsageHistory(
681   *                     username,
682   *                     Futures.getDone(loginDateFuture),
683   *                     Futures.getDone(recentCommandsFuture)),
684   *             executor);
685   * }</pre>
686   *
687   * @since 20.0
688   */
689  @GwtCompatible
690  public static final class FutureCombiner<V extends @Nullable Object> {
691    private final boolean allMustSucceed;
692    private final ImmutableList<ListenableFuture<? extends V>> futures;
693
694    private FutureCombiner(
695        boolean allMustSucceed, ImmutableList<ListenableFuture<? extends V>> futures) {
696      this.allMustSucceed = allMustSucceed;
697      this.futures = futures;
698    }
699
700    /**
701     * Creates the {@link ListenableFuture} which will return the result of calling {@link
702     * AsyncCallable#call} in {@code combiner} when all futures complete, using the specified {@code
703     * executor}.
704     *
705     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
706     * cancelled.
707     *
708     * <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code
709     * ExecutionException} will be extracted and returned as the cause of the new {@code
710     * ExecutionException} that gets thrown by the returned combined future.
711     *
712     * <p>Canceling this future will attempt to cancel all the component futures.
713     *
714     * @return a future whose result is based on {@code combiner} (or based on the input futures
715     *     passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
716     *     FutureCombiner}). Even if you don't care about the value of the future, you should
717     *     typically check whether it failed: See <a
718     *     href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
719     */
720    public <C extends @Nullable Object> ListenableFuture<C> callAsync(
721        AsyncCallable<C> combiner, Executor executor) {
722      return new CombinedFuture<>(futures, allMustSucceed, executor, combiner);
723    }
724
725    /**
726     * Creates the {@link ListenableFuture} which will return the result of calling {@link
727     * Callable#call} in {@code combiner} when all futures complete, using the specified {@code
728     * executor}.
729     *
730     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
731     * cancelled.
732     *
733     * <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code
734     * ExecutionException} will be extracted and returned as the cause of the new {@code
735     * ExecutionException} that gets thrown by the returned combined future.
736     *
737     * <p>Canceling this future will attempt to cancel all the component futures.
738     *
739     * @return a future whose result is based on {@code combiner} (or based on the input futures
740     *     passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
741     *     FutureCombiner}). Even if you don't care about the value of the future, you should
742     *     typically check whether it failed: See <a
743     *     href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
744     */
745    public <C extends @Nullable Object> ListenableFuture<C> call(
746        Callable<C> combiner, Executor executor) {
747      return new CombinedFuture<>(futures, allMustSucceed, executor, combiner);
748    }
749
750    /**
751     * Creates the {@link ListenableFuture} which will return the result of running {@code combiner}
752     * when all Futures complete. {@code combiner} will run using {@code executor}.
753     *
754     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
755     * cancelled.
756     *
757     * <p>Canceling this Future will attempt to cancel all the component futures.
758     *
759     * @since 23.6
760     * @return a future whose result is based on {@code combiner} (or based on the input futures
761     *     passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
762     *     FutureCombiner}). Even though the future never produces a value other than {@code null},
763     *     you should typically check whether it failed: See <a
764     *     href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
765     */
766    public ListenableFuture<?> run(final Runnable combiner, Executor executor) {
767      return call(
768          new Callable<@Nullable Void>() {
769            @Override
770            @CheckForNull
771            public Void call() throws Exception {
772              combiner.run();
773              return null;
774            }
775          },
776          executor);
777    }
778  }
779
780  /**
781   * Returns a {@code ListenableFuture} whose result is set from the supplied future when it
782   * completes. Cancelling the supplied future will also cancel the returned future, but cancelling
783   * the returned future will have no effect on the supplied future.
784   *
785   * @since 15.0
786   */
787  public static <V extends @Nullable Object> ListenableFuture<V> nonCancellationPropagating(
788      ListenableFuture<V> future) {
789    if (future.isDone()) {
790      return future;
791    }
792    NonCancellationPropagatingFuture<V> output = new NonCancellationPropagatingFuture<>(future);
793    future.addListener(output, directExecutor());
794    return output;
795  }
796
797  /** A wrapped future that does not propagate cancellation to its delegate. */
798  private static final class NonCancellationPropagatingFuture<V extends @Nullable Object>
799      extends AbstractFuture.TrustedFuture<V> implements Runnable {
800    @CheckForNull @LazyInit private ListenableFuture<V> delegate;
801
802    NonCancellationPropagatingFuture(final ListenableFuture<V> delegate) {
803      this.delegate = delegate;
804    }
805
806    @Override
807    public void run() {
808      // This prevents cancellation from propagating because we don't call setFuture(delegate) until
809      // delegate is already done, so calling cancel() on this future won't affect it.
810      ListenableFuture<V> localDelegate = delegate;
811      if (localDelegate != null) {
812        setFuture(localDelegate);
813      }
814    }
815
816    @Override
817    @CheckForNull
818    protected String pendingToString() {
819      ListenableFuture<V> localDelegate = delegate;
820      if (localDelegate != null) {
821        return "delegate=[" + localDelegate + "]";
822      }
823      return null;
824    }
825
826    @Override
827    protected void afterDone() {
828      delegate = null;
829    }
830  }
831
832  /**
833   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
834   * successful input futures. The list of results is in the same order as the input list, and if
835   * any of the provided futures fails or is canceled, its corresponding position will contain
836   * {@code null} (which is indistinguishable from the future having a successful value of {@code
837   * null}).
838   *
839   * <p>The list of results is in the same order as the input list.
840   *
841   * <p>This differs from {@link #allAsList(ListenableFuture[])} in that it's tolerant of failed
842   * futures for any of the items, representing them as {@code null} in the result list.
843   *
844   * <p>Canceling this future will attempt to cancel all the component futures.
845   *
846   * @param futures futures to combine
847   * @return a future that provides a list of the results of the component futures
848   * @since 10.0
849   */
850  @SafeVarargs
851  public static <V extends @Nullable Object> ListenableFuture<List<@Nullable V>> successfulAsList(
852      ListenableFuture<? extends V>... futures) {
853    /*
854     * Another way to express this signature would be to bound <V> by @NonNull and accept
855     * LF<? extends @Nullable V>. That might be better: There's currently no difference between the
856     * outputs users get when calling this with <Foo> and calling it with <@Nullable Foo>. The only
857     * difference is that calling it with <Foo> won't work when an input Future has a @Nullable
858     * type. So why even make that error possible by giving callers the choice?
859     *
860     * On the other hand, the current signature is consistent with the similar allAsList method. And
861     * eventually this method may go away entirely in favor of an API like
862     * whenAllComplete().collectSuccesses(). That API would have a signature more like the current
863     * one.
864     */
865    return new ListFuture<V>(ImmutableList.copyOf(futures), false);
866  }
867
868  /**
869   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
870   * successful input futures. The list of results is in the same order as the input list, and if
871   * any of the provided futures fails or is canceled, its corresponding position will contain
872   * {@code null} (which is indistinguishable from the future having a successful value of {@code
873   * null}).
874   *
875   * <p>The list of results is in the same order as the input list.
876   *
877   * <p>This differs from {@link #allAsList(Iterable)} in that it's tolerant of failed futures for
878   * any of the items, representing them as {@code null} in the result list.
879   *
880   * <p>Canceling this future will attempt to cancel all the component futures.
881   *
882   * @param futures futures to combine
883   * @return a future that provides a list of the results of the component futures
884   * @since 10.0
885   */
886  public static <V extends @Nullable Object> ListenableFuture<List<@Nullable V>> successfulAsList(
887      Iterable<? extends ListenableFuture<? extends V>> futures) {
888    return new ListFuture<V>(ImmutableList.copyOf(futures), false);
889  }
890
891  /**
892   * Returns a list of delegate futures that correspond to the futures received in the order that
893   * they complete. Delegate futures return the same value or throw the same exception as the
894   * corresponding input future returns/throws.
895   *
896   * <p>"In the order that they complete" means, for practical purposes, about what you would
897   * expect, but there are some subtleties. First, we do guarantee that, if the output future at
898   * index n is done, the output future at index n-1 is also done. (But as usual with futures, some
899   * listeners for future n may complete before some for future n-1.) However, it is possible, if
900   * one input completes with result X and another later with result Y, for Y to come before X in
901   * the output future list. (Such races are impossible to solve without global synchronization of
902   * all future completions. And they should have little practical impact.)
903   *
904   * <p>Cancelling a delegate future propagates to input futures once all the delegates complete,
905   * either from cancellation or because an input future has completed. If N futures are passed in,
906   * and M delegates are cancelled, the remaining M input futures will be cancelled once N - M of
907   * the input futures complete. If all the delegates are cancelled, all the input futures will be
908   * too.
909   *
910   * @since 17.0
911   */
912  public static <T extends @Nullable Object> ImmutableList<ListenableFuture<T>> inCompletionOrder(
913      Iterable<? extends ListenableFuture<? extends T>> futures) {
914    ListenableFuture<? extends T>[] copy = gwtCompatibleToArray(futures);
915    final InCompletionOrderState<T> state = new InCompletionOrderState<>(copy);
916    ImmutableList.Builder<AbstractFuture<T>> delegatesBuilder =
917        ImmutableList.builderWithExpectedSize(copy.length);
918    for (int i = 0; i < copy.length; i++) {
919      delegatesBuilder.add(new InCompletionOrderFuture<T>(state));
920    }
921
922    final ImmutableList<AbstractFuture<T>> delegates = delegatesBuilder.build();
923    for (int i = 0; i < copy.length; i++) {
924      final int localI = i;
925      copy[i].addListener(() -> state.recordInputCompletion(delegates, localI), directExecutor());
926    }
927
928    @SuppressWarnings("unchecked")
929    ImmutableList<ListenableFuture<T>> delegatesCast = (ImmutableList) delegates;
930    return delegatesCast;
931  }
932
933  /** Can't use Iterables.toArray because it's not gwt compatible */
934  @SuppressWarnings("unchecked")
935  private static <T extends @Nullable Object> ListenableFuture<? extends T>[] gwtCompatibleToArray(
936      Iterable<? extends ListenableFuture<? extends T>> futures) {
937    final Collection<ListenableFuture<? extends T>> collection;
938    if (futures instanceof Collection) {
939      collection = (Collection<ListenableFuture<? extends T>>) futures;
940    } else {
941      collection = ImmutableList.copyOf(futures);
942    }
943    return (ListenableFuture<? extends T>[]) collection.toArray(new ListenableFuture<?>[0]);
944  }
945
946  // This can't be a TrustedFuture, because TrustedFuture has clever optimizations that
947  // mean cancel won't be called if this Future is passed into setFuture, and then
948  // cancelled.
949  private static final class InCompletionOrderFuture<T extends @Nullable Object>
950      extends AbstractFuture<T> {
951    @CheckForNull private InCompletionOrderState<T> state;
952
953    private InCompletionOrderFuture(InCompletionOrderState<T> state) {
954      this.state = state;
955    }
956
957    @Override
958    public boolean cancel(boolean interruptIfRunning) {
959      InCompletionOrderState<T> localState = state;
960      if (super.cancel(interruptIfRunning)) {
961        /*
962         * requireNonNull is generally safe: If cancel succeeded, then this Future was still
963         * pending, so its `state` field hasn't been nulled out yet.
964         *
965         * OK, it's technically possible for this to fail in the presence of unsafe publishing, as
966         * discussed in the comments in TimeoutFuture. TODO(cpovirk): Maybe check for null before
967         * calling recordOutputCancellation?
968         */
969        requireNonNull(localState).recordOutputCancellation(interruptIfRunning);
970        return true;
971      }
972      return false;
973    }
974
975    @Override
976    protected void afterDone() {
977      state = null;
978    }
979
980    @Override
981    @CheckForNull
982    protected String pendingToString() {
983      InCompletionOrderState<T> localState = state;
984      if (localState != null) {
985        // Don't print the actual array! We don't want inCompletionOrder(list).toString() to have
986        // quadratic output.
987        return "inputCount=["
988            + localState.inputFutures.length
989            + "], remaining=["
990            + localState.incompleteOutputCount.get()
991            + "]";
992      }
993      return null;
994    }
995  }
996
997  private static final class InCompletionOrderState<T extends @Nullable Object> {
998    // A happens-before edge between the writes of these fields and their reads exists, because
999    // in order to read these fields, the corresponding write to incompleteOutputCount must have
1000    // been read.
1001    private boolean wasCancelled = false;
1002    private boolean shouldInterrupt = true;
1003    private final AtomicInteger incompleteOutputCount;
1004    // We set the elements of the array to null as they complete.
1005    private final @Nullable ListenableFuture<? extends T>[] inputFutures;
1006    private volatile int delegateIndex = 0;
1007
1008    private InCompletionOrderState(ListenableFuture<? extends T>[] inputFutures) {
1009      this.inputFutures = inputFutures;
1010      incompleteOutputCount = new AtomicInteger(inputFutures.length);
1011    }
1012
1013    private void recordOutputCancellation(boolean interruptIfRunning) {
1014      wasCancelled = true;
1015      // If all the futures were cancelled with interruption, cancel the input futures
1016      // with interruption; otherwise cancel without
1017      if (!interruptIfRunning) {
1018        shouldInterrupt = false;
1019      }
1020      recordCompletion();
1021    }
1022
1023    private void recordInputCompletion(
1024        ImmutableList<AbstractFuture<T>> delegates, int inputFutureIndex) {
1025      /*
1026       * requireNonNull is safe because we accepted an Iterable of non-null Future instances, and we
1027       * don't overwrite an element in the array until after reading it.
1028       */
1029      ListenableFuture<? extends T> inputFuture = requireNonNull(inputFutures[inputFutureIndex]);
1030      // Null out our reference to this future, so it can be GCed
1031      inputFutures[inputFutureIndex] = null;
1032      for (int i = delegateIndex; i < delegates.size(); i++) {
1033        if (delegates.get(i).setFuture(inputFuture)) {
1034          recordCompletion();
1035          // this is technically unnecessary, but should speed up later accesses
1036          delegateIndex = i + 1;
1037          return;
1038        }
1039      }
1040      // If all the delegates were complete, no reason for the next listener to have to
1041      // go through the whole list. Avoids O(n^2) behavior when the entire output list is
1042      // cancelled.
1043      delegateIndex = delegates.size();
1044    }
1045
1046    private void recordCompletion() {
1047      if (incompleteOutputCount.decrementAndGet() == 0 && wasCancelled) {
1048        for (ListenableFuture<? extends T> toCancel : inputFutures) {
1049          if (toCancel != null) {
1050            toCancel.cancel(shouldInterrupt);
1051          }
1052        }
1053      }
1054    }
1055  }
1056
1057  /**
1058   * Registers separate success and failure callbacks to be run when the {@code Future}'s
1059   * computation is {@linkplain java.util.concurrent.Future#isDone() complete} or, if the
1060   * computation is already complete, immediately.
1061   *
1062   * <p>The callback is run on {@code executor}. There is no guaranteed ordering of execution of
1063   * callbacks, but any callback added through this method is guaranteed to be called once the
1064   * computation is complete.
1065   *
1066   * <p>Exceptions thrown by a {@code callback} will be propagated up to the executor. Any exception
1067   * thrown during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an
1068   * exception thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught
1069   * and logged.
1070   *
1071   * <p>Example:
1072   *
1073   * <pre>{@code
1074   * ListenableFuture<QueryResult> future = ...;
1075   * Executor e = ...
1076   * addCallback(future,
1077   *     new FutureCallback<QueryResult>() {
1078   *       public void onSuccess(QueryResult result) {
1079   *         storeInCache(result);
1080   *       }
1081   *       public void onFailure(Throwable t) {
1082   *         reportError(t);
1083   *       }
1084   *     }, e);
1085   * }</pre>
1086   *
1087   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
1088   * the warnings the {@link MoreExecutors#directExecutor} documentation.
1089   *
1090   * <p>For a more general interface to attach a completion listener to a {@code Future}, see {@link
1091   * ListenableFuture#addListener addListener}.
1092   *
1093   * @param future The future attach the callback to.
1094   * @param callback The callback to invoke when {@code future} is completed.
1095   * @param executor The executor to run {@code callback} when the future completes.
1096   * @since 10.0
1097   */
1098  public static <V extends @Nullable Object> void addCallback(
1099      final ListenableFuture<V> future,
1100      final FutureCallback<? super V> callback,
1101      Executor executor) {
1102    Preconditions.checkNotNull(callback);
1103    future.addListener(new CallbackListener<V>(future, callback), executor);
1104  }
1105
1106  /** See {@link #addCallback(ListenableFuture, FutureCallback, Executor)} for behavioral notes. */
1107  private static final class CallbackListener<V extends @Nullable Object> implements Runnable {
1108    final Future<V> future;
1109    final FutureCallback<? super V> callback;
1110
1111    CallbackListener(Future<V> future, FutureCallback<? super V> callback) {
1112      this.future = future;
1113      this.callback = callback;
1114    }
1115
1116    @Override
1117    public void run() {
1118      if (future instanceof InternalFutureFailureAccess) {
1119        Throwable failure =
1120            InternalFutures.tryInternalFastPathGetFailure((InternalFutureFailureAccess) future);
1121        if (failure != null) {
1122          callback.onFailure(failure);
1123          return;
1124        }
1125      }
1126      final V value;
1127      try {
1128        value = getDone(future);
1129      } catch (ExecutionException e) {
1130        callback.onFailure(e.getCause());
1131        return;
1132      } catch (Throwable e) {
1133        // Any Exception is either a RuntimeException or sneaky checked exception.
1134        callback.onFailure(e);
1135        return;
1136      }
1137      callback.onSuccess(value);
1138    }
1139
1140    @Override
1141    public String toString() {
1142      return MoreObjects.toStringHelper(this).addValue(callback).toString();
1143    }
1144  }
1145
1146  /**
1147   * Returns the result of the input {@code Future}, which must have already completed.
1148   *
1149   * <p>The benefits of this method are twofold. First, the name "getDone" suggests to readers that
1150   * the {@code Future} is already done. Second, if buggy code calls {@code getDone} on a {@code
1151   * Future} that is still pending, the program will throw instead of block. This can be important
1152   * for APIs like {@link #whenAllComplete whenAllComplete(...)}{@code .}{@link
1153   * FutureCombiner#call(Callable, Executor) call(...)}, where it is easy to use a new input from
1154   * the {@code call} implementation but forget to add it to the arguments of {@code
1155   * whenAllComplete}.
1156   *
1157   * <p>If you are looking for a method to determine whether a given {@code Future} is done, use the
1158   * instance method {@link Future#isDone()}.
1159   *
1160   * @throws ExecutionException if the {@code Future} failed with an exception
1161   * @throws CancellationException if the {@code Future} was cancelled
1162   * @throws IllegalStateException if the {@code Future} is not done
1163   * @since 20.0
1164   */
1165  @CanIgnoreReturnValue
1166  // TODO(cpovirk): Consider calling getDone() in our own code.
1167  @ParametricNullness
1168  public static <V extends @Nullable Object> V getDone(Future<V> future) throws ExecutionException {
1169    /*
1170     * We throw IllegalStateException, since the call could succeed later. Perhaps we "should" throw
1171     * IllegalArgumentException, since the call could succeed with a different argument. Those
1172     * exceptions' docs suggest that either is acceptable. Google's Java Practices page recommends
1173     * IllegalArgumentException here, in part to keep its recommendation simple: Static methods
1174     * should throw IllegalStateException only when they use static state.
1175     *
1176     * Why do we deviate here? The answer: We want for fluentFuture.getDone() to throw the same
1177     * exception as Futures.getDone(fluentFuture).
1178     */
1179    checkState(future.isDone(), "Future was expected to be done: %s", future);
1180    return getUninterruptibly(future);
1181  }
1182
1183  /**
1184   * Returns the result of {@link Future#get()}, converting most exceptions to a new instance of the
1185   * given checked exception type. This reduces boilerplate for a common use of {@code Future} in
1186   * which it is unnecessary to programmatically distinguish between exception types or to extract
1187   * other information from the exception instance.
1188   *
1189   * <p>Exceptions from {@code Future.get} are treated as follows:
1190   *
1191   * <ul>
1192   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1193   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1194   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1195   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1196   *       interrupt).
1197   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1198   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1199   *       exceptions).
1200   * </ul>
1201   *
1202   * <p>The overall principle is to continue to treat every checked exception as a checked
1203   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1204   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1205   * new stack trace matches that of the current thread.
1206   *
1207   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1208   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1209   * (preferring constructors with at least one {@code String}, then preferring constructors with at
1210   * least one {@code Throwable}) and calling the constructor via reflection. If the exception did
1211   * not already have a cause, one is set by calling {@link Throwable#initCause(Throwable)} on it.
1212   * If no such constructor exists, an {@code IllegalArgumentException} is thrown.
1213   *
1214   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1215   *     whose cause is not itself a checked exception
1216   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1217   *     {@code RuntimeException} as its cause
1218   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1219   *     Error} as its cause
1220   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1221   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1222   *     does not have a suitable constructor
1223   * @since 19.0 (in 10.0 as {@code get})
1224   */
1225  @CanIgnoreReturnValue
1226  @J2ktIncompatible
1227  @GwtIncompatible // reflection
1228  @ParametricNullness
1229  public static <V extends @Nullable Object, X extends Exception> V getChecked(
1230      Future<V> future, Class<X> exceptionClass) throws X {
1231    return FuturesGetChecked.getChecked(future, exceptionClass);
1232  }
1233
1234  /**
1235   * Returns the result of {@link Future#get(long, TimeUnit)}, converting most exceptions to a new
1236   * instance of the given checked exception type. This reduces boilerplate for a common use of
1237   * {@code Future} in which it is unnecessary to programmatically distinguish between exception
1238   * types or to extract other information from the exception instance.
1239   *
1240   * <p>Exceptions from {@code Future.get} are treated as follows:
1241   *
1242   * <ul>
1243   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1244   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1245   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1246   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1247   *       interrupt).
1248   *   <li>Any {@link TimeoutException} is wrapped in an {@code X}.
1249   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1250   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1251   *       exceptions).
1252   * </ul>
1253   *
1254   * <p>The overall principle is to continue to treat every checked exception as a checked
1255   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1256   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1257   * new stack trace matches that of the current thread.
1258   *
1259   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1260   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1261   * (preferring constructors with at least one {@code String}, then preferring constructors with at
1262   * least one {@code Throwable}) and calling the constructor via reflection. If the exception did
1263   * not already have a cause, one is set by calling {@link Throwable#initCause(Throwable)} on it.
1264   * If no such constructor exists, an {@code IllegalArgumentException} is thrown.
1265   *
1266   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1267   *     whose cause is not itself a checked exception
1268   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1269   *     {@code RuntimeException} as its cause
1270   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1271   *     Error} as its cause
1272   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1273   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1274   *     does not have a suitable constructor
1275   * @since 28.0
1276   */
1277  @CanIgnoreReturnValue
1278  @J2ktIncompatible
1279  @GwtIncompatible // reflection
1280  @ParametricNullness
1281  public static <V extends @Nullable Object, X extends Exception> V getChecked(
1282      Future<V> future, Class<X> exceptionClass, Duration timeout) throws X {
1283    return getChecked(future, exceptionClass, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
1284  }
1285
1286  /**
1287   * Returns the result of {@link Future#get(long, TimeUnit)}, converting most exceptions to a new
1288   * instance of the given checked exception type. This reduces boilerplate for a common use of
1289   * {@code Future} in which it is unnecessary to programmatically distinguish between exception
1290   * types or to extract other information from the exception instance.
1291   *
1292   * <p>Exceptions from {@code Future.get} are treated as follows:
1293   *
1294   * <ul>
1295   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1296   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1297   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1298   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1299   *       interrupt).
1300   *   <li>Any {@link TimeoutException} is wrapped in an {@code X}.
1301   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1302   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1303   *       exceptions).
1304   * </ul>
1305   *
1306   * <p>The overall principle is to continue to treat every checked exception as a checked
1307   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1308   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1309   * new stack trace matches that of the current thread.
1310   *
1311   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1312   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1313   * (preferring constructors with at least one {@code String}) and calling the constructor via
1314   * reflection. If the exception did not already have a cause, one is set by calling {@link
1315   * Throwable#initCause(Throwable)} on it. If no such constructor exists, an {@code
1316   * IllegalArgumentException} is thrown.
1317   *
1318   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1319   *     whose cause is not itself a checked exception
1320   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1321   *     {@code RuntimeException} as its cause
1322   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1323   *     Error} as its cause
1324   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1325   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1326   *     does not have a suitable constructor
1327   * @since 19.0 (in 10.0 as {@code get} and with different parameter order)
1328   */
1329  @CanIgnoreReturnValue
1330  @J2ktIncompatible
1331  @GwtIncompatible // reflection
1332  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
1333  @ParametricNullness
1334  public static <V extends @Nullable Object, X extends Exception> V getChecked(
1335      Future<V> future, Class<X> exceptionClass, long timeout, TimeUnit unit) throws X {
1336    return FuturesGetChecked.getChecked(future, exceptionClass, timeout, unit);
1337  }
1338
1339  /**
1340   * Returns the result of calling {@link Future#get()} uninterruptibly on a task known not to throw
1341   * a checked exception. This makes {@code Future} more suitable for lightweight, fast-running
1342   * tasks that, barring bugs in the code, will not fail. This gives it exception-handling behavior
1343   * similar to that of {@code ForkJoinTask.join}.
1344   *
1345   * <p>Exceptions from {@code Future.get} are treated as follows:
1346   *
1347   * <ul>
1348   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@link
1349   *       UncheckedExecutionException} (if the cause is an {@code Exception}) or {@link
1350   *       ExecutionError} (if the cause is an {@code Error}).
1351   *   <li>Any {@link InterruptedException} causes a retry of the {@code get} call. The interrupt is
1352   *       restored before {@code getUnchecked} returns.
1353   *   <li>Any {@link CancellationException} is propagated untouched. So is any other {@link
1354   *       RuntimeException} ({@code get} implementations are discouraged from throwing such
1355   *       exceptions).
1356   * </ul>
1357   *
1358   * <p>The overall principle is to eliminate all checked exceptions: to loop to avoid {@code
1359   * InterruptedException}, to pass through {@code CancellationException}, and to wrap any exception
1360   * from the underlying computation in an {@code UncheckedExecutionException} or {@code
1361   * ExecutionError}.
1362   *
1363   * <p>For an uninterruptible {@code get} that preserves other exceptions, see {@link
1364   * Uninterruptibles#getUninterruptibly(Future)}.
1365   *
1366   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with an
1367   *     {@code Exception} as its cause
1368   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1369   *     Error} as its cause
1370   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1371   * @since 10.0
1372   */
1373  @CanIgnoreReturnValue
1374  @ParametricNullness
1375  public static <V extends @Nullable Object> V getUnchecked(Future<V> future) {
1376    checkNotNull(future);
1377    try {
1378      return getUninterruptibly(future);
1379    } catch (ExecutionException e) {
1380      wrapAndThrowUnchecked(e.getCause());
1381      throw new AssertionError();
1382    }
1383  }
1384
1385  private static void wrapAndThrowUnchecked(Throwable cause) {
1386    if (cause instanceof Error) {
1387      throw new ExecutionError((Error) cause);
1388    }
1389    /*
1390     * It's an Exception. (Or it's a non-Error, non-Exception Throwable. From my survey of such
1391     * classes, I believe that most users intended to extend Exception, so we'll treat it like an
1392     * Exception.)
1393     */
1394    throw new UncheckedExecutionException(cause);
1395  }
1396
1397  /*
1398   * Arguably we don't need a timed getUnchecked because any operation slow enough to require a
1399   * timeout is heavyweight enough to throw a checked exception and therefore be inappropriate to
1400   * use with getUnchecked. Further, it's not clear that converting the checked TimeoutException to
1401   * a RuntimeException -- especially to an UncheckedExecutionException, since it wasn't thrown by
1402   * the computation -- makes sense, and if we don't convert it, the user still has to write a
1403   * try-catch block.
1404   *
1405   * If you think you would use this method, let us know. You might also look into the
1406   * Fork-Join framework: http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html
1407   */
1408}