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