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