001/*
002 * Copyright (C) 2006 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.util.concurrent;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018import static com.google.common.base.Preconditions.checkState;
019import static com.google.common.util.concurrent.Internal.toNanosSaturated;
020import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
021import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
022import static java.util.Objects.requireNonNull;
023
024import com.google.common.annotations.GwtCompatible;
025import com.google.common.annotations.GwtIncompatible;
026import com.google.common.annotations.J2ktIncompatible;
027import com.google.common.base.Function;
028import com.google.common.base.MoreObjects;
029import com.google.common.base.Preconditions;
030import com.google.common.collect.ImmutableList;
031import com.google.common.util.concurrent.CollectionFuture.ListFuture;
032import com.google.common.util.concurrent.ImmediateFuture.ImmediateCancelledFuture;
033import com.google.common.util.concurrent.ImmediateFuture.ImmediateFailedFuture;
034import com.google.common.util.concurrent.internal.InternalFutureFailureAccess;
035import com.google.common.util.concurrent.internal.InternalFutures;
036import com.google.errorprone.annotations.CanIgnoreReturnValue;
037import com.google.errorprone.annotations.concurrent.LazyInit;
038import com.google.j2objc.annotations.RetainedLocalRef;
039import java.time.Duration;
040import java.util.Collection;
041import java.util.List;
042import java.util.concurrent.Callable;
043import java.util.concurrent.CancellationException;
044import java.util.concurrent.ExecutionException;
045import java.util.concurrent.Executor;
046import java.util.concurrent.Future;
047import java.util.concurrent.RejectedExecutionException;
048import java.util.concurrent.ScheduledExecutorService;
049import java.util.concurrent.TimeUnit;
050import java.util.concurrent.TimeoutException;
051import java.util.concurrent.atomic.AtomicInteger;
052import org.checkerframework.checker.nullness.qual.Nullable;
053
054/**
055 * Static utility methods pertaining to the {@link Future} interface.
056 *
057 * <p>Many of these methods use the {@link ListenableFuture} API; consult the Guava User Guide
058 * article on <a href="https://github.com/google/guava/wiki/ListenableFutureExplained">{@code
059 * ListenableFuture}</a>.
060 *
061 * <p>The main purpose of {@code ListenableFuture} is to help you chain together a graph of
062 * asynchronous operations. You can chain them together manually with calls to methods like {@link
063 * Futures#transform(ListenableFuture, Function, Executor) Futures.transform}, but you will often
064 * find it easier to use a framework. Frameworks automate the process, often adding features like
065 * monitoring, debugging, and cancellation. Examples of frameworks include:
066 *
067 * <ul>
068 *   <li><a href="https://dagger.dev/producers.html">Dagger Producers</a>
069 * </ul>
070 *
071 * <p>If you do chain your operations manually, you may want to use {@link FluentFuture}.
072 *
073 * @author Kevin Bourrillion
074 * @author Nishant Thakkar
075 * @author Sven Mawson
076 * @since 1.0
077 */
078@GwtCompatible(emulated = true)
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<>(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  @SuppressWarnings("unchecked") // ImmediateCancelledFuture can work with any type
175  public static <V extends @Nullable Object> ListenableFuture<V> immediateCancelledFuture() {
176    ListenableFuture<Object> instance = ImmediateCancelledFuture.INSTANCE;
177    if (instance != null) {
178      return (ListenableFuture<V>) instance;
179    }
180    return new ImmediateCancelledFuture<>();
181  }
182
183  /**
184   * Executes {@code callable} on the specified {@code executor}, returning a {@code Future}.
185   *
186   * @throws RejectedExecutionException if the task cannot be scheduled for execution
187   * @since 28.2
188   */
189  public static <O extends @Nullable Object> ListenableFuture<O> submit(
190      Callable<O> callable, Executor executor) {
191    TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
192    executor.execute(task);
193    return task;
194  }
195
196  /**
197   * Executes {@code runnable} on the specified {@code executor}, returning a {@code Future} that
198   * will complete after execution.
199   *
200   * @throws RejectedExecutionException if the task cannot be scheduled for execution
201   * @since 28.2
202   */
203  public static ListenableFuture<@Nullable Void> submit(Runnable runnable, Executor executor) {
204    TrustedListenableFutureTask<@Nullable Void> task =
205        TrustedListenableFutureTask.create(runnable, null);
206    executor.execute(task);
207    return task;
208  }
209
210  /**
211   * Executes {@code callable} on the specified {@code executor}, returning a {@code Future}.
212   *
213   * @throws RejectedExecutionException if the task cannot be scheduled for execution
214   * @since 23.0
215   */
216  public static <O extends @Nullable Object> ListenableFuture<O> submitAsync(
217      AsyncCallable<O> callable, Executor executor) {
218    TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
219    executor.execute(task);
220    return task;
221  }
222
223  /**
224   * Schedules {@code callable} on the specified {@code executor}, returning a {@code Future}.
225   *
226   * @throws RejectedExecutionException if the task cannot be scheduled for execution
227   * @since 28.0 (but only since 33.4.0 in the Android flavor)
228   */
229  @J2ktIncompatible
230  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
231  // TODO(cpovirk): Return ListenableScheduledFuture?
232  public static <O extends @Nullable Object> ListenableFuture<O> scheduleAsync(
233      AsyncCallable<O> callable, Duration delay, ScheduledExecutorService executorService) {
234    return scheduleAsync(callable, toNanosSaturated(delay), TimeUnit.NANOSECONDS, executorService);
235  }
236
237  /**
238   * Schedules {@code callable} on the specified {@code executor}, returning a {@code Future}.
239   *
240   * @throws RejectedExecutionException if the task cannot be scheduled for execution
241   * @since 23.0
242   */
243  @J2ktIncompatible
244  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
245  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
246  // TODO(cpovirk): Return ListenableScheduledFuture?
247  public static <O extends @Nullable Object> ListenableFuture<O> scheduleAsync(
248      AsyncCallable<O> callable,
249      long delay,
250      TimeUnit timeUnit,
251      ScheduledExecutorService executorService) {
252    TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
253    Future<?> scheduled = executorService.schedule(task, delay, timeUnit);
254    /*
255     * Even when the user interrupts the task, we pass `false` to `cancel` so that we don't
256     * interrupt a second time after the interruption performed by TrustedListenableFutureTask.
257     */
258    task.addListener(() -> scheduled.cancel(false), directExecutor());
259    return task;
260  }
261
262  /**
263   * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
264   * primary input fails with the given {@code exceptionType}, from the result provided by the
265   * {@code fallback}. {@link Function#apply} is not invoked until the primary input has failed, so
266   * if the primary input succeeds, it is never invoked. If, during the invocation of {@code
267   * fallback}, an exception is thrown, this exception is used as the result of the output {@code
268   * Future}.
269   *
270   * <p>Usage example:
271   *
272   * <pre>{@code
273   * ListenableFuture<Integer> fetchCounterFuture = ...;
274   *
275   * // Falling back to a zero counter in case an exception happens when
276   * // processing the RPC to fetch counters.
277   * ListenableFuture<Integer> faultTolerantFuture = Futures.catching(
278   *     fetchCounterFuture, FetchException.class, x -> 0, directExecutor());
279   * }</pre>
280   *
281   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
282   * the warnings the {@link MoreExecutors#directExecutor} documentation.
283   *
284   * @param input the primary input {@code Future}
285   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
286   *     type is matched against the input's exception. "The input's exception" means the cause of
287   *     the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
288   *     different kind of exception, that exception itself. To avoid hiding bugs and other
289   *     unrecoverable errors, callers should prefer more specific types, avoiding {@code
290   *     Throwable.class} in particular.
291   * @param fallback the {@link Function} to be called if {@code input} fails with the expected
292   *     exception type. The function's argument is the input's exception. "The input's exception"
293   *     means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
294   *     {@code get()} throws a different kind of exception, that exception itself.
295   * @param executor the executor that runs {@code fallback} if {@code input} fails
296   * @since 19.0
297   */
298  @J2ktIncompatible
299  @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
300  public static <V extends @Nullable Object, X extends Throwable> ListenableFuture<V> catching(
301      ListenableFuture<? extends V> input,
302      Class<X> exceptionType,
303      Function<? super X, ? extends V> fallback,
304      Executor executor) {
305    return AbstractCatchingFuture.create(input, exceptionType, fallback, executor);
306  }
307
308  /**
309   * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
310   * primary input fails with the given {@code exceptionType}, from the result provided by the
311   * {@code fallback}. {@link AsyncFunction#apply} is not invoked until the primary input has
312   * failed, so if the primary input succeeds, it is never invoked. If, during the invocation of
313   * {@code fallback}, an exception is thrown, this exception is used as the result of the output
314   * {@code Future}.
315   *
316   * <p>Usage examples:
317   *
318   * <pre>{@code
319   * ListenableFuture<Integer> fetchCounterFuture = ...;
320   *
321   * // Falling back to a zero counter in case an exception happens when
322   * // processing the RPC to fetch counters.
323   * ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
324   *     fetchCounterFuture, FetchException.class, x -> immediateFuture(0), directExecutor());
325   * }</pre>
326   *
327   * <p>The fallback can also choose to propagate the original exception when desired:
328   *
329   * <pre>{@code
330   * ListenableFuture<Integer> fetchCounterFuture = ...;
331   *
332   * // Falling back to a zero counter only in case the exception was a
333   * // TimeoutException.
334   * ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
335   *     fetchCounterFuture,
336   *     FetchException.class,
337   *     e -> {
338   *       if (omitDataOnFetchFailure) {
339   *         return immediateFuture(0);
340   *       }
341   *       throw e;
342   *     },
343   *     directExecutor());
344   * }</pre>
345   *
346   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
347   * the warnings the {@link MoreExecutors#directExecutor} documentation.
348   *
349   * @param input the primary input {@code Future}
350   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
351   *     type is matched against the input's exception. "The input's exception" means the cause of
352   *     the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
353   *     different kind of exception, that exception itself. To avoid hiding bugs and other
354   *     unrecoverable errors, callers should prefer more specific types, avoiding {@code
355   *     Throwable.class} in particular.
356   * @param fallback the {@link AsyncFunction} to be called if {@code input} fails with the expected
357   *     exception type. The function's argument is the input's exception. "The input's exception"
358   *     means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
359   *     {@code get()} throws a different kind of exception, that exception itself.
360   * @param executor the executor that runs {@code fallback} if {@code input} fails
361   * @since 19.0 (similar functionality in 14.0 as {@code withFallback})
362   */
363  @J2ktIncompatible
364  @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
365  public static <V extends @Nullable Object, X extends Throwable> ListenableFuture<V> catchingAsync(
366      ListenableFuture<? extends V> input,
367      Class<X> exceptionType,
368      AsyncFunction<? super X, ? extends V> fallback,
369      Executor executor) {
370    return AbstractCatchingFuture.createAsync(input, exceptionType, fallback, executor);
371  }
372
373  /**
374   * Returns a future that delegates to another but will finish early (via a {@link
375   * TimeoutException} wrapped in an {@link ExecutionException}) if the specified duration expires.
376   *
377   * <p>The delegate future is interrupted and cancelled if it times out.
378   *
379   * @param delegate The future to delegate to.
380   * @param time when to time out the future
381   * @param scheduledExecutor The executor service to enforce the timeout.
382   * @since 28.0 (but only since 33.4.0 in the Android flavor)
383   */
384  @J2ktIncompatible
385  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
386  public static <V extends @Nullable Object> ListenableFuture<V> withTimeout(
387      ListenableFuture<V> delegate, Duration time, ScheduledExecutorService scheduledExecutor) {
388    return withTimeout(delegate, toNanosSaturated(time), TimeUnit.NANOSECONDS, scheduledExecutor);
389  }
390
391  /**
392   * Returns a future that delegates to another but will finish early (via a {@link
393   * TimeoutException} wrapped in an {@link ExecutionException}) if the specified duration expires.
394   *
395   * <p>The delegate future is interrupted and cancelled if it times out.
396   *
397   * @param delegate The future to delegate to.
398   * @param time when to time out the future
399   * @param unit the time unit of the time parameter
400   * @param scheduledExecutor The executor service to enforce the timeout.
401   * @since 19.0
402   */
403  @J2ktIncompatible
404  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
405  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
406  public static <V extends @Nullable Object> ListenableFuture<V> withTimeout(
407      ListenableFuture<V> delegate,
408      long time,
409      TimeUnit unit,
410      ScheduledExecutorService scheduledExecutor) {
411    if (delegate.isDone()) {
412      return delegate;
413    }
414    return TimeoutFuture.create(delegate, time, unit, scheduledExecutor);
415  }
416
417  /**
418   * Returns a new {@code Future} whose result is asynchronously derived from the result of the
419   * given {@code Future}. If the given {@code Future} fails, the returned {@code Future} fails with
420   * the same exception (and the function is not invoked).
421   *
422   * <p>More precisely, the returned {@code Future} takes its result from a {@code Future} produced
423   * by applying the given {@code AsyncFunction} to the result of the original {@code Future}.
424   * Example usage:
425   *
426   * <pre>{@code
427   * ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
428   * ListenableFuture<QueryResult> queryFuture =
429   *     transformAsync(rowKeyFuture, dataService::readFuture, executor);
430   * }</pre>
431   *
432   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
433   * the warnings the {@link MoreExecutors#directExecutor} documentation.
434   *
435   * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
436   * input future and that of the future returned by the chain function. That is, if the returned
437   * {@code Future} is cancelled, it will attempt to cancel the other two, and if either of the
438   * other two is cancelled, the returned {@code Future} will receive a callback in which it will
439   * attempt to cancel itself.
440   *
441   * @param input The future to transform
442   * @param function A function to transform the result of the input future to the result of the
443   *     output future
444   * @param executor Executor to run the function in.
445   * @return A future that holds result of the function (if the input succeeded) or the original
446   *     input's failure (if not)
447   * @since 19.0 (in 11.0 as {@code transform})
448   */
449  public static <I extends @Nullable Object, O extends @Nullable Object>
450      ListenableFuture<O> transformAsync(
451          ListenableFuture<I> input,
452          AsyncFunction<? super I, ? extends O> function,
453          Executor executor) {
454    return AbstractTransformFuture.createAsync(input, function, executor);
455  }
456
457  /**
458   * Returns a new {@code Future} whose result is derived from the result of the given {@code
459   * Future}. If {@code input} fails, the returned {@code Future} fails with the same exception (and
460   * the function is not invoked). Example usage:
461   *
462   * <pre>{@code
463   * ListenableFuture<QueryResult> queryFuture = ...;
464   * ListenableFuture<List<Row>> rowsFuture =
465   *     transform(queryFuture, QueryResult::getRows, executor);
466   * }</pre>
467   *
468   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
469   * the warnings the {@link MoreExecutors#directExecutor} documentation.
470   *
471   * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
472   * input future. That is, if the returned {@code Future} is cancelled, it will attempt to cancel
473   * the input, and if the input is cancelled, the returned {@code Future} will receive a callback
474   * in which it will attempt to cancel itself.
475   *
476   * <p>An example use of this method is to convert a serializable object returned from an RPC into
477   * a POJO.
478   *
479   * @param input The future to transform
480   * @param function A Function to transform the results of the provided future to the results of
481   *     the returned future.
482   * @param executor Executor to run the function in.
483   * @return A future that holds result of the transformation.
484   * @since 9.0 (in 2.0 as {@code compose})
485   */
486  public static <I extends @Nullable Object, O extends @Nullable Object>
487      ListenableFuture<O> transform(
488          ListenableFuture<I> input, Function<? super I, ? extends O> function, Executor executor) {
489    return AbstractTransformFuture.create(input, function, executor);
490  }
491
492  /**
493   * Like {@link #transform(ListenableFuture, Function, Executor)} except that the transformation
494   * {@code function} is invoked on each call to {@link Future#get() get()} on the returned future.
495   *
496   * <p>The returned {@code Future} reflects the input's cancellation state directly, and any
497   * attempt to cancel the returned Future is likewise passed through to the input Future.
498   *
499   * <p>Note that calls to {@linkplain Future#get(long, TimeUnit) timed get} only apply the timeout
500   * to the execution of the underlying {@code Future}, <em>not</em> to the execution of the
501   * transformation function.
502   *
503   * <p>The primary audience of this method is callers of {@code transform} who don't have a {@code
504   * ListenableFuture} available and do not mind repeated, lazy function evaluation.
505   *
506   * @param input The future to transform
507   * @param function A Function to transform the results of the provided future to the results of
508   *     the returned future.
509   * @return A future that returns the result of the transformation.
510   * @since 10.0
511   */
512  @J2ktIncompatible
513  @GwtIncompatible // TODO
514  public static <I extends @Nullable Object, O extends @Nullable Object> Future<O> lazyTransform(
515      final Future<I> input, final Function<? super I, ? extends O> function) {
516    checkNotNull(input);
517    checkNotNull(function);
518    return new Future<O>() {
519
520      @Override
521      public boolean cancel(boolean mayInterruptIfRunning) {
522        return input.cancel(mayInterruptIfRunning);
523      }
524
525      @Override
526      public boolean isCancelled() {
527        return input.isCancelled();
528      }
529
530      @Override
531      public boolean isDone() {
532        return input.isDone();
533      }
534
535      @Override
536      public O get() throws InterruptedException, ExecutionException {
537        return applyTransformation(input.get());
538      }
539
540      @Override
541      public O get(long timeout, TimeUnit unit)
542          throws InterruptedException, ExecutionException, TimeoutException {
543        return applyTransformation(input.get(timeout, unit));
544      }
545
546      private O applyTransformation(I input) throws ExecutionException {
547        try {
548          return function.apply(input);
549        } catch (Throwable t) {
550          // Any Exception is either a RuntimeException or sneaky checked exception.
551          throw new ExecutionException(t);
552        }
553      }
554    };
555  }
556
557  /**
558   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
559   * input futures, if all succeed.
560   *
561   * <p>The list of results is in the same order as the input list.
562   *
563   * <p>This differs from {@link #successfulAsList(ListenableFuture[])} in that it will return a
564   * failed future if any of the items fails.
565   *
566   * <p>Canceling this future will attempt to cancel all the component futures, and if any of the
567   * provided futures fails or is canceled, this one is, too.
568   *
569   * @param futures futures to combine
570   * @return a future that provides a list of the results of the component futures
571   * @since 10.0
572   */
573  @SafeVarargs
574  public static <V extends @Nullable Object> ListenableFuture<List<V>> allAsList(
575      ListenableFuture<? extends V>... futures) {
576    ListenableFuture<List<@Nullable V>> nullable =
577        new ListFuture<V>(ImmutableList.copyOf(futures), true);
578    // allAsList ensures that it fills the output list with V instances.
579    @SuppressWarnings("nullness")
580    ListenableFuture<List<V>> nonNull = nullable;
581    return nonNull;
582  }
583
584  /**
585   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
586   * input futures, if all succeed.
587   *
588   * <p>The list of results is in the same order as the input list.
589   *
590   * <p>This differs from {@link #successfulAsList(Iterable)} in that it will return a failed future
591   * if any of the items fails.
592   *
593   * <p>Canceling this future will attempt to cancel all the component futures, and if any of the
594   * provided futures fails or is canceled, this one is, too.
595   *
596   * @param futures futures to combine
597   * @return a future that provides a list of the results of the component futures
598   * @since 10.0
599   */
600  public static <V extends @Nullable Object> ListenableFuture<List<V>> allAsList(
601      Iterable<? extends ListenableFuture<? extends V>> futures) {
602    ListenableFuture<List<@Nullable V>> nullable =
603        new ListFuture<V>(ImmutableList.copyOf(futures), true);
604    // allAsList ensures that it fills the output list with V instances.
605    @SuppressWarnings("nullness")
606    ListenableFuture<List<V>> nonNull = nullable;
607    return nonNull;
608  }
609
610  /**
611   * Creates a {@link FutureCombiner} that processes the completed futures whether or not they're
612   * successful.
613   *
614   * <p>Any failures from the input futures will not be propagated to the returned future.
615   *
616   * @since 20.0
617   */
618  @SafeVarargs
619  public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
620      ListenableFuture<? extends V>... futures) {
621    return new FutureCombiner<>(false, ImmutableList.copyOf(futures));
622  }
623
624  /**
625   * Creates a {@link FutureCombiner} that processes the completed futures whether or not they're
626   * successful.
627   *
628   * <p>Any failures from the input futures will not be propagated to the returned future.
629   *
630   * @since 20.0
631   */
632  public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
633      Iterable<? extends ListenableFuture<? extends V>> futures) {
634    return new FutureCombiner<>(false, ImmutableList.copyOf(futures));
635  }
636
637  /**
638   * Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
639   *
640   * <p>If any input fails, the returned future fails immediately.
641   *
642   * @since 20.0
643   */
644  @SafeVarargs
645  public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
646      ListenableFuture<? extends V>... futures) {
647    return new FutureCombiner<>(true, ImmutableList.copyOf(futures));
648  }
649
650  /**
651   * Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
652   *
653   * <p>If any input fails, the returned future fails immediately.
654   *
655   * @since 20.0
656   */
657  public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
658      Iterable<? extends ListenableFuture<? extends V>> futures) {
659    return new FutureCombiner<>(true, ImmutableList.copyOf(futures));
660  }
661
662  /**
663   * A helper to create a new {@code ListenableFuture} whose result is generated from a combination
664   * of input futures.
665   *
666   * <p>See {@link #whenAllComplete} and {@link #whenAllSucceed} for how to instantiate this class.
667   *
668   * <p>Example:
669   *
670   * <pre>{@code
671   * final ListenableFuture<Instant> loginDateFuture =
672   *     loginService.findLastLoginDate(username);
673   * final ListenableFuture<List<String>> recentCommandsFuture =
674   *     recentCommandsService.findRecentCommands(username);
675   * ListenableFuture<UsageHistory> usageFuture =
676   *     Futures.whenAllSucceed(loginDateFuture, recentCommandsFuture)
677   *         .call(
678   *             () ->
679   *                 new UsageHistory(
680   *                     username,
681   *                     Futures.getDone(loginDateFuture),
682   *                     Futures.getDone(recentCommandsFuture)),
683   *             executor);
684   * }</pre>
685   *
686   * @since 20.0
687   */
688  @GwtCompatible
689  public static final class FutureCombiner<V extends @Nullable Object> {
690    private final boolean allMustSucceed;
691    private final ImmutableList<ListenableFuture<? extends V>> futures;
692
693    private FutureCombiner(
694        boolean allMustSucceed, ImmutableList<ListenableFuture<? extends V>> futures) {
695      this.allMustSucceed = allMustSucceed;
696      this.futures = futures;
697    }
698
699    /**
700     * Creates the {@link ListenableFuture} which will return the result of calling {@link
701     * AsyncCallable#call} in {@code combiner} when all futures complete, using the specified {@code
702     * executor}.
703     *
704     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
705     * cancelled.
706     *
707     * <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code
708     * ExecutionException} will be extracted and returned as the cause of the new {@code
709     * ExecutionException} that gets thrown by the returned combined future.
710     *
711     * <p>Canceling this future will attempt to cancel all the component futures.
712     *
713     * @return a future whose result is based on {@code combiner} (or based on the input futures
714     *     passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
715     *     FutureCombiner}). Even if you don't care about the value of the future, you should
716     *     typically check whether it failed: See <a
717     *     href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
718     */
719    public <C extends @Nullable Object> ListenableFuture<C> callAsync(
720        AsyncCallable<C> combiner, Executor executor) {
721      return new CombinedFuture<>(futures, allMustSucceed, executor, combiner);
722    }
723
724    /**
725     * Creates the {@link ListenableFuture} which will return the result of calling {@link
726     * Callable#call} in {@code combiner} when all futures complete, using the specified {@code
727     * executor}.
728     *
729     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
730     * cancelled.
731     *
732     * <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code
733     * ExecutionException} will be extracted and returned as the cause of the new {@code
734     * ExecutionException} that gets thrown by the returned combined future.
735     *
736     * <p>Canceling this future will attempt to cancel all the component futures.
737     *
738     * @return a future whose result is based on {@code combiner} (or based on the input futures
739     *     passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
740     *     FutureCombiner}). Even if you don't care about the value of the future, you should
741     *     typically check whether it failed: See <a
742     *     href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
743     */
744    public <C extends @Nullable Object> ListenableFuture<C> call(
745        Callable<C> combiner, Executor executor) {
746      return new CombinedFuture<>(futures, allMustSucceed, executor, combiner);
747    }
748
749    /**
750     * Creates the {@link ListenableFuture} which will return the result of running {@code combiner}
751     * when all Futures complete. {@code combiner} will run using {@code executor}.
752     *
753     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
754     * cancelled.
755     *
756     * <p>Canceling this Future will attempt to cancel all the component futures.
757     *
758     * @since 23.6
759     * @return a future whose result is based on {@code combiner} (or based on the input futures
760     *     passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
761     *     FutureCombiner}). Even though the future never produces a value other than {@code null},
762     *     you should typically check whether it failed: See <a
763     *     href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
764     */
765    public ListenableFuture<?> run(final Runnable combiner, Executor executor) {
766      return call(
767          new Callable<@Nullable Void>() {
768            @Override
769            public @Nullable 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    @LazyInit private @Nullable 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      @RetainedLocalRef ListenableFuture<V> localDelegate = delegate;
809      if (localDelegate != null) {
810        setFuture(localDelegate);
811      }
812    }
813
814    @Override
815    protected @Nullable String pendingToString() {
816      @RetainedLocalRef 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    private @Nullable 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    protected @Nullable String pendingToString() {
979      InCompletionOrderState<T> localState = state;
980      if (localState != null) {
981        // Don't print the actual array! We don't want inCompletionOrder(list).toString() to have
982        // quadratic output.
983        return "inputCount=["
984            + localState.inputFutures.length
985            + "], remaining=["
986            + localState.incompleteOutputCount.get()
987            + "]";
988      }
989      return null;
990    }
991  }
992
993  private static final class InCompletionOrderState<T extends @Nullable Object> {
994    // A happens-before edge between the writes of these fields and their reads exists, because
995    // in order to read these fields, the corresponding write to incompleteOutputCount must have
996    // been read.
997    private boolean wasCancelled = false;
998    private boolean shouldInterrupt = true;
999    private final AtomicInteger incompleteOutputCount;
1000    // We set the elements of the array to null as they complete.
1001    private final @Nullable ListenableFuture<? extends T>[] inputFutures;
1002    private volatile int delegateIndex = 0;
1003
1004    private InCompletionOrderState(ListenableFuture<? extends T>[] inputFutures) {
1005      this.inputFutures = inputFutures;
1006      incompleteOutputCount = new AtomicInteger(inputFutures.length);
1007    }
1008
1009    private void recordOutputCancellation(boolean interruptIfRunning) {
1010      wasCancelled = true;
1011      // If all the futures were cancelled with interruption, cancel the input futures
1012      // with interruption; otherwise cancel without
1013      if (!interruptIfRunning) {
1014        shouldInterrupt = false;
1015      }
1016      recordCompletion();
1017    }
1018
1019    private void recordInputCompletion(
1020        ImmutableList<AbstractFuture<T>> delegates, int inputFutureIndex) {
1021      /*
1022       * requireNonNull is safe because we accepted an Iterable of non-null Future instances, and we
1023       * don't overwrite an element in the array until after reading it.
1024       */
1025      ListenableFuture<? extends T> inputFuture = requireNonNull(inputFutures[inputFutureIndex]);
1026      // Null out our reference to this future, so it can be GCed
1027      inputFutures[inputFutureIndex] = null;
1028      for (int i = delegateIndex; i < delegates.size(); i++) {
1029        if (delegates.get(i).setFuture(inputFuture)) {
1030          recordCompletion();
1031          // this is technically unnecessary, but should speed up later accesses
1032          delegateIndex = i + 1;
1033          return;
1034        }
1035      }
1036      // If all the delegates were complete, no reason for the next listener to have to
1037      // go through the whole list. Avoids O(n^2) behavior when the entire output list is
1038      // cancelled.
1039      delegateIndex = delegates.size();
1040    }
1041
1042    @SuppressWarnings("Interruption") // We are propagating an interrupt from a caller.
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 (Throwable e) {
1130        // Any Exception is either a RuntimeException or sneaky checked exception.
1131        callback.onFailure(e);
1132        return;
1133      }
1134      callback.onSuccess(value);
1135    }
1136
1137    @Override
1138    public String toString() {
1139      return MoreObjects.toStringHelper(this).addValue(callback).toString();
1140    }
1141  }
1142
1143  /**
1144   * Returns the result of the input {@code Future}, which must have already completed.
1145   *
1146   * <p>The benefits of this method are twofold. First, the name "getDone" suggests to readers that
1147   * the {@code Future} is already done. Second, if buggy code calls {@code getDone} on a {@code
1148   * Future} that is still pending, the program will throw instead of block. This can be important
1149   * for APIs like {@link #whenAllComplete whenAllComplete(...)}{@code .}{@link
1150   * FutureCombiner#call(Callable, Executor) call(...)}, where it is easy to use a new input from
1151   * the {@code call} implementation but forget to add it to the arguments of {@code
1152   * whenAllComplete}.
1153   *
1154   * <p>If you are looking for a method to determine whether a given {@code Future} is done, use the
1155   * instance method {@link Future#isDone()}.
1156   *
1157   * @throws ExecutionException if the {@code Future} failed with an exception
1158   * @throws CancellationException if the {@code Future} was cancelled
1159   * @throws IllegalStateException if the {@code Future} is not done
1160   * @since 20.0
1161   */
1162  @CanIgnoreReturnValue
1163  // TODO(cpovirk): Consider calling getDone() in our own code.
1164  @ParametricNullness
1165  public static <V extends @Nullable Object> V getDone(Future<V> future) throws ExecutionException {
1166    /*
1167     * We throw IllegalStateException, since the call could succeed later. Perhaps we "should" throw
1168     * IllegalArgumentException, since the call could succeed with a different argument. Those
1169     * exceptions' docs suggest that either is acceptable. Google's Java Practices page recommends
1170     * IllegalArgumentException here, in part to keep its recommendation simple: Static methods
1171     * should throw IllegalStateException only when they use static state.
1172     *
1173     * Why do we deviate here? The answer: We want for fluentFuture.getDone() to throw the same
1174     * exception as Futures.getDone(fluentFuture).
1175     */
1176    checkState(future.isDone(), "Future was expected to be done: %s", future);
1177    return getUninterruptibly(future);
1178  }
1179
1180  /**
1181   * Returns the result of {@link Future#get()}, converting most exceptions to a new instance of the
1182   * given checked exception type. This reduces boilerplate for a common use of {@code Future} in
1183   * which it is unnecessary to programmatically distinguish between exception types or to extract
1184   * other information from the exception instance.
1185   *
1186   * <p>Exceptions from {@code Future.get} are treated as follows:
1187   *
1188   * <ul>
1189   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1190   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1191   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1192   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1193   *       interrupt).
1194   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1195   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1196   *       exceptions).
1197   * </ul>
1198   *
1199   * <p>The overall principle is to continue to treat every checked exception as a checked
1200   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1201   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1202   * new stack trace matches that of the current thread.
1203   *
1204   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1205   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1206   * (preferring constructors with at least one {@code String}, then preferring constructors with at
1207   * least one {@code Throwable}) and calling the constructor via reflection. If the exception did
1208   * not already have a cause, one is set by calling {@link Throwable#initCause(Throwable)} on it.
1209   * If no such constructor exists, an {@code IllegalArgumentException} is thrown.
1210   *
1211   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1212   *     whose cause is not itself a checked exception
1213   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1214   *     {@code RuntimeException} as its cause
1215   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1216   *     Error} as its cause
1217   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1218   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1219   *     does not have a suitable constructor
1220   * @since 19.0 (in 10.0 as {@code get})
1221   */
1222  @CanIgnoreReturnValue
1223  @J2ktIncompatible
1224  @GwtIncompatible // reflection
1225  @ParametricNullness
1226  public static <V extends @Nullable Object, X extends Exception> V getChecked(
1227      Future<V> future, Class<X> exceptionClass) throws X {
1228    return FuturesGetChecked.getChecked(future, exceptionClass);
1229  }
1230
1231  /**
1232   * Returns the result of {@link Future#get(long, TimeUnit)}, converting most exceptions to a new
1233   * instance of the given checked exception type. This reduces boilerplate for a common use of
1234   * {@code Future} in which it is unnecessary to programmatically distinguish between exception
1235   * types or to extract other information from the exception instance.
1236   *
1237   * <p>Exceptions from {@code Future.get} are treated as follows:
1238   *
1239   * <ul>
1240   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1241   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1242   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1243   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1244   *       interrupt).
1245   *   <li>Any {@link TimeoutException} is wrapped in an {@code X}.
1246   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1247   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1248   *       exceptions).
1249   * </ul>
1250   *
1251   * <p>The overall principle is to continue to treat every checked exception as a checked
1252   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1253   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1254   * new stack trace matches that of the current thread.
1255   *
1256   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1257   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1258   * (preferring constructors with at least one {@code String}, then preferring constructors with at
1259   * least one {@code Throwable}) and calling the constructor via reflection. If the exception did
1260   * not already have a cause, one is set by calling {@link Throwable#initCause(Throwable)} on it.
1261   * If no such constructor exists, an {@code IllegalArgumentException} is thrown.
1262   *
1263   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1264   *     whose cause is not itself a checked exception
1265   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1266   *     {@code RuntimeException} as its cause
1267   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1268   *     Error} as its cause
1269   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1270   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1271   *     does not have a suitable constructor
1272   * @since 28.0 (but only since 33.4.0 in the Android flavor)
1273   */
1274  @CanIgnoreReturnValue
1275  @J2ktIncompatible
1276  @GwtIncompatible // reflection
1277  @ParametricNullness
1278  public static <V extends @Nullable Object, X extends Exception> V getChecked(
1279      Future<V> future, Class<X> exceptionClass, Duration timeout) throws X {
1280    return getChecked(future, exceptionClass, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
1281  }
1282
1283  /**
1284   * Returns the result of {@link Future#get(long, TimeUnit)}, converting most exceptions to a new
1285   * instance of the given checked exception type. This reduces boilerplate for a common use of
1286   * {@code Future} in which it is unnecessary to programmatically distinguish between exception
1287   * types or to extract other information from the exception instance.
1288   *
1289   * <p>Exceptions from {@code Future.get} are treated as follows:
1290   *
1291   * <ul>
1292   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1293   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1294   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1295   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1296   *       interrupt).
1297   *   <li>Any {@link TimeoutException} is wrapped in an {@code X}.
1298   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1299   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1300   *       exceptions).
1301   * </ul>
1302   *
1303   * <p>The overall principle is to continue to treat every checked exception as a checked
1304   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1305   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1306   * new stack trace matches that of the current thread.
1307   *
1308   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1309   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1310   * (preferring constructors with at least one {@code String}) and calling the constructor via
1311   * reflection. If the exception did not already have a cause, one is set by calling {@link
1312   * Throwable#initCause(Throwable)} on it. If no such constructor exists, an {@code
1313   * IllegalArgumentException} is thrown.
1314   *
1315   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1316   *     whose cause is not itself a checked exception
1317   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1318   *     {@code RuntimeException} as its cause
1319   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1320   *     Error} as its cause
1321   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1322   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1323   *     does not have a suitable constructor
1324   * @since 19.0 (in 10.0 as {@code get} and with different parameter order)
1325   */
1326  @CanIgnoreReturnValue
1327  @J2ktIncompatible
1328  @GwtIncompatible // reflection
1329  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
1330  @ParametricNullness
1331  public static <V extends @Nullable Object, X extends Exception> V getChecked(
1332      Future<V> future, Class<X> exceptionClass, long timeout, TimeUnit unit) throws X {
1333    return FuturesGetChecked.getChecked(future, exceptionClass, timeout, unit);
1334  }
1335
1336  /**
1337   * Returns the result of calling {@link Future#get()} uninterruptibly on a task known not to throw
1338   * a checked exception. This makes {@code Future} more suitable for lightweight, fast-running
1339   * tasks that, barring bugs in the code, will not fail. This gives it exception-handling behavior
1340   * similar to that of {@code ForkJoinTask.join}.
1341   *
1342   * <p>Exceptions from {@code Future.get} are treated as follows:
1343   *
1344   * <ul>
1345   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@link
1346   *       UncheckedExecutionException} (if the cause is an {@code Exception}) or {@link
1347   *       ExecutionError} (if the cause is an {@code Error}).
1348   *   <li>Any {@link InterruptedException} causes a retry of the {@code get} call. The interrupt is
1349   *       restored before {@code getUnchecked} returns.
1350   *   <li>Any {@link CancellationException} is propagated untouched. So is any other {@link
1351   *       RuntimeException} ({@code get} implementations are discouraged from throwing such
1352   *       exceptions).
1353   * </ul>
1354   *
1355   * <p>The overall principle is to eliminate all checked exceptions: to loop to avoid {@code
1356   * InterruptedException}, to pass through {@code CancellationException}, and to wrap any exception
1357   * from the underlying computation in an {@code UncheckedExecutionException} or {@code
1358   * ExecutionError}.
1359   *
1360   * <p>For an uninterruptible {@code get} that preserves other exceptions, see {@link
1361   * Uninterruptibles#getUninterruptibly(Future)}.
1362   *
1363   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with an
1364   *     {@code Exception} as its cause
1365   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1366   *     Error} as its cause
1367   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1368   * @since 10.0
1369   */
1370  @CanIgnoreReturnValue
1371  @ParametricNullness
1372  public static <V extends @Nullable Object> V getUnchecked(Future<V> future) {
1373    checkNotNull(future);
1374    try {
1375      return getUninterruptibly(future);
1376    } catch (ExecutionException wrapper) {
1377      if (wrapper.getCause() instanceof Error) {
1378        throw new ExecutionError((Error) wrapper.getCause());
1379      }
1380      /*
1381       * It's an Exception. (Or it's a non-Error, non-Exception Throwable. From my survey of such
1382       * classes, I believe that most users intended to extend Exception, so we'll treat it like an
1383       * Exception.)
1384       */
1385      throw new UncheckedExecutionException(wrapper.getCause());
1386    }
1387  }
1388
1389  /*
1390   * Arguably we don't need a timed getUnchecked because any operation slow enough to require a
1391   * timeout is heavyweight enough to throw a checked exception and therefore be inappropriate to
1392   * use with getUnchecked. Further, it's not clear that converting the checked TimeoutException to
1393   * a RuntimeException -- especially to an UncheckedExecutionException, since it wasn't thrown by
1394   * the computation -- makes sense, and if we don't convert it, the user still has to write a
1395   * try-catch block.
1396   *
1397   * If you think you would use this method, let us know. You might also look into the
1398   * Fork-Join framework: http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html
1399   */
1400}