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