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