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