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