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