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