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 (RuntimeException | Error t) {
549          throw new ExecutionException(t);
550        }
551      }
552    };
553  }
554
555  /**
556   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
557   * input futures, if all succeed.
558   *
559   * <p>The list of results is in the same order as the input list.
560   *
561   * <p>This differs from {@link #successfulAsList(ListenableFuture[])} in that it will return a
562   * failed future if any of the items fails.
563   *
564   * <p>Canceling this future will attempt to cancel all the component futures, and if any of the
565   * provided futures fails or is canceled, this one is, too.
566   *
567   * @param futures futures to combine
568   * @return a future that provides a list of the results of the component futures
569   * @since 10.0
570   */
571  @SafeVarargs
572  public static <V extends @Nullable Object> ListenableFuture<List<V>> allAsList(
573      ListenableFuture<? extends V>... futures) {
574    ListenableFuture<List<@Nullable V>> nullable =
575        new ListFuture<V>(ImmutableList.copyOf(futures), true);
576    // allAsList ensures that it fills the output list with V instances.
577    @SuppressWarnings("nullness")
578    ListenableFuture<List<V>> nonNull = nullable;
579    return nonNull;
580  }
581
582  /**
583   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
584   * input futures, if all succeed.
585   *
586   * <p>The list of results is in the same order as the input list.
587   *
588   * <p>This differs from {@link #successfulAsList(Iterable)} in that it will return a failed future
589   * if any of the items fails.
590   *
591   * <p>Canceling this future will attempt to cancel all the component futures, and if any of the
592   * provided futures fails or is canceled, this one is, too.
593   *
594   * @param futures futures to combine
595   * @return a future that provides a list of the results of the component futures
596   * @since 10.0
597   */
598  public static <V extends @Nullable Object> ListenableFuture<List<V>> allAsList(
599      Iterable<? extends ListenableFuture<? extends V>> futures) {
600    ListenableFuture<List<@Nullable V>> nullable =
601        new ListFuture<V>(ImmutableList.copyOf(futures), true);
602    // allAsList ensures that it fills the output list with V instances.
603    @SuppressWarnings("nullness")
604    ListenableFuture<List<V>> nonNull = nullable;
605    return nonNull;
606  }
607
608  /**
609   * Creates a {@link FutureCombiner} that processes the completed futures whether or not they're
610   * successful.
611   *
612   * <p>Any failures from the input futures will not be propagated to the returned future.
613   *
614   * @since 20.0
615   */
616  @SafeVarargs
617  public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
618      ListenableFuture<? extends V>... futures) {
619    return new FutureCombiner<V>(false, ImmutableList.copyOf(futures));
620  }
621
622  /**
623   * Creates a {@link FutureCombiner} that processes the completed futures whether or not they're
624   * successful.
625   *
626   * <p>Any failures from the input futures will not be propagated to the returned future.
627   *
628   * @since 20.0
629   */
630  public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
631      Iterable<? extends ListenableFuture<? extends V>> futures) {
632    return new FutureCombiner<V>(false, ImmutableList.copyOf(futures));
633  }
634
635  /**
636   * Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
637   *
638   * <p>If any input fails, the returned future fails immediately.
639   *
640   * @since 20.0
641   */
642  @SafeVarargs
643  public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
644      ListenableFuture<? extends V>... futures) {
645    return new FutureCombiner<V>(true, ImmutableList.copyOf(futures));
646  }
647
648  /**
649   * Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
650   *
651   * <p>If any input fails, the returned future fails immediately.
652   *
653   * @since 20.0
654   */
655  public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
656      Iterable<? extends ListenableFuture<? extends V>> futures) {
657    return new FutureCombiner<V>(true, ImmutableList.copyOf(futures));
658  }
659
660  /**
661   * A helper to create a new {@code ListenableFuture} whose result is generated from a combination
662   * of input futures.
663   *
664   * <p>See {@link #whenAllComplete} and {@link #whenAllSucceed} for how to instantiate this class.
665   *
666   * <p>Example:
667   *
668   * <pre>{@code
669   * final ListenableFuture<Instant> loginDateFuture =
670   *     loginService.findLastLoginDate(username);
671   * final ListenableFuture<List<String>> recentCommandsFuture =
672   *     recentCommandsService.findRecentCommands(username);
673   * ListenableFuture<UsageHistory> usageFuture =
674   *     Futures.whenAllSucceed(loginDateFuture, recentCommandsFuture)
675   *         .call(
676   *             () ->
677   *                 new UsageHistory(
678   *                     username,
679   *                     Futures.getDone(loginDateFuture),
680   *                     Futures.getDone(recentCommandsFuture)),
681   *             executor);
682   * }</pre>
683   *
684   * @since 20.0
685   */
686  @GwtCompatible
687  public static final class FutureCombiner<V extends @Nullable Object> {
688    private final boolean allMustSucceed;
689    private final ImmutableList<ListenableFuture<? extends V>> futures;
690
691    private FutureCombiner(
692        boolean allMustSucceed, ImmutableList<ListenableFuture<? extends V>> futures) {
693      this.allMustSucceed = allMustSucceed;
694      this.futures = futures;
695    }
696
697    /**
698     * Creates the {@link ListenableFuture} which will return the result of calling {@link
699     * AsyncCallable#call} in {@code combiner} when all futures complete, using the specified {@code
700     * executor}.
701     *
702     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
703     * cancelled.
704     *
705     * <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code
706     * ExecutionException} will be extracted and returned as the cause of the new {@code
707     * ExecutionException} that gets thrown by the returned combined future.
708     *
709     * <p>Canceling this future will attempt to cancel all the component futures.
710     *
711     * @return a future whose result is based on {@code combiner} (or based on the input futures
712     *     passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
713     *     FutureCombiner}). Even if you don't care about the value of the future, you should
714     *     typically check whether it failed: See <a
715     *     href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
716     */
717    public <C extends @Nullable Object> ListenableFuture<C> callAsync(
718        AsyncCallable<C> combiner, Executor executor) {
719      return new CombinedFuture<C>(futures, allMustSucceed, executor, combiner);
720    }
721
722    /**
723     * Creates the {@link ListenableFuture} which will return the result of calling {@link
724     * Callable#call} in {@code combiner} when all futures complete, using the specified {@code
725     * executor}.
726     *
727     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
728     * cancelled.
729     *
730     * <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code
731     * ExecutionException} will be extracted and returned as the cause of the new {@code
732     * ExecutionException} that gets thrown by the returned combined future.
733     *
734     * <p>Canceling this future will attempt to cancel all the component futures.
735     *
736     * @return a future whose result is based on {@code combiner} (or based on the input futures
737     *     passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
738     *     FutureCombiner}). Even if you don't care about the value of the future, you should
739     *     typically check whether it failed: See <a
740     *     href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
741     */
742    public <C extends @Nullable Object> ListenableFuture<C> call(
743        Callable<C> combiner, Executor executor) {
744      return new CombinedFuture<C>(futures, allMustSucceed, executor, combiner);
745    }
746
747    /**
748     * Creates the {@link ListenableFuture} which will return the result of running {@code combiner}
749     * when all Futures complete. {@code combiner} will run using {@code executor}.
750     *
751     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
752     * cancelled.
753     *
754     * <p>Canceling this Future will attempt to cancel all the component futures.
755     *
756     * @since 23.6
757     * @return a future whose result is based on {@code combiner} (or based on the input futures
758     *     passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
759     *     FutureCombiner}). Even though the future never produces a value other than {@code null},
760     *     you should typically check whether it failed: See <a
761     *     href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
762     */
763    public ListenableFuture<?> run(final Runnable combiner, Executor executor) {
764      return call(
765          new Callable<@Nullable Void>() {
766            @Override
767            @CheckForNull
768            public Void call() throws Exception {
769              combiner.run();
770              return null;
771            }
772          },
773          executor);
774    }
775  }
776
777  /**
778   * Returns a {@code ListenableFuture} whose result is set from the supplied future when it
779   * completes. Cancelling the supplied future will also cancel the returned future, but cancelling
780   * the returned future will have no effect on the supplied future.
781   *
782   * @since 15.0
783   */
784  public static <V extends @Nullable Object> ListenableFuture<V> nonCancellationPropagating(
785      ListenableFuture<V> future) {
786    if (future.isDone()) {
787      return future;
788    }
789    NonCancellationPropagatingFuture<V> output = new NonCancellationPropagatingFuture<>(future);
790    future.addListener(output, directExecutor());
791    return output;
792  }
793
794  /** A wrapped future that does not propagate cancellation to its delegate. */
795  private static final class NonCancellationPropagatingFuture<V extends @Nullable Object>
796      extends AbstractFuture.TrustedFuture<V> implements Runnable {
797    @CheckForNull private ListenableFuture<V> delegate;
798
799    NonCancellationPropagatingFuture(final ListenableFuture<V> delegate) {
800      this.delegate = delegate;
801    }
802
803    @Override
804    public void run() {
805      // This prevents cancellation from propagating because we don't call setFuture(delegate) until
806      // delegate is already done, so calling cancel() on this future won't affect it.
807      ListenableFuture<V> localDelegate = delegate;
808      if (localDelegate != null) {
809        setFuture(localDelegate);
810      }
811    }
812
813    @Override
814    @CheckForNull
815    protected String pendingToString() {
816      ListenableFuture<V> localDelegate = delegate;
817      if (localDelegate != null) {
818        return "delegate=[" + localDelegate + "]";
819      }
820      return null;
821    }
822
823    @Override
824    protected void afterDone() {
825      delegate = null;
826    }
827  }
828
829  /**
830   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
831   * successful input futures. The list of results is in the same order as the input list, and if
832   * any of the provided futures fails or is canceled, its corresponding position will contain
833   * {@code null} (which is indistinguishable from the future having a successful value of {@code
834   * null}).
835   *
836   * <p>The list of results is in the same order as the input list.
837   *
838   * <p>This differs from {@link #allAsList(ListenableFuture[])} in that it's tolerant of failed
839   * futures for any of the items, representing them as {@code null} in the result list.
840   *
841   * <p>Canceling this future will attempt to cancel all the component futures.
842   *
843   * @param futures futures to combine
844   * @return a future that provides a list of the results of the component futures
845   * @since 10.0
846   */
847  @SafeVarargs
848  public static <V extends @Nullable Object> ListenableFuture<List<@Nullable V>> successfulAsList(
849      ListenableFuture<? extends V>... futures) {
850    /*
851     * Another way to express this signature would be to bound <V> by @NonNull and accept
852     * LF<? extends @Nullable V>. That might be better: There's currently no difference between the
853     * outputs users get when calling this with <Foo> and calling it with <@Nullable Foo>. The only
854     * difference is that calling it with <Foo> won't work when an input Future has a @Nullable
855     * type. So why even make that error possible by giving callers the choice?
856     *
857     * On the other hand, the current signature is consistent with the similar allAsList method. And
858     * eventually this method may go away entirely in favor of an API like
859     * whenAllComplete().collectSuccesses(). That API would have a signature more like the current
860     * one.
861     */
862    return new ListFuture<V>(ImmutableList.copyOf(futures), false);
863  }
864
865  /**
866   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
867   * successful input futures. The list of results is in the same order as the input list, and if
868   * any of the provided futures fails or is canceled, its corresponding position will contain
869   * {@code null} (which is indistinguishable from the future having a successful value of {@code
870   * null}).
871   *
872   * <p>The list of results is in the same order as the input list.
873   *
874   * <p>This differs from {@link #allAsList(Iterable)} in that it's tolerant of failed futures for
875   * any of the items, representing them as {@code null} in the result list.
876   *
877   * <p>Canceling this future will attempt to cancel all the component futures.
878   *
879   * @param futures futures to combine
880   * @return a future that provides a list of the results of the component futures
881   * @since 10.0
882   */
883  public static <V extends @Nullable Object> ListenableFuture<List<@Nullable V>> successfulAsList(
884      Iterable<? extends ListenableFuture<? extends V>> futures) {
885    return new ListFuture<V>(ImmutableList.copyOf(futures), false);
886  }
887
888  /**
889   * Returns a list of delegate futures that correspond to the futures received in the order that
890   * they complete. Delegate futures return the same value or throw the same exception as the
891   * corresponding input future returns/throws.
892   *
893   * <p>"In the order that they complete" means, for practical purposes, about what you would
894   * expect, but there are some subtleties. First, we do guarantee that, if the output future at
895   * index n is done, the output future at index n-1 is also done. (But as usual with futures, some
896   * listeners for future n may complete before some for future n-1.) However, it is possible, if
897   * one input completes with result X and another later with result Y, for Y to come before X in
898   * the output future list. (Such races are impossible to solve without global synchronization of
899   * all future completions. And they should have little practical impact.)
900   *
901   * <p>Cancelling a delegate future propagates to input futures once all the delegates complete,
902   * either from cancellation or because an input future has completed. If N futures are passed in,
903   * and M delegates are cancelled, the remaining M input futures will be cancelled once N - M of
904   * the input futures complete. If all the delegates are cancelled, all the input futures will be
905   * too.
906   *
907   * @since 17.0
908   */
909  public static <T extends @Nullable Object> ImmutableList<ListenableFuture<T>> inCompletionOrder(
910      Iterable<? extends ListenableFuture<? extends T>> futures) {
911    ListenableFuture<? extends T>[] copy = gwtCompatibleToArray(futures);
912    final InCompletionOrderState<T> state = new InCompletionOrderState<>(copy);
913    ImmutableList.Builder<AbstractFuture<T>> delegatesBuilder =
914        ImmutableList.builderWithExpectedSize(copy.length);
915    for (int i = 0; i < copy.length; i++) {
916      delegatesBuilder.add(new InCompletionOrderFuture<T>(state));
917    }
918
919    final ImmutableList<AbstractFuture<T>> delegates = delegatesBuilder.build();
920    for (int i = 0; i < copy.length; i++) {
921      final int localI = i;
922      copy[i].addListener(() -> state.recordInputCompletion(delegates, localI), directExecutor());
923    }
924
925    @SuppressWarnings("unchecked")
926    ImmutableList<ListenableFuture<T>> delegatesCast = (ImmutableList) delegates;
927    return delegatesCast;
928  }
929
930  /** Can't use Iterables.toArray because it's not gwt compatible */
931  @SuppressWarnings("unchecked")
932  private static <T extends @Nullable Object> ListenableFuture<? extends T>[] gwtCompatibleToArray(
933      Iterable<? extends ListenableFuture<? extends T>> futures) {
934    final Collection<ListenableFuture<? extends T>> collection;
935    if (futures instanceof Collection) {
936      collection = (Collection<ListenableFuture<? extends T>>) futures;
937    } else {
938      collection = ImmutableList.copyOf(futures);
939    }
940    return (ListenableFuture<? extends T>[]) collection.toArray(new ListenableFuture<?>[0]);
941  }
942
943  // This can't be a TrustedFuture, because TrustedFuture has clever optimizations that
944  // mean cancel won't be called if this Future is passed into setFuture, and then
945  // cancelled.
946  private static final class InCompletionOrderFuture<T extends @Nullable Object>
947      extends AbstractFuture<T> {
948    @CheckForNull private InCompletionOrderState<T> state;
949
950    private InCompletionOrderFuture(InCompletionOrderState<T> state) {
951      this.state = state;
952    }
953
954    @Override
955    public boolean cancel(boolean interruptIfRunning) {
956      InCompletionOrderState<T> localState = state;
957      if (super.cancel(interruptIfRunning)) {
958        /*
959         * requireNonNull is generally safe: If cancel succeeded, then this Future was still
960         * pending, so its `state` field hasn't been nulled out yet.
961         *
962         * OK, it's technically possible for this to fail in the presence of unsafe publishing, as
963         * discussed in the comments in TimeoutFuture. TODO(cpovirk): Maybe check for null before
964         * calling recordOutputCancellation?
965         */
966        requireNonNull(localState).recordOutputCancellation(interruptIfRunning);
967        return true;
968      }
969      return false;
970    }
971
972    @Override
973    protected void afterDone() {
974      state = null;
975    }
976
977    @Override
978    @CheckForNull
979    protected String pendingToString() {
980      InCompletionOrderState<T> localState = state;
981      if (localState != null) {
982        // Don't print the actual array! We don't want inCompletionOrder(list).toString() to have
983        // quadratic output.
984        return "inputCount=["
985            + localState.inputFutures.length
986            + "], remaining=["
987            + localState.incompleteOutputCount.get()
988            + "]";
989      }
990      return null;
991    }
992  }
993
994  private static final class InCompletionOrderState<T extends @Nullable Object> {
995    // A happens-before edge between the writes of these fields and their reads exists, because
996    // in order to read these fields, the corresponding write to incompleteOutputCount must have
997    // been read.
998    private boolean wasCancelled = false;
999    private boolean shouldInterrupt = true;
1000    private final AtomicInteger incompleteOutputCount;
1001    // We set the elements of the array to null as they complete.
1002    private final @Nullable ListenableFuture<? extends T>[] inputFutures;
1003    private volatile int delegateIndex = 0;
1004
1005    private InCompletionOrderState(ListenableFuture<? extends T>[] inputFutures) {
1006      this.inputFutures = inputFutures;
1007      incompleteOutputCount = new AtomicInteger(inputFutures.length);
1008    }
1009
1010    private void recordOutputCancellation(boolean interruptIfRunning) {
1011      wasCancelled = true;
1012      // If all the futures were cancelled with interruption, cancel the input futures
1013      // with interruption; otherwise cancel without
1014      if (!interruptIfRunning) {
1015        shouldInterrupt = false;
1016      }
1017      recordCompletion();
1018    }
1019
1020    private void recordInputCompletion(
1021        ImmutableList<AbstractFuture<T>> delegates, int inputFutureIndex) {
1022      /*
1023       * requireNonNull is safe because we accepted an Iterable of non-null Future instances, and we
1024       * don't overwrite an element in the array until after reading it.
1025       */
1026      ListenableFuture<? extends T> inputFuture = requireNonNull(inputFutures[inputFutureIndex]);
1027      // Null out our reference to this future, so it can be GCed
1028      inputFutures[inputFutureIndex] = null;
1029      for (int i = delegateIndex; i < delegates.size(); i++) {
1030        if (delegates.get(i).setFuture(inputFuture)) {
1031          recordCompletion();
1032          // this is technically unnecessary, but should speed up later accesses
1033          delegateIndex = i + 1;
1034          return;
1035        }
1036      }
1037      // If all the delegates were complete, no reason for the next listener to have to
1038      // go through the whole list. Avoids O(n^2) behavior when the entire output list is
1039      // cancelled.
1040      delegateIndex = delegates.size();
1041    }
1042
1043    private void recordCompletion() {
1044      if (incompleteOutputCount.decrementAndGet() == 0 && wasCancelled) {
1045        for (ListenableFuture<? extends T> toCancel : inputFutures) {
1046          if (toCancel != null) {
1047            toCancel.cancel(shouldInterrupt);
1048          }
1049        }
1050      }
1051    }
1052  }
1053
1054  /**
1055   * Registers separate success and failure callbacks to be run when the {@code Future}'s
1056   * computation is {@linkplain java.util.concurrent.Future#isDone() complete} or, if the
1057   * computation is already complete, immediately.
1058   *
1059   * <p>The callback is run on {@code executor}. There is no guaranteed ordering of execution of
1060   * callbacks, but any callback added through this method is guaranteed to be called once the
1061   * computation is complete.
1062   *
1063   * <p>Exceptions thrown by a {@code callback} will be propagated up to the executor. Any exception
1064   * thrown during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an
1065   * exception thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught
1066   * and logged.
1067   *
1068   * <p>Example:
1069   *
1070   * <pre>{@code
1071   * ListenableFuture<QueryResult> future = ...;
1072   * Executor e = ...
1073   * addCallback(future,
1074   *     new FutureCallback<QueryResult>() {
1075   *       public void onSuccess(QueryResult result) {
1076   *         storeInCache(result);
1077   *       }
1078   *       public void onFailure(Throwable t) {
1079   *         reportError(t);
1080   *       }
1081   *     }, e);
1082   * }</pre>
1083   *
1084   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
1085   * the warnings the {@link MoreExecutors#directExecutor} documentation.
1086   *
1087   * <p>For a more general interface to attach a completion listener to a {@code Future}, see {@link
1088   * ListenableFuture#addListener addListener}.
1089   *
1090   * @param future The future attach the callback to.
1091   * @param callback The callback to invoke when {@code future} is completed.
1092   * @param executor The executor to run {@code callback} when the future completes.
1093   * @since 10.0
1094   */
1095  public static <V extends @Nullable Object> void addCallback(
1096      final ListenableFuture<V> future,
1097      final FutureCallback<? super V> callback,
1098      Executor executor) {
1099    Preconditions.checkNotNull(callback);
1100    future.addListener(new CallbackListener<V>(future, callback), executor);
1101  }
1102
1103  /** See {@link #addCallback(ListenableFuture, FutureCallback, Executor)} for behavioral notes. */
1104  private static final class CallbackListener<V extends @Nullable Object> implements Runnable {
1105    final Future<V> future;
1106    final FutureCallback<? super V> callback;
1107
1108    CallbackListener(Future<V> future, FutureCallback<? super V> callback) {
1109      this.future = future;
1110      this.callback = callback;
1111    }
1112
1113    @Override
1114    public void run() {
1115      if (future instanceof InternalFutureFailureAccess) {
1116        Throwable failure =
1117            InternalFutures.tryInternalFastPathGetFailure((InternalFutureFailureAccess) future);
1118        if (failure != null) {
1119          callback.onFailure(failure);
1120          return;
1121        }
1122      }
1123      final V value;
1124      try {
1125        value = getDone(future);
1126      } catch (ExecutionException e) {
1127        callback.onFailure(e.getCause());
1128        return;
1129      } catch (RuntimeException | Error e) {
1130        callback.onFailure(e);
1131        return;
1132      }
1133      callback.onSuccess(value);
1134    }
1135
1136    @Override
1137    public String toString() {
1138      return MoreObjects.toStringHelper(this).addValue(callback).toString();
1139    }
1140  }
1141
1142  /**
1143   * Returns the result of the input {@code Future}, which must have already completed.
1144   *
1145   * <p>The benefits of this method are twofold. First, the name "getDone" suggests to readers that
1146   * the {@code Future} is already done. Second, if buggy code calls {@code getDone} on a {@code
1147   * Future} that is still pending, the program will throw instead of block. This can be important
1148   * for APIs like {@link #whenAllComplete whenAllComplete(...)}{@code .}{@link
1149   * FutureCombiner#call(Callable, Executor) call(...)}, where it is easy to use a new input from
1150   * the {@code call} implementation but forget to add it to the arguments of {@code
1151   * whenAllComplete}.
1152   *
1153   * <p>If you are looking for a method to determine whether a given {@code Future} is done, use the
1154   * instance method {@link Future#isDone()}.
1155   *
1156   * @throws ExecutionException if the {@code Future} failed with an exception
1157   * @throws CancellationException if the {@code Future} was cancelled
1158   * @throws IllegalStateException if the {@code Future} is not done
1159   * @since 20.0
1160   */
1161  @CanIgnoreReturnValue
1162  // TODO(cpovirk): Consider calling getDone() in our own code.
1163  @ParametricNullness
1164  public static <V extends @Nullable Object> V getDone(Future<V> future) throws ExecutionException {
1165    /*
1166     * We throw IllegalStateException, since the call could succeed later. Perhaps we "should" throw
1167     * IllegalArgumentException, since the call could succeed with a different argument. Those
1168     * exceptions' docs suggest that either is acceptable. Google's Java Practices page recommends
1169     * IllegalArgumentException here, in part to keep its recommendation simple: Static methods
1170     * should throw IllegalStateException only when they use static state.
1171     *
1172     * Why do we deviate here? The answer: We want for fluentFuture.getDone() to throw the same
1173     * exception as Futures.getDone(fluentFuture).
1174     */
1175    checkState(future.isDone(), "Future was expected to be done: %s", future);
1176    return getUninterruptibly(future);
1177  }
1178
1179  /**
1180   * Returns the result of {@link Future#get()}, converting most exceptions to a new instance of the
1181   * given checked exception type. This reduces boilerplate for a common use of {@code Future} in
1182   * which it is unnecessary to programmatically distinguish between exception types or to extract
1183   * other information from the exception instance.
1184   *
1185   * <p>Exceptions from {@code Future.get} are treated as follows:
1186   *
1187   * <ul>
1188   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1189   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1190   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1191   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1192   *       interrupt).
1193   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1194   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1195   *       exceptions).
1196   * </ul>
1197   *
1198   * <p>The overall principle is to continue to treat every checked exception as a checked
1199   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1200   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1201   * new stack trace matches that of the current thread.
1202   *
1203   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1204   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1205   * (preferring constructors with at least one {@code String}, then preferring constructors with at
1206   * least one {@code Throwable}) and calling the constructor via reflection. If the exception did
1207   * not already have a cause, one is set by calling {@link Throwable#initCause(Throwable)} on it.
1208   * If no such constructor exists, an {@code IllegalArgumentException} is thrown.
1209   *
1210   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1211   *     whose cause is not itself a checked exception
1212   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1213   *     {@code RuntimeException} as its cause
1214   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1215   *     Error} as its cause
1216   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1217   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1218   *     does not have a suitable constructor
1219   * @since 19.0 (in 10.0 as {@code get})
1220   */
1221  @CanIgnoreReturnValue
1222  @J2ktIncompatible
1223  @GwtIncompatible // reflection
1224  @ParametricNullness
1225  public static <V extends @Nullable Object, X extends Exception> V getChecked(
1226      Future<V> future, Class<X> exceptionClass) throws X {
1227    return FuturesGetChecked.getChecked(future, exceptionClass);
1228  }
1229
1230  /**
1231   * Returns the result of {@link Future#get(long, TimeUnit)}, converting most exceptions to a new
1232   * instance of the given checked exception type. This reduces boilerplate for a common use of
1233   * {@code Future} in which it is unnecessary to programmatically distinguish between exception
1234   * types or to extract other information from the exception instance.
1235   *
1236   * <p>Exceptions from {@code Future.get} are treated as follows:
1237   *
1238   * <ul>
1239   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1240   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1241   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1242   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1243   *       interrupt).
1244   *   <li>Any {@link TimeoutException} is wrapped in an {@code X}.
1245   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1246   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1247   *       exceptions).
1248   * </ul>
1249   *
1250   * <p>The overall principle is to continue to treat every checked exception as a checked
1251   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1252   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1253   * new stack trace matches that of the current thread.
1254   *
1255   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1256   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1257   * (preferring constructors with at least one {@code String}, then preferring constructors with at
1258   * least one {@code Throwable}) and calling the constructor via reflection. If the exception did
1259   * not already have a cause, one is set by calling {@link Throwable#initCause(Throwable)} on it.
1260   * If no such constructor exists, an {@code IllegalArgumentException} is thrown.
1261   *
1262   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1263   *     whose cause is not itself a checked exception
1264   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1265   *     {@code RuntimeException} as its cause
1266   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1267   *     Error} as its cause
1268   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1269   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1270   *     does not have a suitable constructor
1271   * @since 28.0
1272   */
1273  @CanIgnoreReturnValue
1274  @J2ktIncompatible
1275  @GwtIncompatible // reflection
1276  @ParametricNullness
1277  public static <V extends @Nullable Object, X extends Exception> V getChecked(
1278      Future<V> future, Class<X> exceptionClass, Duration timeout) throws X {
1279    return getChecked(future, exceptionClass, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
1280  }
1281
1282  /**
1283   * Returns the result of {@link Future#get(long, TimeUnit)}, converting most exceptions to a new
1284   * instance of the given checked exception type. This reduces boilerplate for a common use of
1285   * {@code Future} in which it is unnecessary to programmatically distinguish between exception
1286   * types or to extract other information from the exception instance.
1287   *
1288   * <p>Exceptions from {@code Future.get} are treated as follows:
1289   *
1290   * <ul>
1291   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1292   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1293   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1294   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1295   *       interrupt).
1296   *   <li>Any {@link TimeoutException} is wrapped in an {@code X}.
1297   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1298   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1299   *       exceptions).
1300   * </ul>
1301   *
1302   * <p>The overall principle is to continue to treat every checked exception as a checked
1303   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1304   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1305   * new stack trace matches that of the current thread.
1306   *
1307   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1308   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1309   * (preferring constructors with at least one {@code String}) and calling the constructor via
1310   * reflection. If the exception did not already have a cause, one is set by calling {@link
1311   * Throwable#initCause(Throwable)} on it. If no such constructor exists, an {@code
1312   * IllegalArgumentException} is thrown.
1313   *
1314   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1315   *     whose cause is not itself a checked exception
1316   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1317   *     {@code RuntimeException} as its cause
1318   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1319   *     Error} as its cause
1320   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1321   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1322   *     does not have a suitable constructor
1323   * @since 19.0 (in 10.0 as {@code get} and with different parameter order)
1324   */
1325  @CanIgnoreReturnValue
1326  @J2ktIncompatible
1327  @GwtIncompatible // reflection
1328  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
1329  @ParametricNullness
1330  public static <V extends @Nullable Object, X extends Exception> V getChecked(
1331      Future<V> future, Class<X> exceptionClass, long timeout, TimeUnit unit) throws X {
1332    return FuturesGetChecked.getChecked(future, exceptionClass, timeout, unit);
1333  }
1334
1335  /**
1336   * Returns the result of calling {@link Future#get()} uninterruptibly on a task known not to throw
1337   * a checked exception. This makes {@code Future} more suitable for lightweight, fast-running
1338   * tasks that, barring bugs in the code, will not fail. This gives it exception-handling behavior
1339   * similar to that of {@code ForkJoinTask.join}.
1340   *
1341   * <p>Exceptions from {@code Future.get} are treated as follows:
1342   *
1343   * <ul>
1344   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@link
1345   *       UncheckedExecutionException} (if the cause is an {@code Exception}) or {@link
1346   *       ExecutionError} (if the cause is an {@code Error}).
1347   *   <li>Any {@link InterruptedException} causes a retry of the {@code get} call. The interrupt is
1348   *       restored before {@code getUnchecked} returns.
1349   *   <li>Any {@link CancellationException} is propagated untouched. So is any other {@link
1350   *       RuntimeException} ({@code get} implementations are discouraged from throwing such
1351   *       exceptions).
1352   * </ul>
1353   *
1354   * <p>The overall principle is to eliminate all checked exceptions: to loop to avoid {@code
1355   * InterruptedException}, to pass through {@code CancellationException}, and to wrap any exception
1356   * from the underlying computation in an {@code UncheckedExecutionException} or {@code
1357   * ExecutionError}.
1358   *
1359   * <p>For an uninterruptible {@code get} that preserves other exceptions, see {@link
1360   * Uninterruptibles#getUninterruptibly(Future)}.
1361   *
1362   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with an
1363   *     {@code Exception} as its cause
1364   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1365   *     Error} as its cause
1366   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1367   * @since 10.0
1368   */
1369  @CanIgnoreReturnValue
1370  @ParametricNullness
1371  public static <V extends @Nullable Object> V getUnchecked(Future<V> future) {
1372    checkNotNull(future);
1373    try {
1374      return getUninterruptibly(future);
1375    } catch (ExecutionException e) {
1376      wrapAndThrowUnchecked(e.getCause());
1377      throw new AssertionError();
1378    }
1379  }
1380
1381  private static void wrapAndThrowUnchecked(Throwable cause) {
1382    if (cause instanceof Error) {
1383      throw new ExecutionError((Error) cause);
1384    }
1385    /*
1386     * It's an Exception. (Or it's a non-Error, non-Exception Throwable. From my survey of such
1387     * classes, I believe that most users intended to extend Exception, so we'll treat it like an
1388     * Exception.)
1389     */
1390    throw new UncheckedExecutionException(cause);
1391  }
1392
1393  /*
1394   * Arguably we don't need a timed getUnchecked because any operation slow enough to require a
1395   * timeout is heavyweight enough to throw a checked exception and therefore be inappropriate to
1396   * use with getUnchecked. Further, it's not clear that converting the checked TimeoutException to
1397   * a RuntimeException -- especially to an UncheckedExecutionException, since it wasn't thrown by
1398   * the computation -- makes sense, and if we don't convert it, the user still has to write a
1399   * try-catch block.
1400   *
1401   * If you think you would use this method, let us know. You might also look into the
1402   * Fork-Join framework: http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html
1403   */
1404}