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