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