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