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