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