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