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