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