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    ListenableFuture<Object> instance = ImmediateCancelledFuture.INSTANCE;
176    if (instance != null) {
177      return (ListenableFuture<V>) instance;
178    }
179    return new ImmediateCancelledFuture<>();
180  }
181
182  /**
183   * Executes {@code callable} on the specified {@code executor}, returning a {@code Future}.
184   *
185   * @throws RejectedExecutionException if the task cannot be scheduled for execution
186   * @since 28.2
187   */
188  public static <O extends @Nullable Object> ListenableFuture<O> submit(
189      Callable<O> callable, Executor executor) {
190    TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
191    executor.execute(task);
192    return task;
193  }
194
195  /**
196   * Executes {@code runnable} on the specified {@code executor}, returning a {@code Future} that
197   * will complete after execution.
198   *
199   * @throws RejectedExecutionException if the task cannot be scheduled for execution
200   * @since 28.2
201   */
202  public static ListenableFuture<@Nullable Void> submit(Runnable runnable, Executor executor) {
203    TrustedListenableFutureTask<@Nullable Void> task =
204        TrustedListenableFutureTask.create(runnable, null);
205    executor.execute(task);
206    return task;
207  }
208
209  /**
210   * Executes {@code callable} on the specified {@code executor}, returning a {@code Future}.
211   *
212   * @throws RejectedExecutionException if the task cannot be scheduled for execution
213   * @since 23.0
214   */
215  public static <O extends @Nullable Object> ListenableFuture<O> submitAsync(
216      AsyncCallable<O> callable, Executor executor) {
217    TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
218    executor.execute(task);
219    return task;
220  }
221
222  /**
223   * Schedules {@code callable} on the specified {@code executor}, returning a {@code Future}.
224   *
225   * @throws RejectedExecutionException if the task cannot be scheduled for execution
226   * @since 28.0
227   */
228  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
229  // TODO(cpovirk): Return ListenableScheduledFuture?
230  public static <O extends @Nullable Object> ListenableFuture<O> scheduleAsync(
231      AsyncCallable<O> callable, Duration delay, ScheduledExecutorService executorService) {
232    return scheduleAsync(callable, toNanosSaturated(delay), TimeUnit.NANOSECONDS, executorService);
233  }
234
235  /**
236   * Schedules {@code callable} on the specified {@code executor}, returning a {@code Future}.
237   *
238   * @throws RejectedExecutionException if the task cannot be scheduled for execution
239   * @since 23.0
240   */
241  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
242  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
243  // TODO(cpovirk): Return ListenableScheduledFuture?
244  public static <O extends @Nullable Object> ListenableFuture<O> scheduleAsync(
245      AsyncCallable<O> callable,
246      long delay,
247      TimeUnit timeUnit,
248      ScheduledExecutorService executorService) {
249    TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
250    final Future<?> scheduled = executorService.schedule(task, delay, timeUnit);
251    task.addListener(
252        new Runnable() {
253          @Override
254          public void run() {
255            // Don't want to interrupt twice
256            scheduled.cancel(false);
257          }
258        },
259        directExecutor());
260    return task;
261  }
262
263  /**
264   * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
265   * primary input fails with the given {@code exceptionType}, from the result provided by the
266   * {@code fallback}. {@link Function#apply} is not invoked until the primary input has failed, so
267   * if the primary input succeeds, it is never invoked. If, during the invocation of {@code
268   * fallback}, an exception is thrown, this exception is used as the result of the output {@code
269   * Future}.
270   *
271   * <p>Usage example:
272   *
273   * <pre>{@code
274   * ListenableFuture<Integer> fetchCounterFuture = ...;
275   *
276   * // Falling back to a zero counter in case an exception happens when
277   * // processing the RPC to fetch counters.
278   * ListenableFuture<Integer> faultTolerantFuture = Futures.catching(
279   *     fetchCounterFuture, FetchException.class, x -> 0, directExecutor());
280   * }</pre>
281   *
282   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
283   * the warnings the {@link MoreExecutors#directExecutor} documentation.
284   *
285   * @param input the primary input {@code Future}
286   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
287   *     type is matched against the input's exception. "The input's exception" means the cause of
288   *     the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
289   *     different kind of exception, that exception itself. To avoid hiding bugs and other
290   *     unrecoverable errors, callers should prefer more specific types, avoiding {@code
291   *     Throwable.class} in particular.
292   * @param fallback the {@link Function} to be called if {@code input} fails with the expected
293   *     exception type. The function's argument is the input's exception. "The input's exception"
294   *     means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
295   *     {@code get()} throws a different kind of exception, that exception itself.
296   * @param executor the executor that runs {@code fallback} if {@code input} fails
297   * @since 19.0
298   */
299  @Beta
300  @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
301  public static <V extends @Nullable Object, X extends Throwable> ListenableFuture<V> catching(
302      ListenableFuture<? extends V> input,
303      Class<X> exceptionType,
304      Function<? super X, ? extends V> fallback,
305      Executor executor) {
306    return AbstractCatchingFuture.create(input, exceptionType, fallback, executor);
307  }
308
309  /**
310   * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
311   * primary input fails with the given {@code exceptionType}, from the result provided by the
312   * {@code fallback}. {@link AsyncFunction#apply} is not invoked until the primary input has
313   * failed, so if the primary input succeeds, it is never invoked. If, during the invocation of
314   * {@code fallback}, an exception is thrown, this exception is used as the result of the output
315   * {@code Future}.
316   *
317   * <p>Usage examples:
318   *
319   * <pre>{@code
320   * ListenableFuture<Integer> fetchCounterFuture = ...;
321   *
322   * // Falling back to a zero counter in case an exception happens when
323   * // processing the RPC to fetch counters.
324   * ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
325   *     fetchCounterFuture, FetchException.class, x -> immediateFuture(0), directExecutor());
326   * }</pre>
327   *
328   * <p>The fallback can also choose to propagate the original exception when desired:
329   *
330   * <pre>{@code
331   * ListenableFuture<Integer> fetchCounterFuture = ...;
332   *
333   * // Falling back to a zero counter only in case the exception was a
334   * // TimeoutException.
335   * ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
336   *     fetchCounterFuture,
337   *     FetchException.class,
338   *     e -> {
339   *       if (omitDataOnFetchFailure) {
340   *         return immediateFuture(0);
341   *       }
342   *       throw e;
343   *     },
344   *     directExecutor());
345   * }</pre>
346   *
347   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
348   * the warnings the {@link MoreExecutors#directExecutor} documentation.
349   *
350   * @param input the primary input {@code Future}
351   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
352   *     type is matched against the input's exception. "The input's exception" means the cause of
353   *     the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
354   *     different kind of exception, that exception itself. To avoid hiding bugs and other
355   *     unrecoverable errors, callers should prefer more specific types, avoiding {@code
356   *     Throwable.class} in particular.
357   * @param fallback the {@link AsyncFunction} to be called if {@code input} fails with the expected
358   *     exception type. The function's argument is the input's exception. "The input's exception"
359   *     means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
360   *     {@code get()} throws a different kind of exception, that exception itself.
361   * @param executor the executor that runs {@code fallback} if {@code input} fails
362   * @since 19.0 (similar functionality in 14.0 as {@code withFallback})
363   */
364  @Beta
365  @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
366  public static <V extends @Nullable Object, X extends Throwable> ListenableFuture<V> catchingAsync(
367      ListenableFuture<? extends V> input,
368      Class<X> exceptionType,
369      AsyncFunction<? super X, ? extends V> fallback,
370      Executor executor) {
371    return AbstractCatchingFuture.create(input, exceptionType, fallback, executor);
372  }
373
374  /**
375   * Returns a future that delegates to another but will finish early (via a {@link
376   * TimeoutException} wrapped in an {@link ExecutionException}) if the specified duration expires.
377   *
378   * <p>The delegate future is interrupted and cancelled if it times out.
379   *
380   * @param delegate The future to delegate to.
381   * @param time when to timeout the future
382   * @param scheduledExecutor The executor service to enforce the timeout.
383   * @since 28.0
384   */
385  @Beta
386  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
387  public static <V extends @Nullable Object> ListenableFuture<V> withTimeout(
388      ListenableFuture<V> delegate, Duration time, ScheduledExecutorService scheduledExecutor) {
389    return withTimeout(delegate, toNanosSaturated(time), TimeUnit.NANOSECONDS, scheduledExecutor);
390  }
391
392  /**
393   * Returns a future that delegates to another but will finish early (via a {@link
394   * TimeoutException} wrapped in an {@link ExecutionException}) if the specified duration expires.
395   *
396   * <p>The delegate future is interrupted and cancelled if it times out.
397   *
398   * @param delegate The future to delegate to.
399   * @param time when to timeout the future
400   * @param unit the time unit of the time parameter
401   * @param scheduledExecutor The executor service to enforce the timeout.
402   * @since 19.0
403   */
404  @Beta
405  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
406  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
407  public static <V extends @Nullable Object> ListenableFuture<V> withTimeout(
408      ListenableFuture<V> delegate,
409      long time,
410      TimeUnit unit,
411      ScheduledExecutorService scheduledExecutor) {
412    if (delegate.isDone()) {
413      return delegate;
414    }
415    return TimeoutFuture.create(delegate, time, unit, scheduledExecutor);
416  }
417
418  /**
419   * Returns a new {@code Future} whose result is asynchronously derived from the result of the
420   * given {@code Future}. If the given {@code Future} fails, the returned {@code Future} fails with
421   * the same exception (and the function is not invoked).
422   *
423   * <p>More precisely, the returned {@code Future} takes its result from a {@code Future} produced
424   * by applying the given {@code AsyncFunction} to the result of the original {@code Future}.
425   * Example usage:
426   *
427   * <pre>{@code
428   * ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
429   * ListenableFuture<QueryResult> queryFuture =
430   *     transformAsync(rowKeyFuture, dataService::readFuture, executor);
431   * }</pre>
432   *
433   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
434   * the warnings the {@link MoreExecutors#directExecutor} documentation.
435   *
436   * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
437   * input future and that of the future returned by the chain function. That is, if the returned
438   * {@code Future} is cancelled, it will attempt to cancel the other two, and if either of the
439   * other two is cancelled, the returned {@code Future} will receive a callback in which it will
440   * attempt to cancel itself.
441   *
442   * @param input The future to transform
443   * @param function A function to transform the result of the input future to the result of the
444   *     output future
445   * @param executor Executor to run the function in.
446   * @return A future that holds result of the function (if the input succeeded) or the original
447   *     input's failure (if not)
448   * @since 19.0 (in 11.0 as {@code transform})
449   */
450  @Beta
451  public static <I extends @Nullable Object, O extends @Nullable Object>
452      ListenableFuture<O> transformAsync(
453          ListenableFuture<I> input,
454          AsyncFunction<? super I, ? extends O> function,
455          Executor executor) {
456    return AbstractTransformFuture.create(input, function, executor);
457  }
458
459  /**
460   * Returns a new {@code Future} whose result is derived from the result of the given {@code
461   * Future}. If {@code input} fails, the returned {@code Future} fails with the same exception (and
462   * the function is not invoked). Example usage:
463   *
464   * <pre>{@code
465   * ListenableFuture<QueryResult> queryFuture = ...;
466   * ListenableFuture<List<Row>> rowsFuture =
467   *     transform(queryFuture, QueryResult::getRows, executor);
468   * }</pre>
469   *
470   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
471   * the warnings the {@link MoreExecutors#directExecutor} documentation.
472   *
473   * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
474   * input future. That is, if the returned {@code Future} is cancelled, it will attempt to cancel
475   * the input, and if the input is cancelled, the returned {@code Future} will receive a callback
476   * in which it will attempt to cancel itself.
477   *
478   * <p>An example use of this method is to convert a serializable object returned from an RPC into
479   * a POJO.
480   *
481   * @param input The future to transform
482   * @param function A Function to transform the results of the provided future to the results of
483   *     the returned future.
484   * @param executor Executor to run the function in.
485   * @return A future that holds result of the transformation.
486   * @since 9.0 (in 2.0 as {@code compose})
487   */
488  @Beta
489  public static <I extends @Nullable Object, O extends @Nullable Object>
490      ListenableFuture<O> transform(
491          ListenableFuture<I> input, Function<? super I, ? extends O> function, Executor executor) {
492    return AbstractTransformFuture.create(input, function, executor);
493  }
494
495  /**
496   * Like {@link #transform(ListenableFuture, Function, Executor)} except that the transformation
497   * {@code function} is invoked on each call to {@link Future#get() get()} on the returned future.
498   *
499   * <p>The returned {@code Future} reflects the input's cancellation state directly, and any
500   * attempt to cancel the returned Future is likewise passed through to the input Future.
501   *
502   * <p>Note that calls to {@linkplain Future#get(long, TimeUnit) timed get} only apply the timeout
503   * to the execution of the underlying {@code Future}, <em>not</em> to the execution of the
504   * transformation function.
505   *
506   * <p>The primary audience of this method is callers of {@code transform} who don't have a {@code
507   * ListenableFuture} available and do not mind repeated, lazy function evaluation.
508   *
509   * @param input The future to transform
510   * @param function A Function to transform the results of the provided future to the results of
511   *     the returned future.
512   * @return A future that returns the result of the transformation.
513   * @since 10.0
514   */
515  @Beta
516  @GwtIncompatible // TODO
517  public static <I extends @Nullable Object, O extends @Nullable Object> Future<O> lazyTransform(
518      final Future<I> input, final Function<? super I, ? extends O> function) {
519    checkNotNull(input);
520    checkNotNull(function);
521    return new Future<O>() {
522
523      @Override
524      public boolean cancel(boolean mayInterruptIfRunning) {
525        return input.cancel(mayInterruptIfRunning);
526      }
527
528      @Override
529      public boolean isCancelled() {
530        return input.isCancelled();
531      }
532
533      @Override
534      public boolean isDone() {
535        return input.isDone();
536      }
537
538      @Override
539      public O get() throws InterruptedException, ExecutionException {
540        return applyTransformation(input.get());
541      }
542
543      @Override
544      public O get(long timeout, TimeUnit unit)
545          throws InterruptedException, ExecutionException, TimeoutException {
546        return applyTransformation(input.get(timeout, unit));
547      }
548
549      private O applyTransformation(I input) throws ExecutionException {
550        try {
551          return function.apply(input);
552        } catch (Throwable t) {
553          throw new ExecutionException(t);
554        }
555      }
556    };
557  }
558
559  /**
560   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
561   * input futures, if all succeed.
562   *
563   * <p>The list of results is in the same order as the input list.
564   *
565   * <p>This differs from {@link #successfulAsList(ListenableFuture[])} in that it will return a
566   * failed future if any of the items fails.
567   *
568   * <p>Canceling this future will attempt to cancel all the component futures, and if any of the
569   * provided futures fails or is canceled, this one is, too.
570   *
571   * @param futures futures to combine
572   * @return a future that provides a list of the results of the component futures
573   * @since 10.0
574   */
575  @Beta
576  @SafeVarargs
577  public static <V extends @Nullable Object> ListenableFuture<List<V>> allAsList(
578      ListenableFuture<? extends V>... futures) {
579    ListenableFuture<List<@Nullable V>> nullable =
580        new ListFuture<V>(ImmutableList.copyOf(futures), true);
581    // allAsList ensures that it fills the output list with V instances.
582    @SuppressWarnings("nullness")
583    ListenableFuture<List<V>> nonNull = nullable;
584    return nonNull;
585  }
586
587  /**
588   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
589   * input futures, if all succeed.
590   *
591   * <p>The list of results is in the same order as the input list.
592   *
593   * <p>This differs from {@link #successfulAsList(Iterable)} in that it will return a failed future
594   * if any of the items fails.
595   *
596   * <p>Canceling this future will attempt to cancel all the component futures, and if any of the
597   * provided futures fails or is canceled, this one is, too.
598   *
599   * @param futures futures to combine
600   * @return a future that provides a list of the results of the component futures
601   * @since 10.0
602   */
603  @Beta
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  @Beta
623  @SafeVarargs
624  public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
625      ListenableFuture<? extends V>... futures) {
626    return new FutureCombiner<V>(false, ImmutableList.copyOf(futures));
627  }
628
629  /**
630   * Creates a {@link FutureCombiner} that processes the completed futures whether or not they're
631   * successful.
632   *
633   * <p>Any failures from the input futures will not be propagated to the returned future.
634   *
635   * @since 20.0
636   */
637  @Beta
638  public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
639      Iterable<? extends ListenableFuture<? extends V>> futures) {
640    return new FutureCombiner<V>(false, ImmutableList.copyOf(futures));
641  }
642
643  /**
644   * Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
645   *
646   * <p>If any input fails, the returned future fails immediately.
647   *
648   * @since 20.0
649   */
650  @Beta
651  @SafeVarargs
652  public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
653      ListenableFuture<? extends V>... futures) {
654    return new FutureCombiner<V>(true, ImmutableList.copyOf(futures));
655  }
656
657  /**
658   * Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
659   *
660   * <p>If any input fails, the returned future fails immediately.
661   *
662   * @since 20.0
663   */
664  @Beta
665  public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
666      Iterable<? extends ListenableFuture<? extends V>> futures) {
667    return new FutureCombiner<V>(true, ImmutableList.copyOf(futures));
668  }
669
670  /**
671   * A helper to create a new {@code ListenableFuture} whose result is generated from a combination
672   * of input futures.
673   *
674   * <p>See {@link #whenAllComplete} and {@link #whenAllSucceed} for how to instantiate this class.
675   *
676   * <p>Example:
677   *
678   * <pre>{@code
679   * final ListenableFuture<Instant> loginDateFuture =
680   *     loginService.findLastLoginDate(username);
681   * final ListenableFuture<List<String>> recentCommandsFuture =
682   *     recentCommandsService.findRecentCommands(username);
683   * ListenableFuture<UsageHistory> usageFuture =
684   *     Futures.whenAllSucceed(loginDateFuture, recentCommandsFuture)
685   *         .call(
686   *             () ->
687   *                 new UsageHistory(
688   *                     username,
689   *                     Futures.getDone(loginDateFuture),
690   *                     Futures.getDone(recentCommandsFuture)),
691   *             executor);
692   * }</pre>
693   *
694   * @since 20.0
695   */
696  @Beta
697  @CanIgnoreReturnValue // TODO(cpovirk): Consider removing, especially if we provide run(Runnable)
698  @GwtCompatible
699  public static final class FutureCombiner<V extends @Nullable Object> {
700    private final boolean allMustSucceed;
701    private final ImmutableList<ListenableFuture<? extends V>> futures;
702
703    private FutureCombiner(
704        boolean allMustSucceed, ImmutableList<ListenableFuture<? extends V>> futures) {
705      this.allMustSucceed = allMustSucceed;
706      this.futures = futures;
707    }
708
709    /**
710     * Creates the {@link ListenableFuture} which will return the result of calling {@link
711     * AsyncCallable#call} in {@code combiner} when all futures complete, using the specified {@code
712     * executor}.
713     *
714     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
715     * cancelled.
716     *
717     * <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code
718     * ExecutionException} will be extracted and returned as the cause of the new {@code
719     * ExecutionException} that gets thrown by the returned combined future.
720     *
721     * <p>Canceling this future will attempt to cancel all the component futures.
722     */
723    public <C extends @Nullable Object> ListenableFuture<C> callAsync(
724        AsyncCallable<C> combiner, Executor executor) {
725      return new CombinedFuture<C>(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    @CanIgnoreReturnValue // TODO(cpovirk): Remove this
743    public <C extends @Nullable Object> ListenableFuture<C> call(
744        Callable<C> combiner, Executor executor) {
745      return new CombinedFuture<C>(futures, allMustSucceed, executor, combiner);
746    }
747
748    /**
749     * Creates the {@link ListenableFuture} which will return the result of running {@code combiner}
750     * when all Futures complete. {@code combiner} will run using {@code executor}.
751     *
752     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
753     * cancelled.
754     *
755     * <p>Canceling this Future will attempt to cancel all the component futures.
756     *
757     * @since 23.6
758     */
759    public ListenableFuture<?> run(final Runnable combiner, Executor executor) {
760      return call(
761          new Callable<@Nullable Void>() {
762            @Override
763            @CheckForNull
764            public Void call() throws Exception {
765              combiner.run();
766              return null;
767            }
768          },
769          executor);
770    }
771  }
772
773  /**
774   * Returns a {@code ListenableFuture} whose result is set from the supplied future when it
775   * completes. Cancelling the supplied future will also cancel the returned future, but cancelling
776   * the returned future will have no effect on the supplied future.
777   *
778   * @since 15.0
779   */
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  @Beta
844  @SafeVarargs
845  public static <V extends @Nullable Object> ListenableFuture<List<@Nullable V>> successfulAsList(
846      ListenableFuture<? extends V>... futures) {
847    /*
848     * Another way to express this signature would be to bound <V> by @NonNull and accept
849     * LF<? extends @Nullable V>. That might be better: There's currently no difference between the
850     * outputs users get when calling this with <Foo> and calling it with <@Nullable Foo>. The only
851     * difference is that calling it with <Foo> won't work when an input Future has a @Nullable
852     * type. So why even make that error possible by giving callers the choice?
853     *
854     * On the other hand, the current signature is consistent with the similar allAsList method. And
855     * eventually this method may go away entirely in favor of an API like
856     * whenAllComplete().collectSuccesses(). That API would have a signature more like the current
857     * one.
858     */
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  public static <T extends @Nullable Object> ImmutableList<ListenableFuture<T>> inCompletionOrder(
908      Iterable<? extends ListenableFuture<? extends T>> futures) {
909    ListenableFuture<? extends T>[] copy = gwtCompatibleToArray(futures);
910    final InCompletionOrderState<T> state = new InCompletionOrderState<>(copy);
911    ImmutableList.Builder<AbstractFuture<T>> delegatesBuilder =
912        ImmutableList.builderWithExpectedSize(copy.length);
913    for (int i = 0; i < copy.length; i++) {
914      delegatesBuilder.add(new InCompletionOrderFuture<T>(state));
915    }
916
917    final ImmutableList<AbstractFuture<T>> delegates = delegatesBuilder.build();
918    for (int i = 0; i < copy.length; i++) {
919      final int localI = i;
920      copy[i].addListener(
921          new Runnable() {
922            @Override
923            public void run() {
924              state.recordInputCompletion(delegates, localI);
925            }
926          },
927          directExecutor());
928    }
929
930    @SuppressWarnings("unchecked")
931    ImmutableList<ListenableFuture<T>> delegatesCast = (ImmutableList) delegates;
932    return delegatesCast;
933  }
934
935  /** Can't use Iterables.toArray because it's not gwt compatible */
936  @SuppressWarnings("unchecked")
937  private static <T extends @Nullable Object> ListenableFuture<? extends T>[] gwtCompatibleToArray(
938      Iterable<? extends ListenableFuture<? extends T>> futures) {
939    final Collection<ListenableFuture<? extends T>> collection;
940    if (futures instanceof Collection) {
941      collection = (Collection<ListenableFuture<? extends T>>) futures;
942    } else {
943      collection = ImmutableList.copyOf(futures);
944    }
945    return (ListenableFuture<? extends T>[]) collection.toArray(new ListenableFuture<?>[0]);
946  }
947
948  // This can't be a TrustedFuture, because TrustedFuture has clever optimizations that
949  // mean cancel won't be called if this Future is passed into setFuture, and then
950  // cancelled.
951  private static final class InCompletionOrderFuture<T extends @Nullable Object>
952      extends AbstractFuture<T> {
953    @CheckForNull private InCompletionOrderState<T> state;
954
955    private InCompletionOrderFuture(InCompletionOrderState<T> state) {
956      this.state = state;
957    }
958
959    @Override
960    public boolean cancel(boolean interruptIfRunning) {
961      InCompletionOrderState<T> localState = state;
962      if (super.cancel(interruptIfRunning)) {
963        /*
964         * requireNonNull is generally safe: If cancel succeeded, then this Future was still
965         * pending, so its `state` field hasn't been nulled out yet.
966         *
967         * OK, it's technically possible for this to fail in the presence of unsafe publishing, as
968         * discussed in the comments in TimeoutFuture. TODO(cpovirk): Maybe check for null before
969         * calling recordOutputCancellation?
970         */
971        requireNonNull(localState).recordOutputCancellation(interruptIfRunning);
972        return true;
973      }
974      return false;
975    }
976
977    @Override
978    protected void afterDone() {
979      state = null;
980    }
981
982    @Override
983    @CheckForNull
984    protected String pendingToString() {
985      InCompletionOrderState<T> localState = state;
986      if (localState != null) {
987        // Don't print the actual array! We don't want inCompletionOrder(list).toString() to have
988        // quadratic output.
989        return "inputCount=["
990            + localState.inputFutures.length
991            + "], remaining=["
992            + localState.incompleteOutputCount.get()
993            + "]";
994      }
995      return null;
996    }
997  }
998
999  private static final class InCompletionOrderState<T extends @Nullable Object> {
1000    // A happens-before edge between the writes of these fields and their reads exists, because
1001    // in order to read these fields, the corresponding write to incompleteOutputCount must have
1002    // been read.
1003    private boolean wasCancelled = false;
1004    private boolean shouldInterrupt = true;
1005    private final AtomicInteger incompleteOutputCount;
1006    // We set the elements of the array to null as they complete.
1007    private final @Nullable ListenableFuture<? extends T>[] inputFutures;
1008    private volatile int delegateIndex = 0;
1009
1010    private InCompletionOrderState(ListenableFuture<? extends T>[] inputFutures) {
1011      this.inputFutures = inputFutures;
1012      incompleteOutputCount = new AtomicInteger(inputFutures.length);
1013    }
1014
1015    private void recordOutputCancellation(boolean interruptIfRunning) {
1016      wasCancelled = true;
1017      // If all the futures were cancelled with interruption, cancel the input futures
1018      // with interruption; otherwise cancel without
1019      if (!interruptIfRunning) {
1020        shouldInterrupt = false;
1021      }
1022      recordCompletion();
1023    }
1024
1025    private void recordInputCompletion(
1026        ImmutableList<AbstractFuture<T>> delegates, int inputFutureIndex) {
1027      /*
1028       * requireNonNull is safe because we accepted an Iterable of non-null Future instances, and we
1029       * don't overwrite an element in the array until after reading it.
1030       */
1031      ListenableFuture<? extends T> inputFuture = requireNonNull(inputFutures[inputFutureIndex]);
1032      // Null out our reference to this future, so it can be GCed
1033      inputFutures[inputFutureIndex] = null;
1034      for (int i = delegateIndex; i < delegates.size(); i++) {
1035        if (delegates.get(i).setFuture(inputFuture)) {
1036          recordCompletion();
1037          // this is technically unnecessary, but should speed up later accesses
1038          delegateIndex = i + 1;
1039          return;
1040        }
1041      }
1042      // If all the delegates were complete, no reason for the next listener to have to
1043      // go through the whole list. Avoids O(n^2) behavior when the entire output list is
1044      // cancelled.
1045      delegateIndex = delegates.size();
1046    }
1047
1048    private void recordCompletion() {
1049      if (incompleteOutputCount.decrementAndGet() == 0 && wasCancelled) {
1050        for (ListenableFuture<? extends T> toCancel : inputFutures) {
1051          if (toCancel != null) {
1052            toCancel.cancel(shouldInterrupt);
1053          }
1054        }
1055      }
1056    }
1057  }
1058
1059  /**
1060   * Registers separate success and failure callbacks to be run when the {@code Future}'s
1061   * computation is {@linkplain java.util.concurrent.Future#isDone() complete} or, if the
1062   * computation is already complete, immediately.
1063   *
1064   * <p>The callback is run on {@code executor}. There is no guaranteed ordering of execution of
1065   * callbacks, but any callback added through this method is guaranteed to be called once the
1066   * computation is complete.
1067   *
1068   * <p>Exceptions thrown by a {@code callback} will be propagated up to the executor. Any exception
1069   * thrown during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an
1070   * exception thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught
1071   * and logged.
1072   *
1073   * <p>Example:
1074   *
1075   * <pre>{@code
1076   * ListenableFuture<QueryResult> future = ...;
1077   * Executor e = ...
1078   * addCallback(future,
1079   *     new FutureCallback<QueryResult>() {
1080   *       public void onSuccess(QueryResult result) {
1081   *         storeInCache(result);
1082   *       }
1083   *       public void onFailure(Throwable t) {
1084   *         reportError(t);
1085   *       }
1086   *     }, e);
1087   * }</pre>
1088   *
1089   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
1090   * the warnings the {@link MoreExecutors#directExecutor} documentation.
1091   *
1092   * <p>For a more general interface to attach a completion listener to a {@code Future}, see {@link
1093   * ListenableFuture#addListener addListener}.
1094   *
1095   * @param future The future attach the callback to.
1096   * @param callback The callback to invoke when {@code future} is completed.
1097   * @param executor The executor to run {@code callback} when the future completes.
1098   * @since 10.0
1099   */
1100  public static <V extends @Nullable Object> void addCallback(
1101      final ListenableFuture<V> future,
1102      final FutureCallback<? super V> callback,
1103      Executor executor) {
1104    Preconditions.checkNotNull(callback);
1105    future.addListener(new CallbackListener<V>(future, callback), executor);
1106  }
1107
1108  /** See {@link #addCallback(ListenableFuture, FutureCallback, Executor)} for behavioral notes. */
1109  private static final class CallbackListener<V extends @Nullable Object> implements Runnable {
1110    final Future<V> future;
1111    final FutureCallback<? super V> callback;
1112
1113    CallbackListener(Future<V> future, FutureCallback<? super V> callback) {
1114      this.future = future;
1115      this.callback = callback;
1116    }
1117
1118    @Override
1119    public void run() {
1120      if (future instanceof InternalFutureFailureAccess) {
1121        Throwable failure =
1122            InternalFutures.tryInternalFastPathGetFailure((InternalFutureFailureAccess) future);
1123        if (failure != null) {
1124          callback.onFailure(failure);
1125          return;
1126        }
1127      }
1128      final V value;
1129      try {
1130        value = getDone(future);
1131      } catch (ExecutionException e) {
1132        callback.onFailure(e.getCause());
1133        return;
1134      } catch (RuntimeException | Error e) {
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}) and calling the constructor via
1211   * reflection. If the exception did not already have a cause, one is set by calling {@link
1212   * Throwable#initCause(Throwable)} on it. If no such constructor exists, an {@code
1213   * 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  @Beta
1227  @CanIgnoreReturnValue
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}) and calling the constructor via
1263   * reflection. If the exception did not already have a cause, one is set by calling {@link
1264   * Throwable#initCause(Throwable)} on it. If no such constructor exists, an {@code
1265   * 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 28.0
1277   */
1278  @Beta
1279  @CanIgnoreReturnValue
1280  @GwtIncompatible // reflection
1281  @ParametricNullness
1282  public static <V extends @Nullable Object, X extends Exception> V getChecked(
1283      Future<V> future, Class<X> exceptionClass, Duration timeout) throws X {
1284    return getChecked(future, exceptionClass, toNanosSaturated(timeout), TimeUnit.NANOSECONDS);
1285  }
1286
1287  /**
1288   * Returns the result of {@link Future#get(long, TimeUnit)}, converting most exceptions to a new
1289   * instance of the given checked exception type. This reduces boilerplate for a common use of
1290   * {@code Future} in which it is unnecessary to programmatically distinguish between exception
1291   * types or to extract other information from the exception instance.
1292   *
1293   * <p>Exceptions from {@code Future.get} are treated as follows:
1294   *
1295   * <ul>
1296   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1297   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1298   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1299   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1300   *       interrupt).
1301   *   <li>Any {@link TimeoutException} is wrapped in an {@code X}.
1302   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1303   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1304   *       exceptions).
1305   * </ul>
1306   *
1307   * <p>The overall principle is to continue to treat every checked exception as a checked
1308   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1309   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1310   * new stack trace matches that of the current thread.
1311   *
1312   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1313   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1314   * (preferring constructors with at least one {@code String}) and calling the constructor via
1315   * reflection. If the exception did not already have a cause, one is set by calling {@link
1316   * Throwable#initCause(Throwable)} on it. If no such constructor exists, an {@code
1317   * IllegalArgumentException} is thrown.
1318   *
1319   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1320   *     whose cause is not itself a checked exception
1321   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1322   *     {@code RuntimeException} as its cause
1323   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1324   *     Error} as its cause
1325   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1326   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1327   *     does not have a suitable constructor
1328   * @since 19.0 (in 10.0 as {@code get} and with different parameter order)
1329   */
1330  @Beta
1331  @CanIgnoreReturnValue
1332  @GwtIncompatible // reflection
1333  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
1334  @ParametricNullness
1335  public static <V extends @Nullable Object, X extends Exception> V getChecked(
1336      Future<V> future, Class<X> exceptionClass, long timeout, TimeUnit unit) throws X {
1337    return FuturesGetChecked.getChecked(future, exceptionClass, timeout, unit);
1338  }
1339
1340  /**
1341   * Returns the result of calling {@link Future#get()} uninterruptibly on a task known not to throw
1342   * a checked exception. This makes {@code Future} more suitable for lightweight, fast-running
1343   * tasks that, barring bugs in the code, will not fail. This gives it exception-handling behavior
1344   * similar to that of {@code ForkJoinTask.join}.
1345   *
1346   * <p>Exceptions from {@code Future.get} are treated as follows:
1347   *
1348   * <ul>
1349   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@link
1350   *       UncheckedExecutionException} (if the cause is an {@code Exception}) or {@link
1351   *       ExecutionError} (if the cause is an {@code Error}).
1352   *   <li>Any {@link InterruptedException} causes a retry of the {@code get} call. The interrupt is
1353   *       restored before {@code getUnchecked} returns.
1354   *   <li>Any {@link CancellationException} is propagated untouched. So is any other {@link
1355   *       RuntimeException} ({@code get} implementations are discouraged from throwing such
1356   *       exceptions).
1357   * </ul>
1358   *
1359   * <p>The overall principle is to eliminate all checked exceptions: to loop to avoid {@code
1360   * InterruptedException}, to pass through {@code CancellationException}, and to wrap any exception
1361   * from the underlying computation in an {@code UncheckedExecutionException} or {@code
1362   * ExecutionError}.
1363   *
1364   * <p>For an uninterruptible {@code get} that preserves other exceptions, see {@link
1365   * Uninterruptibles#getUninterruptibly(Future)}.
1366   *
1367   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with an
1368   *     {@code Exception} as its cause
1369   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1370   *     Error} as its cause
1371   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1372   * @since 10.0
1373   */
1374  @CanIgnoreReturnValue
1375  @ParametricNullness
1376  public static <V extends @Nullable Object> V getUnchecked(Future<V> future) {
1377    checkNotNull(future);
1378    try {
1379      return getUninterruptibly(future);
1380    } catch (ExecutionException e) {
1381      wrapAndThrowUnchecked(e.getCause());
1382      throw new AssertionError();
1383    }
1384  }
1385
1386  private static void wrapAndThrowUnchecked(Throwable cause) {
1387    if (cause instanceof Error) {
1388      throw new ExecutionError((Error) cause);
1389    }
1390    /*
1391     * It's an Exception. (Or it's a non-Error, non-Exception Throwable. From my survey of such
1392     * classes, I believe that most users intended to extend Exception, so we'll treat it like an
1393     * Exception.)
1394     */
1395    throw new UncheckedExecutionException(cause);
1396  }
1397
1398  /*
1399   * Arguably we don't need a timed getUnchecked because any operation slow enough to require a
1400   * timeout is heavyweight enough to throw a checked exception and therefore be inappropriate to
1401   * use with getUnchecked. Further, it's not clear that converting the checked TimeoutException to
1402   * a RuntimeException -- especially to an UncheckedExecutionException, since it wasn't thrown by
1403   * the computation -- makes sense, and if we don't convert it, the user still has to write a
1404   * try-catch block.
1405   *
1406   * If you think you would use this method, let us know. You might also look into the
1407   * Fork-Join framework: http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html
1408   */
1409}