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