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 (Throwable t) {
514          // Any Exception is either a RuntimeException or sneaky checked exception.
515          throw new ExecutionException(t);
516        }
517      }
518    };
519  }
520
521  /**
522   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
523   * input futures, if all succeed.
524   *
525   * <p>The list of results is in the same order as the input list.
526   *
527   * <p>This differs from {@link #successfulAsList(ListenableFuture[])} in that it will return a
528   * failed future if any of the items fails.
529   *
530   * <p>Canceling this future will attempt to cancel all the component futures, and if any of the
531   * provided futures fails or is canceled, this one is, too.
532   *
533   * @param futures futures to combine
534   * @return a future that provides a list of the results of the component futures
535   * @since 10.0
536   */
537  @SafeVarargs
538  public static <V extends @Nullable Object> ListenableFuture<List<V>> allAsList(
539      ListenableFuture<? extends V>... futures) {
540    ListenableFuture<List<@Nullable V>> nullable =
541        new ListFuture<V>(ImmutableList.copyOf(futures), true);
542    // allAsList ensures that it fills the output list with V instances.
543    @SuppressWarnings("nullness")
544    ListenableFuture<List<V>> nonNull = nullable;
545    return nonNull;
546  }
547
548  /**
549   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
550   * input futures, if all succeed.
551   *
552   * <p>The list of results is in the same order as the input list.
553   *
554   * <p>This differs from {@link #successfulAsList(Iterable)} in that it will return a failed future
555   * if any of the items fails.
556   *
557   * <p>Canceling this future will attempt to cancel all the component futures, and if any of the
558   * provided futures fails or is canceled, this one is, too.
559   *
560   * @param futures futures to combine
561   * @return a future that provides a list of the results of the component futures
562   * @since 10.0
563   */
564  public static <V extends @Nullable Object> ListenableFuture<List<V>> allAsList(
565      Iterable<? extends ListenableFuture<? extends V>> futures) {
566    ListenableFuture<List<@Nullable V>> nullable =
567        new ListFuture<V>(ImmutableList.copyOf(futures), true);
568    // allAsList ensures that it fills the output list with V instances.
569    @SuppressWarnings("nullness")
570    ListenableFuture<List<V>> nonNull = nullable;
571    return nonNull;
572  }
573
574  /**
575   * Creates a {@link FutureCombiner} that processes the completed futures whether or not they're
576   * successful.
577   *
578   * <p>Any failures from the input futures will not be propagated to the returned future.
579   *
580   * @since 20.0
581   */
582  @SafeVarargs
583  public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
584      ListenableFuture<? extends V>... futures) {
585    return new FutureCombiner<V>(false, ImmutableList.copyOf(futures));
586  }
587
588  /**
589   * Creates a {@link FutureCombiner} that processes the completed futures whether or not they're
590   * successful.
591   *
592   * <p>Any failures from the input futures will not be propagated to the returned future.
593   *
594   * @since 20.0
595   */
596  public static <V extends @Nullable Object> FutureCombiner<V> whenAllComplete(
597      Iterable<? extends ListenableFuture<? extends V>> futures) {
598    return new FutureCombiner<V>(false, ImmutableList.copyOf(futures));
599  }
600
601  /**
602   * Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
603   *
604   * <p>If any input fails, the returned future fails immediately.
605   *
606   * @since 20.0
607   */
608  @SafeVarargs
609  public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
610      ListenableFuture<? extends V>... futures) {
611    return new FutureCombiner<V>(true, ImmutableList.copyOf(futures));
612  }
613
614  /**
615   * Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
616   *
617   * <p>If any input fails, the returned future fails immediately.
618   *
619   * @since 20.0
620   */
621  public static <V extends @Nullable Object> FutureCombiner<V> whenAllSucceed(
622      Iterable<? extends ListenableFuture<? extends V>> futures) {
623    return new FutureCombiner<V>(true, ImmutableList.copyOf(futures));
624  }
625
626  /**
627   * A helper to create a new {@code ListenableFuture} whose result is generated from a combination
628   * of input futures.
629   *
630   * <p>See {@link #whenAllComplete} and {@link #whenAllSucceed} for how to instantiate this class.
631   *
632   * <p>Example:
633   *
634   * <pre>{@code
635   * final ListenableFuture<Instant> loginDateFuture =
636   *     loginService.findLastLoginDate(username);
637   * final ListenableFuture<List<String>> recentCommandsFuture =
638   *     recentCommandsService.findRecentCommands(username);
639   * ListenableFuture<UsageHistory> usageFuture =
640   *     Futures.whenAllSucceed(loginDateFuture, recentCommandsFuture)
641   *         .call(
642   *             () ->
643   *                 new UsageHistory(
644   *                     username,
645   *                     Futures.getDone(loginDateFuture),
646   *                     Futures.getDone(recentCommandsFuture)),
647   *             executor);
648   * }</pre>
649   *
650   * @since 20.0
651   */
652  @GwtCompatible
653  public static final class FutureCombiner<V extends @Nullable Object> {
654    private final boolean allMustSucceed;
655    private final ImmutableList<ListenableFuture<? extends V>> futures;
656
657    private FutureCombiner(
658        boolean allMustSucceed, ImmutableList<ListenableFuture<? extends V>> futures) {
659      this.allMustSucceed = allMustSucceed;
660      this.futures = futures;
661    }
662
663    /**
664     * Creates the {@link ListenableFuture} which will return the result of calling {@link
665     * AsyncCallable#call} in {@code combiner} when all futures complete, using the specified {@code
666     * executor}.
667     *
668     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
669     * cancelled.
670     *
671     * <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code
672     * ExecutionException} will be extracted and returned as the cause of the new {@code
673     * ExecutionException} that gets thrown by the returned combined future.
674     *
675     * <p>Canceling this future will attempt to cancel all the component futures.
676     *
677     * @return a future whose result is based on {@code combiner} (or based on the input futures
678     *     passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
679     *     FutureCombiner}). Even if you don't care about the value of the future, you should
680     *     typically check whether it failed: See <a
681     *     href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
682     */
683    public <C extends @Nullable Object> ListenableFuture<C> callAsync(
684        AsyncCallable<C> combiner, Executor executor) {
685      return new CombinedFuture<C>(futures, allMustSucceed, executor, combiner);
686    }
687
688    /**
689     * Creates the {@link ListenableFuture} which will return the result of calling {@link
690     * Callable#call} in {@code combiner} when all futures complete, using the specified {@code
691     * executor}.
692     *
693     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
694     * cancelled.
695     *
696     * <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code
697     * ExecutionException} will be extracted and returned as the cause of the new {@code
698     * ExecutionException} that gets thrown by the returned combined future.
699     *
700     * <p>Canceling this future will attempt to cancel all the component futures.
701     *
702     * @return a future whose result is based on {@code combiner} (or based on the input futures
703     *     passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
704     *     FutureCombiner}). Even if you don't care about the value of the future, you should
705     *     typically check whether it failed: See <a
706     *     href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
707     */
708    public <C extends @Nullable Object> ListenableFuture<C> call(
709        Callable<C> combiner, Executor executor) {
710      return new CombinedFuture<C>(futures, allMustSucceed, executor, combiner);
711    }
712
713    /**
714     * Creates the {@link ListenableFuture} which will return the result of running {@code combiner}
715     * when all Futures complete. {@code combiner} will run using {@code executor}.
716     *
717     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
718     * cancelled.
719     *
720     * <p>Canceling this Future will attempt to cancel all the component futures.
721     *
722     * @since 23.6
723     * @return a future whose result is based on {@code combiner} (or based on the input futures
724     *     passed to {@code whenAllSucceed}, if that is the method you used to create this {@code
725     *     FutureCombiner}). Even though the future never produces a value other than {@code null},
726     *     you should typically check whether it failed: See <a
727     *     href="https://errorprone.info/bugpattern/FutureReturnValueIgnored">https://errorprone.info/bugpattern/FutureReturnValueIgnored</a>.
728     */
729    public ListenableFuture<?> run(final Runnable combiner, Executor executor) {
730      return call(
731          new Callable<@Nullable Void>() {
732            @Override
733            @CheckForNull
734            public Void call() throws Exception {
735              combiner.run();
736              return null;
737            }
738          },
739          executor);
740    }
741  }
742
743  /**
744   * Returns a {@code ListenableFuture} whose result is set from the supplied future when it
745   * completes. Cancelling the supplied future will also cancel the returned future, but cancelling
746   * the returned future will have no effect on the supplied future.
747   *
748   * @since 15.0
749   */
750  public static <V extends @Nullable Object> ListenableFuture<V> nonCancellationPropagating(
751      ListenableFuture<V> future) {
752    if (future.isDone()) {
753      return future;
754    }
755    NonCancellationPropagatingFuture<V> output = new NonCancellationPropagatingFuture<>(future);
756    future.addListener(output, directExecutor());
757    return output;
758  }
759
760  /** A wrapped future that does not propagate cancellation to its delegate. */
761  private static final class NonCancellationPropagatingFuture<V extends @Nullable Object>
762      extends AbstractFuture.TrustedFuture<V> implements Runnable {
763    @CheckForNull private ListenableFuture<V> delegate;
764
765    NonCancellationPropagatingFuture(final ListenableFuture<V> delegate) {
766      this.delegate = delegate;
767    }
768
769    @Override
770    public void run() {
771      // This prevents cancellation from propagating because we don't call setFuture(delegate) until
772      // delegate is already done, so calling cancel() on this future won't affect it.
773      ListenableFuture<V> localDelegate = delegate;
774      if (localDelegate != null) {
775        setFuture(localDelegate);
776      }
777    }
778
779    @Override
780    @CheckForNull
781    protected String pendingToString() {
782      ListenableFuture<V> localDelegate = delegate;
783      if (localDelegate != null) {
784        return "delegate=[" + localDelegate + "]";
785      }
786      return null;
787    }
788
789    @Override
790    protected void afterDone() {
791      delegate = null;
792    }
793  }
794
795  /**
796   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
797   * successful input futures. The list of results is in the same order as the input list, and if
798   * any of the provided futures fails or is canceled, its corresponding position will contain
799   * {@code null} (which is indistinguishable from the future having a successful value of {@code
800   * null}).
801   *
802   * <p>The list of results is in the same order as the input list.
803   *
804   * <p>This differs from {@link #allAsList(ListenableFuture[])} in that it's tolerant of failed
805   * futures for any of the items, representing them as {@code null} in the result list.
806   *
807   * <p>Canceling this future will attempt to cancel all the component futures.
808   *
809   * @param futures futures to combine
810   * @return a future that provides a list of the results of the component futures
811   * @since 10.0
812   */
813  @SafeVarargs
814  public static <V extends @Nullable Object> ListenableFuture<List<@Nullable V>> successfulAsList(
815      ListenableFuture<? extends V>... futures) {
816    /*
817     * Another way to express this signature would be to bound <V> by @NonNull and accept
818     * LF<? extends @Nullable V>. That might be better: There's currently no difference between the
819     * outputs users get when calling this with <Foo> and calling it with <@Nullable Foo>. The only
820     * difference is that calling it with <Foo> won't work when an input Future has a @Nullable
821     * type. So why even make that error possible by giving callers the choice?
822     *
823     * On the other hand, the current signature is consistent with the similar allAsList method. And
824     * eventually this method may go away entirely in favor of an API like
825     * whenAllComplete().collectSuccesses(). That API would have a signature more like the current
826     * one.
827     */
828    return new ListFuture<V>(ImmutableList.copyOf(futures), false);
829  }
830
831  /**
832   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
833   * successful input futures. The list of results is in the same order as the input list, and if
834   * any of the provided futures fails or is canceled, its corresponding position will contain
835   * {@code null} (which is indistinguishable from the future having a successful value of {@code
836   * null}).
837   *
838   * <p>The list of results is in the same order as the input list.
839   *
840   * <p>This differs from {@link #allAsList(Iterable)} in that it's tolerant of failed futures for
841   * any of the items, representing them as {@code null} in the result list.
842   *
843   * <p>Canceling this future will attempt to cancel all the component futures.
844   *
845   * @param futures futures to combine
846   * @return a future that provides a list of the results of the component futures
847   * @since 10.0
848   */
849  public static <V extends @Nullable Object> ListenableFuture<List<@Nullable V>> successfulAsList(
850      Iterable<? extends ListenableFuture<? extends V>> futures) {
851    return new ListFuture<V>(ImmutableList.copyOf(futures), false);
852  }
853
854  /**
855   * Returns a list of delegate futures that correspond to the futures received in the order that
856   * they complete. Delegate futures return the same value or throw the same exception as the
857   * corresponding input future returns/throws.
858   *
859   * <p>"In the order that they complete" means, for practical purposes, about what you would
860   * expect, but there are some subtleties. First, we do guarantee that, if the output future at
861   * index n is done, the output future at index n-1 is also done. (But as usual with futures, some
862   * listeners for future n may complete before some for future n-1.) However, it is possible, if
863   * one input completes with result X and another later with result Y, for Y to come before X in
864   * the output future list. (Such races are impossible to solve without global synchronization of
865   * all future completions. And they should have little practical impact.)
866   *
867   * <p>Cancelling a delegate future propagates to input futures once all the delegates complete,
868   * either from cancellation or because an input future has completed. If N futures are passed in,
869   * and M delegates are cancelled, the remaining M input futures will be cancelled once N - M of
870   * the input futures complete. If all the delegates are cancelled, all the input futures will be
871   * too.
872   *
873   * @since 17.0
874   */
875  public static <T extends @Nullable Object> ImmutableList<ListenableFuture<T>> inCompletionOrder(
876      Iterable<? extends ListenableFuture<? extends T>> futures) {
877    ListenableFuture<? extends T>[] copy = gwtCompatibleToArray(futures);
878    final InCompletionOrderState<T> state = new InCompletionOrderState<>(copy);
879    ImmutableList.Builder<AbstractFuture<T>> delegatesBuilder =
880        ImmutableList.builderWithExpectedSize(copy.length);
881    for (int i = 0; i < copy.length; i++) {
882      delegatesBuilder.add(new InCompletionOrderFuture<T>(state));
883    }
884
885    final ImmutableList<AbstractFuture<T>> delegates = delegatesBuilder.build();
886    for (int i = 0; i < copy.length; i++) {
887      final int localI = i;
888      copy[i].addListener(() -> state.recordInputCompletion(delegates, localI), directExecutor());
889    }
890
891    @SuppressWarnings("unchecked")
892    ImmutableList<ListenableFuture<T>> delegatesCast = (ImmutableList) delegates;
893    return delegatesCast;
894  }
895
896  /** Can't use Iterables.toArray because it's not gwt compatible */
897  @SuppressWarnings("unchecked")
898  private static <T extends @Nullable Object> ListenableFuture<? extends T>[] gwtCompatibleToArray(
899      Iterable<? extends ListenableFuture<? extends T>> futures) {
900    final Collection<ListenableFuture<? extends T>> collection;
901    if (futures instanceof Collection) {
902      collection = (Collection<ListenableFuture<? extends T>>) futures;
903    } else {
904      collection = ImmutableList.copyOf(futures);
905    }
906    return (ListenableFuture<? extends T>[]) collection.toArray(new ListenableFuture<?>[0]);
907  }
908
909  // This can't be a TrustedFuture, because TrustedFuture has clever optimizations that
910  // mean cancel won't be called if this Future is passed into setFuture, and then
911  // cancelled.
912  private static final class InCompletionOrderFuture<T extends @Nullable Object>
913      extends AbstractFuture<T> {
914    @CheckForNull private InCompletionOrderState<T> state;
915
916    private InCompletionOrderFuture(InCompletionOrderState<T> state) {
917      this.state = state;
918    }
919
920    @Override
921    public boolean cancel(boolean interruptIfRunning) {
922      InCompletionOrderState<T> localState = state;
923      if (super.cancel(interruptIfRunning)) {
924        /*
925         * requireNonNull is generally safe: If cancel succeeded, then this Future was still
926         * pending, so its `state` field hasn't been nulled out yet.
927         *
928         * OK, it's technically possible for this to fail in the presence of unsafe publishing, as
929         * discussed in the comments in TimeoutFuture. TODO(cpovirk): Maybe check for null before
930         * calling recordOutputCancellation?
931         */
932        requireNonNull(localState).recordOutputCancellation(interruptIfRunning);
933        return true;
934      }
935      return false;
936    }
937
938    @Override
939    protected void afterDone() {
940      state = null;
941    }
942
943    @Override
944    @CheckForNull
945    protected String pendingToString() {
946      InCompletionOrderState<T> localState = state;
947      if (localState != null) {
948        // Don't print the actual array! We don't want inCompletionOrder(list).toString() to have
949        // quadratic output.
950        return "inputCount=["
951            + localState.inputFutures.length
952            + "], remaining=["
953            + localState.incompleteOutputCount.get()
954            + "]";
955      }
956      return null;
957    }
958  }
959
960  private static final class InCompletionOrderState<T extends @Nullable Object> {
961    // A happens-before edge between the writes of these fields and their reads exists, because
962    // in order to read these fields, the corresponding write to incompleteOutputCount must have
963    // been read.
964    private boolean wasCancelled = false;
965    private boolean shouldInterrupt = true;
966    private final AtomicInteger incompleteOutputCount;
967    // We set the elements of the array to null as they complete.
968    private final @Nullable ListenableFuture<? extends T>[] inputFutures;
969    private volatile int delegateIndex = 0;
970
971    private InCompletionOrderState(ListenableFuture<? extends T>[] inputFutures) {
972      this.inputFutures = inputFutures;
973      incompleteOutputCount = new AtomicInteger(inputFutures.length);
974    }
975
976    private void recordOutputCancellation(boolean interruptIfRunning) {
977      wasCancelled = true;
978      // If all the futures were cancelled with interruption, cancel the input futures
979      // with interruption; otherwise cancel without
980      if (!interruptIfRunning) {
981        shouldInterrupt = false;
982      }
983      recordCompletion();
984    }
985
986    private void recordInputCompletion(
987        ImmutableList<AbstractFuture<T>> delegates, int inputFutureIndex) {
988      /*
989       * requireNonNull is safe because we accepted an Iterable of non-null Future instances, and we
990       * don't overwrite an element in the array until after reading it.
991       */
992      ListenableFuture<? extends T> inputFuture = requireNonNull(inputFutures[inputFutureIndex]);
993      // Null out our reference to this future, so it can be GCed
994      inputFutures[inputFutureIndex] = null;
995      for (int i = delegateIndex; i < delegates.size(); i++) {
996        if (delegates.get(i).setFuture(inputFuture)) {
997          recordCompletion();
998          // this is technically unnecessary, but should speed up later accesses
999          delegateIndex = i + 1;
1000          return;
1001        }
1002      }
1003      // If all the delegates were complete, no reason for the next listener to have to
1004      // go through the whole list. Avoids O(n^2) behavior when the entire output list is
1005      // cancelled.
1006      delegateIndex = delegates.size();
1007    }
1008
1009    private void recordCompletion() {
1010      if (incompleteOutputCount.decrementAndGet() == 0 && wasCancelled) {
1011        for (ListenableFuture<? extends T> toCancel : inputFutures) {
1012          if (toCancel != null) {
1013            toCancel.cancel(shouldInterrupt);
1014          }
1015        }
1016      }
1017    }
1018  }
1019
1020  /**
1021   * Registers separate success and failure callbacks to be run when the {@code Future}'s
1022   * computation is {@linkplain java.util.concurrent.Future#isDone() complete} or, if the
1023   * computation is already complete, immediately.
1024   *
1025   * <p>The callback is run on {@code executor}. There is no guaranteed ordering of execution of
1026   * callbacks, but any callback added through this method is guaranteed to be called once the
1027   * computation is complete.
1028   *
1029   * <p>Exceptions thrown by a {@code callback} will be propagated up to the executor. Any exception
1030   * thrown during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an
1031   * exception thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught
1032   * and logged.
1033   *
1034   * <p>Example:
1035   *
1036   * <pre>{@code
1037   * ListenableFuture<QueryResult> future = ...;
1038   * Executor e = ...
1039   * addCallback(future,
1040   *     new FutureCallback<QueryResult>() {
1041   *       public void onSuccess(QueryResult result) {
1042   *         storeInCache(result);
1043   *       }
1044   *       public void onFailure(Throwable t) {
1045   *         reportError(t);
1046   *       }
1047   *     }, e);
1048   * }</pre>
1049   *
1050   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
1051   * the warnings the {@link MoreExecutors#directExecutor} documentation.
1052   *
1053   * <p>For a more general interface to attach a completion listener to a {@code Future}, see {@link
1054   * ListenableFuture#addListener addListener}.
1055   *
1056   * @param future The future attach the callback to.
1057   * @param callback The callback to invoke when {@code future} is completed.
1058   * @param executor The executor to run {@code callback} when the future completes.
1059   * @since 10.0
1060   */
1061  public static <V extends @Nullable Object> void addCallback(
1062      final ListenableFuture<V> future,
1063      final FutureCallback<? super V> callback,
1064      Executor executor) {
1065    Preconditions.checkNotNull(callback);
1066    future.addListener(new CallbackListener<V>(future, callback), executor);
1067  }
1068
1069  /** See {@link #addCallback(ListenableFuture, FutureCallback, Executor)} for behavioral notes. */
1070  private static final class CallbackListener<V extends @Nullable Object> implements Runnable {
1071    final Future<V> future;
1072    final FutureCallback<? super V> callback;
1073
1074    CallbackListener(Future<V> future, FutureCallback<? super V> callback) {
1075      this.future = future;
1076      this.callback = callback;
1077    }
1078
1079    @Override
1080    public void run() {
1081      if (future instanceof InternalFutureFailureAccess) {
1082        Throwable failure =
1083            InternalFutures.tryInternalFastPathGetFailure((InternalFutureFailureAccess) future);
1084        if (failure != null) {
1085          callback.onFailure(failure);
1086          return;
1087        }
1088      }
1089      final V value;
1090      try {
1091        value = getDone(future);
1092      } catch (ExecutionException e) {
1093        callback.onFailure(e.getCause());
1094        return;
1095      } catch (Throwable e) {
1096        // Any Exception is either a RuntimeException or sneaky checked exception.
1097        callback.onFailure(e);
1098        return;
1099      }
1100      callback.onSuccess(value);
1101    }
1102
1103    @Override
1104    public String toString() {
1105      return MoreObjects.toStringHelper(this).addValue(callback).toString();
1106    }
1107  }
1108
1109  /**
1110   * Returns the result of the input {@code Future}, which must have already completed.
1111   *
1112   * <p>The benefits of this method are twofold. First, the name "getDone" suggests to readers that
1113   * the {@code Future} is already done. Second, if buggy code calls {@code getDone} on a {@code
1114   * Future} that is still pending, the program will throw instead of block. This can be important
1115   * for APIs like {@link #whenAllComplete whenAllComplete(...)}{@code .}{@link
1116   * FutureCombiner#call(Callable, Executor) call(...)}, where it is easy to use a new input from
1117   * the {@code call} implementation but forget to add it to the arguments of {@code
1118   * whenAllComplete}.
1119   *
1120   * <p>If you are looking for a method to determine whether a given {@code Future} is done, use the
1121   * instance method {@link Future#isDone()}.
1122   *
1123   * @throws ExecutionException if the {@code Future} failed with an exception
1124   * @throws CancellationException if the {@code Future} was cancelled
1125   * @throws IllegalStateException if the {@code Future} is not done
1126   * @since 20.0
1127   */
1128  @CanIgnoreReturnValue
1129  // TODO(cpovirk): Consider calling getDone() in our own code.
1130  @ParametricNullness
1131  public static <V extends @Nullable Object> V getDone(Future<V> future) throws ExecutionException {
1132    /*
1133     * We throw IllegalStateException, since the call could succeed later. Perhaps we "should" throw
1134     * IllegalArgumentException, since the call could succeed with a different argument. Those
1135     * exceptions' docs suggest that either is acceptable. Google's Java Practices page recommends
1136     * IllegalArgumentException here, in part to keep its recommendation simple: Static methods
1137     * should throw IllegalStateException only when they use static state.
1138     *
1139     * Why do we deviate here? The answer: We want for fluentFuture.getDone() to throw the same
1140     * exception as Futures.getDone(fluentFuture).
1141     */
1142    checkState(future.isDone(), "Future was expected to be done: %s", future);
1143    return getUninterruptibly(future);
1144  }
1145
1146  /**
1147   * Returns the result of {@link Future#get()}, converting most exceptions to a new instance of the
1148   * given checked exception type. This reduces boilerplate for a common use of {@code Future} in
1149   * which it is unnecessary to programmatically distinguish between exception types or to extract
1150   * other information from the exception instance.
1151   *
1152   * <p>Exceptions from {@code Future.get} are treated as follows:
1153   *
1154   * <ul>
1155   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1156   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1157   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1158   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1159   *       interrupt).
1160   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1161   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1162   *       exceptions).
1163   * </ul>
1164   *
1165   * <p>The overall principle is to continue to treat every checked exception as a checked
1166   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1167   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1168   * new stack trace matches that of the current thread.
1169   *
1170   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1171   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1172   * (preferring constructors with at least one {@code String}, then preferring constructors with at
1173   * least one {@code Throwable}) and calling the constructor via reflection. If the exception did
1174   * not already have a cause, one is set by calling {@link Throwable#initCause(Throwable)} on it.
1175   * If no such constructor exists, an {@code IllegalArgumentException} is thrown.
1176   *
1177   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1178   *     whose cause is not itself a checked exception
1179   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1180   *     {@code RuntimeException} as its cause
1181   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1182   *     Error} as its cause
1183   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1184   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1185   *     does not have a suitable constructor
1186   * @since 19.0 (in 10.0 as {@code get})
1187   */
1188  @CanIgnoreReturnValue
1189  @J2ktIncompatible
1190  @GwtIncompatible // reflection
1191  @ParametricNullness
1192  public static <V extends @Nullable Object, X extends Exception> V getChecked(
1193      Future<V> future, Class<X> exceptionClass) throws X {
1194    return FuturesGetChecked.getChecked(future, exceptionClass);
1195  }
1196
1197  /**
1198   * Returns the result of {@link Future#get(long, TimeUnit)}, converting most exceptions to a new
1199   * instance of the given checked exception type. This reduces boilerplate for a common use of
1200   * {@code Future} in which it is unnecessary to programmatically distinguish between exception
1201   * types or to extract other information from the exception instance.
1202   *
1203   * <p>Exceptions from {@code Future.get} are treated as follows:
1204   *
1205   * <ul>
1206   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1207   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1208   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1209   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1210   *       interrupt).
1211   *   <li>Any {@link TimeoutException} is wrapped in an {@code X}.
1212   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1213   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1214   *       exceptions).
1215   * </ul>
1216   *
1217   * <p>The overall principle is to continue to treat every checked exception as a checked
1218   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1219   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1220   * new stack trace matches that of the current thread.
1221   *
1222   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1223   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1224   * (preferring constructors with at least one {@code String}, then preferring constructors with at
1225   * least one {@code Throwable}) and calling the constructor via reflection. If the exception did
1226   * not already have a cause, one is set by calling {@link Throwable#initCause(Throwable)} on it.
1227   * If no such constructor exists, an {@code IllegalArgumentException} is thrown.
1228   *
1229   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1230   *     whose cause is not itself a checked exception
1231   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1232   *     {@code RuntimeException} as its cause
1233   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1234   *     Error} as its cause
1235   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1236   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1237   *     does not have a suitable constructor
1238   * @since 19.0 (in 10.0 as {@code get} and with different parameter order)
1239   */
1240  @CanIgnoreReturnValue
1241  @J2ktIncompatible
1242  @GwtIncompatible // reflection
1243  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
1244  @ParametricNullness
1245  public static <V extends @Nullable Object, X extends Exception> V getChecked(
1246      Future<V> future, Class<X> exceptionClass, long timeout, TimeUnit unit) throws X {
1247    return FuturesGetChecked.getChecked(future, exceptionClass, timeout, unit);
1248  }
1249
1250  /**
1251   * Returns the result of calling {@link Future#get()} uninterruptibly on a task known not to throw
1252   * a checked exception. This makes {@code Future} more suitable for lightweight, fast-running
1253   * tasks that, barring bugs in the code, will not fail. This gives it exception-handling behavior
1254   * similar to that of {@code ForkJoinTask.join}.
1255   *
1256   * <p>Exceptions from {@code Future.get} are treated as follows:
1257   *
1258   * <ul>
1259   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@link
1260   *       UncheckedExecutionException} (if the cause is an {@code Exception}) or {@link
1261   *       ExecutionError} (if the cause is an {@code Error}).
1262   *   <li>Any {@link InterruptedException} causes a retry of the {@code get} call. The interrupt is
1263   *       restored before {@code getUnchecked} returns.
1264   *   <li>Any {@link CancellationException} is propagated untouched. So is any other {@link
1265   *       RuntimeException} ({@code get} implementations are discouraged from throwing such
1266   *       exceptions).
1267   * </ul>
1268   *
1269   * <p>The overall principle is to eliminate all checked exceptions: to loop to avoid {@code
1270   * InterruptedException}, to pass through {@code CancellationException}, and to wrap any exception
1271   * from the underlying computation in an {@code UncheckedExecutionException} or {@code
1272   * ExecutionError}.
1273   *
1274   * <p>For an uninterruptible {@code get} that preserves other exceptions, see {@link
1275   * Uninterruptibles#getUninterruptibly(Future)}.
1276   *
1277   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with an
1278   *     {@code Exception} as its cause
1279   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1280   *     Error} as its cause
1281   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1282   * @since 10.0
1283   */
1284  @CanIgnoreReturnValue
1285  @ParametricNullness
1286  public static <V extends @Nullable Object> V getUnchecked(Future<V> future) {
1287    checkNotNull(future);
1288    try {
1289      return getUninterruptibly(future);
1290    } catch (ExecutionException e) {
1291      wrapAndThrowUnchecked(e.getCause());
1292      throw new AssertionError();
1293    }
1294  }
1295
1296  private static void wrapAndThrowUnchecked(Throwable cause) {
1297    if (cause instanceof Error) {
1298      throw new ExecutionError((Error) cause);
1299    }
1300    /*
1301     * It's an Exception. (Or it's a non-Error, non-Exception Throwable. From my survey of such
1302     * classes, I believe that most users intended to extend Exception, so we'll treat it like an
1303     * Exception.)
1304     */
1305    throw new UncheckedExecutionException(cause);
1306  }
1307
1308  /*
1309   * Arguably we don't need a timed getUnchecked because any operation slow enough to require a
1310   * timeout is heavyweight enough to throw a checked exception and therefore be inappropriate to
1311   * use with getUnchecked. Further, it's not clear that converting the checked TimeoutException to
1312   * a RuntimeException -- especially to an UncheckedExecutionException, since it wasn't thrown by
1313   * the computation -- makes sense, and if we don't convert it, the user still has to write a
1314   * try-catch block.
1315   *
1316   * If you think you would use this method, let us know. You might also look into the
1317   * Fork-Join framework: http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html
1318   */
1319}