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 February 2018.
148   */
149  @Deprecated
150  @GwtIncompatible // TODO
151  public static <V, X extends Exception> CheckedFuture<V, X> makeChecked(
152      ListenableFuture<V> future, Function<? super Exception, X> mapper) {
153    return new MappingCheckedFuture<>(checkNotNull(future), mapper);
154  }
155
156  /**
157   * Creates a {@code ListenableFuture} which has its value set immediately upon construction. The
158   * getters just return the value. This {@code Future} can't be canceled or timed out and its
159   * {@code isDone()} method always returns {@code true}.
160   */
161  public static <V> ListenableFuture<V> immediateFuture(@NullableDecl V value) {
162    if (value == null) {
163      // This cast is safe because null is assignable to V for all V (i.e. it is covariant)
164      @SuppressWarnings({"unchecked", "rawtypes"})
165      ListenableFuture<V> typedNull = (ListenableFuture) ImmediateSuccessfulFuture.NULL;
166      return typedNull;
167    }
168    return new ImmediateSuccessfulFuture<V>(value);
169  }
170
171  /**
172   * Returns a {@code CheckedFuture} which has its value set immediately upon construction.
173   *
174   * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()} method always
175   * returns {@code true}. Calling {@code get()} or {@code checkedGet()} will immediately return the
176   * provided value.
177   *
178   * @deprecated {@link CheckedFuture} cannot properly support the chained operations that are the
179   *     primary goal of {@link ListenableFuture}. {@code CheckedFuture} also encourages users to
180   *     rethrow exceptions from one thread in another thread, producing misleading stack traces.
181   *     Additionally, it has a surprising policy about which exceptions to map and which to leave
182   *     untouched. Guava users who want a {@code CheckedFuture} can fork the classes for their own
183   *     use, possibly specializing them to the particular exception type they use. We recommend
184   *     that most people use {@code ListenableFuture} and perform any exception wrapping
185   *     themselves. This method is scheduled for removal from Guava in February 2018.
186   */
187  @Deprecated
188  @GwtIncompatible // TODO
189  public static <V, X extends Exception> CheckedFuture<V, X> immediateCheckedFuture(
190      @NullableDecl V value) {
191    return new ImmediateSuccessfulCheckedFuture<>(value);
192  }
193
194  /**
195   * Returns a {@code ListenableFuture} which has an exception set immediately upon construction.
196   *
197   * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()} method always
198   * returns {@code true}. Calling {@code get()} will immediately throw the provided {@code
199   * Throwable} wrapped in an {@code ExecutionException}.
200   */
201  public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable) {
202    checkNotNull(throwable);
203    return new ImmediateFailedFuture<V>(throwable);
204  }
205
206  /**
207   * Creates a {@code ListenableFuture} which is cancelled immediately upon construction, so that
208   * {@code isCancelled()} always returns {@code true}.
209   *
210   * @since 14.0
211   */
212  public static <V> ListenableFuture<V> immediateCancelledFuture() {
213    return new ImmediateCancelledFuture<V>();
214  }
215
216  /**
217   * Returns a {@code CheckedFuture} which has an exception set immediately upon construction.
218   *
219   * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()} method always
220   * returns {@code true}. Calling {@code get()} will immediately throw the provided {@code
221   * Exception} wrapped in an {@code ExecutionException}, and calling {@code checkedGet()} will
222   * throw the provided exception itself.
223   *
224   * @deprecated {@link CheckedFuture} cannot properly support the chained operations that are the
225   *     primary goal of {@link ListenableFuture}. {@code CheckedFuture} also encourages users to
226   *     rethrow exceptions from one thread in another thread, producing misleading stack traces.
227   *     Additionally, it has a surprising policy about which exceptions to map and which to leave
228   *     untouched. Guava users who want a {@code CheckedFuture} can fork the classes for their own
229   *     use, possibly specializing them to the particular exception type they use. We recommend
230   *     that most people use {@code ListenableFuture} and perform any exception wrapping
231   *     themselves. This method is scheduled for removal from Guava in February 2018.
232   */
233  @Deprecated
234  @GwtIncompatible // TODO
235  public static <V, X extends Exception> CheckedFuture<V, X> immediateFailedCheckedFuture(
236      X exception) {
237    checkNotNull(exception);
238    return new ImmediateFailedCheckedFuture<>(exception);
239  }
240
241  /**
242   * Executes {@code callable} on the specified {@code executor}, returning a {@code Future}.
243   *
244   * @throws RejectedExecutionException if the task cannot be scheduled for execution
245   * @since 23.0
246   */
247  public static <O> ListenableFuture<O> submitAsync(AsyncCallable<O> callable, Executor executor) {
248    TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
249    executor.execute(task);
250    return task;
251  }
252
253  /**
254   * Schedules {@code callable} on the specified {@code executor}, returning a {@code Future}.
255   *
256   * @throws RejectedExecutionException if the task cannot be scheduled for execution
257   * @since 23.0
258   */
259  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
260  public static <O> ListenableFuture<O> scheduleAsync(
261      AsyncCallable<O> callable,
262      long delay,
263      TimeUnit timeUnit,
264      ScheduledExecutorService executorService) {
265    TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
266    final Future<?> scheduled = executorService.schedule(task, delay, timeUnit);
267    task.addListener(
268        new Runnable() {
269          @Override
270          public void run() {
271            // Don't want to interrupt twice
272            scheduled.cancel(false);
273          }
274        },
275        directExecutor());
276    return task;
277  }
278
279  /**
280   * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
281   * primary input fails with the given {@code exceptionType}, from the result provided by the
282   * {@code fallback}. {@link Function#apply} is not invoked until the primary input has failed, so
283   * if the primary input succeeds, it is never invoked. If, during the invocation of {@code
284   * fallback}, an exception is thrown, this exception is used as the result of the output {@code
285   * Future}.
286   *
287   * <p>Usage example:
288   *
289   * <pre>{@code
290   * ListenableFuture<Integer> fetchCounterFuture = ...;
291   *
292   * // Falling back to a zero counter in case an exception happens when
293   * // processing the RPC to fetch counters.
294   * ListenableFuture<Integer> faultTolerantFuture = Futures.catching(
295   *     fetchCounterFuture, FetchException.class, x -> 0);
296   * }</pre>
297   *
298   * <p>This overload, which does not accept an executor, uses {@code directExecutor}, a dangerous
299   * choice in some cases. See the discussion in the {@link ListenableFuture#addListener
300   * ListenableFuture.addListener} documentation. All its warnings about heavyweight listeners are
301   * also applicable to heavyweight functions passed to this method.
302   *
303   * @param input the primary input {@code Future}
304   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
305   *     type is matched against the input's exception. "The input's exception" means the cause of
306   *     the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
307   *     different kind of exception, that exception itself. To avoid hiding bugs and other
308   *     unrecoverable errors, callers should prefer more specific types, avoiding {@code
309   *     Throwable.class} in particular.
310   * @param fallback the {@link Function} to be called if {@code input} fails with the expected
311   *     exception type. The function's argument is the input's exception. "The input's exception"
312   *     means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
313   *     {@code get()} throws a different kind of exception, that exception itself.
314   * @since 19.0
315   * @deprecated Use {@linkplain #catching(ListenableFuture, Class, Function, Executor) the overload
316   *     that requires an executor}. For identical behavior, pass {@link
317   *     MoreExecutors#directExecutor}, but consider whether another executor would be safer, as
318   *     discussed in the {@link ListenableFuture#addListener ListenableFuture.addListener}
319   *     documentation. This method is scheduled to be removed in April 2018.
320   */
321  @Deprecated
322  @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
323  public static <V, X extends Throwable> ListenableFuture<V> catching(
324      ListenableFuture<? extends V> input,
325      Class<X> exceptionType,
326      Function<? super X, ? extends V> fallback) {
327    return AbstractCatchingFuture.create(input, exceptionType, fallback, directExecutor());
328  }
329
330  /**
331   * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
332   * primary input fails with the given {@code exceptionType}, from the result provided by the
333   * {@code fallback}. {@link Function#apply} is not invoked until the primary input has failed, so
334   * if the primary input succeeds, it is never invoked. If, during the invocation of {@code
335   * fallback}, an exception is thrown, this exception is used as the result of the output {@code
336   * Future}.
337   *
338   * <p>Usage example:
339   *
340   * <pre>{@code
341   * ListenableFuture<Integer> fetchCounterFuture = ...;
342   *
343   * // Falling back to a zero counter in case an exception happens when
344   * // processing the RPC to fetch counters.
345   * ListenableFuture<Integer> faultTolerantFuture = Futures.catching(
346   *     fetchCounterFuture, FetchException.class, x -> 0, directExecutor());
347   * }</pre>
348   *
349   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
350   * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener}
351   * documentation. All its warnings about heavyweight listeners are also applicable to heavyweight
352   * functions passed to this method.
353   *
354   * @param input the primary input {@code Future}
355   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
356   *     type is matched against the input's exception. "The input's exception" means the cause of
357   *     the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
358   *     different kind of exception, that exception itself. To avoid hiding bugs and other
359   *     unrecoverable errors, callers should prefer more specific types, avoiding {@code
360   *     Throwable.class} in particular.
361   * @param fallback the {@link Function} to be called if {@code input} fails with the expected
362   *     exception type. The function's argument is the input's exception. "The input's exception"
363   *     means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
364   *     {@code get()} throws a different kind of exception, that exception itself.
365   * @param executor the executor that runs {@code fallback} if {@code input} fails
366   * @since 19.0
367   */
368  @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
369  public static <V, X extends Throwable> ListenableFuture<V> catching(
370      ListenableFuture<? extends V> input,
371      Class<X> exceptionType,
372      Function<? super X, ? extends V> fallback,
373      Executor executor) {
374    return AbstractCatchingFuture.create(input, exceptionType, fallback, executor);
375  }
376
377  /**
378   * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
379   * primary input fails with the given {@code exceptionType}, from the result provided by the
380   * {@code fallback}. {@link AsyncFunction#apply} is not invoked until the primary input has
381   * failed, so if the primary input succeeds, it is never invoked. If, during the invocation of
382   * {@code fallback}, an exception is thrown, this exception is used as the result of the output
383   * {@code Future}.
384   *
385   * <p>Usage examples:
386   *
387   * <pre>{@code
388   * ListenableFuture<Integer> fetchCounterFuture = ...;
389   *
390   * // Falling back to a zero counter in case an exception happens when
391   * // processing the RPC to fetch counters.
392   * ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
393   *     fetchCounterFuture, FetchException.class, x -> immediateFuture(0));
394   * }</pre>
395   *
396   * <p>The fallback can also choose to propagate the original exception when desired:
397   *
398   * <pre>{@code
399   * ListenableFuture<Integer> fetchCounterFuture = ...;
400   *
401   * // Falling back to a zero counter only in case the exception was a
402   * // TimeoutException.
403   * ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
404   *     fetchCounterFuture,
405   *     FetchException.class,
406   *     e -> {
407   *       if (omitDataOnFetchFailure) {
408   *         return immediateFuture(0);
409   *       }
410   *       throw e;
411   *     });
412   * }</pre>
413   *
414   * <p>This overload, which does not accept an executor, uses {@code directExecutor}, a dangerous
415   * choice in some cases. See the discussion in the {@link ListenableFuture#addListener
416   * ListenableFuture.addListener} documentation. All its warnings about heavyweight listeners are
417   * also applicable to heavyweight functions passed to this method. (Specifically, {@code
418   * directExecutor} functions should avoid heavyweight operations inside {@code
419   * AsyncFunction.apply}. Any heavyweight operations should occur in other threads responsible for
420   * completing the returned {@code Future}.)
421   *
422   * @param input the primary input {@code Future}
423   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
424   *     type is matched against the input's exception. "The input's exception" means the cause of
425   *     the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
426   *     different kind of exception, that exception itself. To avoid hiding bugs and other
427   *     unrecoverable errors, callers should prefer more specific types, avoiding {@code
428   *     Throwable.class} in particular.
429   * @param fallback the {@link AsyncFunction} to be called if {@code input} fails with the expected
430   *     exception type. The function's argument is the input's exception. "The input's exception"
431   *     means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
432   *     {@code get()} throws a different kind of exception, that exception itself.
433   * @since 19.0 (similar functionality in 14.0 as {@code withFallback})
434   * @deprecated Use {@linkplain #catchingAsync(ListenableFuture, Class, AsyncFunction, Executor)
435   *     the overload that requires an executor}. For identical behavior, pass {@link
436   *     MoreExecutors#directExecutor}, but consider whether another executor would be safer, as
437   *     discussed in the {@link ListenableFuture#addListener ListenableFuture.addListener}
438   *     documentation. This method is scheduled to be removed in April 2018.
439   */
440  @CanIgnoreReturnValue // TODO(kak): @CheckReturnValue
441  @Deprecated
442  @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
443  public static <V, X extends Throwable> ListenableFuture<V> catchingAsync(
444      ListenableFuture<? extends V> input,
445      Class<X> exceptionType,
446      AsyncFunction<? super X, ? extends V> fallback) {
447    return AbstractCatchingFuture.create(input, exceptionType, fallback, directExecutor());
448  }
449
450  /**
451   * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
452   * primary input fails with the given {@code exceptionType}, from the result provided by the
453   * {@code fallback}. {@link AsyncFunction#apply} is not invoked until the primary input has
454   * failed, so if the primary input succeeds, it is never invoked. If, during the invocation of
455   * {@code fallback}, an exception is thrown, this exception is used as the result of the output
456   * {@code Future}.
457   *
458   * <p>Usage examples:
459   *
460   * <pre>{@code
461   * ListenableFuture<Integer> fetchCounterFuture = ...;
462   *
463   * // Falling back to a zero counter in case an exception happens when
464   * // processing the RPC to fetch counters.
465   * ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
466   *     fetchCounterFuture, FetchException.class, x -> immediateFuture(0), directExecutor());
467   * }</pre>
468   *
469   * <p>The fallback can also choose to propagate the original exception when desired:
470   *
471   * <pre>{@code
472   * ListenableFuture<Integer> fetchCounterFuture = ...;
473   *
474   * // Falling back to a zero counter only in case the exception was a
475   * // TimeoutException.
476   * ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
477   *     fetchCounterFuture,
478   *     FetchException.class,
479   *     e -> {
480   *       if (omitDataOnFetchFailure) {
481   *         return immediateFuture(0);
482   *       }
483   *       throw e;
484   *     },
485   *     directExecutor());
486   * }</pre>
487   *
488   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
489   * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener}
490   * documentation. All its warnings about heavyweight listeners are also applicable to heavyweight
491   * functions passed to this method. (Specifically, {@code directExecutor} functions should avoid
492   * heavyweight operations inside {@code AsyncFunction.apply}. Any heavyweight operations should
493   * occur in other threads responsible for completing the returned {@code Future}.)
494   *
495   * @param input the primary input {@code Future}
496   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
497   *     type is matched against the input's exception. "The input's exception" means the cause of
498   *     the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
499   *     different kind of exception, that exception itself. To avoid hiding bugs and other
500   *     unrecoverable errors, callers should prefer more specific types, avoiding {@code
501   *     Throwable.class} in particular.
502   * @param fallback the {@link AsyncFunction} to be called if {@code input} fails with the expected
503   *     exception type. The function's argument is the input's exception. "The input's exception"
504   *     means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
505   *     {@code get()} throws a different kind of exception, that exception itself.
506   * @param executor the executor that runs {@code fallback} if {@code input} fails
507   * @since 19.0 (similar functionality in 14.0 as {@code withFallback})
508   */
509  @CanIgnoreReturnValue // TODO(kak): @CheckReturnValue
510  @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
511  public static <V, X extends Throwable> ListenableFuture<V> catchingAsync(
512      ListenableFuture<? extends V> input,
513      Class<X> exceptionType,
514      AsyncFunction<? super X, ? extends V> fallback,
515      Executor executor) {
516    return AbstractCatchingFuture.create(input, exceptionType, fallback, executor);
517  }
518
519  /**
520   * Returns a future that delegates to another but will finish early (via a {@link
521   * TimeoutException} wrapped in an {@link ExecutionException}) if the specified duration expires.
522   *
523   * <p>The delegate future is interrupted and cancelled if it times out.
524   *
525   * @param delegate The future to delegate to.
526   * @param time when to timeout the future
527   * @param unit the time unit of the time parameter
528   * @param scheduledExecutor The executor service to enforce the timeout.
529   * @since 19.0
530   */
531  @GwtIncompatible // java.util.concurrent.ScheduledExecutorService
532  public static <V> ListenableFuture<V> withTimeout(
533      ListenableFuture<V> delegate,
534      long time,
535      TimeUnit unit,
536      ScheduledExecutorService scheduledExecutor) {
537    return TimeoutFuture.create(delegate, time, unit, scheduledExecutor);
538  }
539
540  /**
541   * Returns a new {@code Future} whose result is asynchronously derived from the result of the
542   * given {@code Future}. If the given {@code Future} fails, the returned {@code Future} fails with
543   * the same exception (and the function is not invoked).
544   *
545   * <p>More precisely, the returned {@code Future} takes its result from a {@code Future} produced
546   * by applying the given {@code AsyncFunction} to the result of the original {@code Future}.
547   * Example usage:
548   *
549   * <pre>{@code
550   * ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
551   * ListenableFuture<QueryResult> queryFuture =
552   *     transformAsync(rowKeyFuture, dataService::readFuture);
553   * }</pre>
554   *
555   * <p>This overload, which does not accept an executor, uses {@code directExecutor}, a dangerous
556   * choice in some cases. See the discussion in the {@link ListenableFuture#addListener
557   * ListenableFuture.addListener} documentation. All its warnings about heavyweight listeners are
558   * also applicable to heavyweight functions passed to this method. (Specifically, {@code
559   * directExecutor} functions should avoid heavyweight operations inside {@code
560   * AsyncFunction.apply}. Any heavyweight operations should occur in other threads responsible for
561   * completing the returned {@code Future}.)
562   *
563   * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
564   * input future and that of the future returned by the function. That is, if the returned {@code
565   * Future} is cancelled, it will attempt to cancel the other two, and if either of the other two
566   * is cancelled, the returned {@code Future} will receive a callback in which it will attempt to
567   * cancel itself.
568   *
569   * @param input The future to transform
570   * @param function A function to transform the result of the input future to the result of the
571   *     output future
572   * @return A future that holds result of the function (if the input succeeded) or the original
573   *     input's failure (if not)
574   * @since 19.0 (in 11.0 as {@code transform})
575   * @deprecated Use {@linkplain #transformAsync(ListenableFuture, AsyncFunction, Executor) the
576   *     overload that requires an executor}. For identical behavior, pass {@link
577   *     MoreExecutors#directExecutor}, but consider whether another executor would be safer, as
578   *     discussed in the {@link ListenableFuture#addListener ListenableFuture.addListener}
579   *     documentation. This method is scheduled to be removed in April 2018.
580   */
581  @Deprecated
582  public static <I, O> ListenableFuture<O> transformAsync(
583      ListenableFuture<I> input, AsyncFunction<? super I, ? extends O> function) {
584    return AbstractTransformFuture.create(input, function, directExecutor());
585  }
586
587  /**
588   * Returns a new {@code Future} whose result is asynchronously derived from the result of the
589   * given {@code Future}. If the given {@code Future} fails, the returned {@code Future} fails with
590   * the same exception (and the function is not invoked).
591   *
592   * <p>More precisely, the returned {@code Future} takes its result from a {@code Future} produced
593   * by applying the given {@code AsyncFunction} to the result of the original {@code Future}.
594   * Example usage:
595   *
596   * <pre>{@code
597   * ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
598   * ListenableFuture<QueryResult> queryFuture =
599   *     transformAsync(rowKeyFuture, dataService::readFuture, executor);
600   * }</pre>
601   *
602   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
603   * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener}
604   * documentation. All its warnings about heavyweight listeners are also applicable to heavyweight
605   * functions passed to this method. (Specifically, {@code directExecutor} functions should avoid
606   * heavyweight operations inside {@code AsyncFunction.apply}. Any heavyweight operations should
607   * occur in other threads responsible for completing the returned {@code Future}.)
608   *
609   * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
610   * input future and that of the future returned by the chain function. That is, if the returned
611   * {@code Future} is cancelled, it will attempt to cancel the other two, and if either of the
612   * other two is cancelled, the returned {@code Future} will receive a callback in which it will
613   * attempt to cancel itself.
614   *
615   * @param input The future to transform
616   * @param function A function to transform the result of the input future to the result of the
617   *     output future
618   * @param executor Executor to run the function in.
619   * @return A future that holds result of the function (if the input succeeded) or the original
620   *     input's failure (if not)
621   * @since 19.0 (in 11.0 as {@code transform})
622   */
623  public static <I, O> ListenableFuture<O> transformAsync(
624      ListenableFuture<I> input,
625      AsyncFunction<? super I, ? extends O> function,
626      Executor executor) {
627    return AbstractTransformFuture.create(input, function, executor);
628  }
629
630  /**
631   * Returns a new {@code Future} whose result is derived from the result of the given {@code
632   * Future}. If {@code input} fails, the returned {@code Future} fails with the same exception (and
633   * the function is not invoked). Example usage:
634   *
635   * <pre>{@code
636   * ListenableFuture<QueryResult> queryFuture = ...;
637   * ListenableFuture<List<Row>> rowsFuture =
638   *     transform(queryFuture, QueryResult::getRows);
639   * }</pre>
640   *
641   * <p>This overload, which does not accept an executor, uses {@code directExecutor}, a dangerous
642   * choice in some cases. See the discussion in the {@link ListenableFuture#addListener
643   * ListenableFuture.addListener} documentation. All its warnings about heavyweight listeners are
644   * also applicable to heavyweight functions passed to this method.
645   *
646   * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
647   * input future. That is, if the returned {@code Future} is cancelled, it will attempt to cancel
648   * the input, and if the input is cancelled, the returned {@code Future} will receive a callback
649   * in which it will attempt to cancel itself.
650   *
651   * <p>An example use of this method is to convert a serializable object returned from an RPC into
652   * a POJO.
653   *
654   * @param input The future to transform
655   * @param function A Function to transform the results of the provided future to the results of
656   *     the returned future. This will be run in the thread that notifies input it is complete.
657   * @return A future that holds result of the transformation.
658   * @since 9.0 (in 1.0 as {@code compose})
659   * @deprecated Use {@linkplain #transform(ListenableFuture, Function, Executor) the overload that
660   *     requires an executor}. For identical behavior, pass {@link MoreExecutors#directExecutor},
661   *     but consider whether another executor would be safer, as discussed in the {@link
662   *     ListenableFuture#addListener ListenableFuture.addListener} documentation. This method is
663   *     scheduled to be removed in April 2018.
664   */
665  @Deprecated
666  public static <I, O> ListenableFuture<O> transform(
667      ListenableFuture<I> input, Function<? super I, ? extends O> function) {
668    return AbstractTransformFuture.create(input, function, directExecutor());
669  }
670
671  /**
672   * Returns a new {@code Future} whose result is derived from the result of the given {@code
673   * Future}. If {@code input} fails, the returned {@code Future} fails with the same exception (and
674   * the function is not invoked). Example usage:
675   *
676   * <pre>{@code
677   * ListenableFuture<QueryResult> queryFuture = ...;
678   * ListenableFuture<List<Row>> rowsFuture =
679   *     transform(queryFuture, QueryResult::getRows, executor);
680   * }</pre>
681   *
682   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
683   * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener}
684   * documentation. All its warnings about heavyweight listeners are also applicable to heavyweight
685   * functions passed to this method.
686   *
687   * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
688   * input future. That is, if the returned {@code Future} is cancelled, it will attempt to cancel
689   * the input, and if the input is cancelled, the returned {@code Future} will receive a callback
690   * in which it will attempt to cancel itself.
691   *
692   * <p>An example use of this method is to convert a serializable object returned from an RPC into
693   * a POJO.
694   *
695   * @param input The future to transform
696   * @param function A Function to transform the results of the provided future to the results of
697   *     the returned future.
698   * @param executor Executor to run the function in.
699   * @return A future that holds result of the transformation.
700   * @since 9.0 (in 2.0 as {@code compose})
701   */
702  public static <I, O> ListenableFuture<O> transform(
703      ListenableFuture<I> input, Function<? super I, ? extends O> function, Executor executor) {
704    return AbstractTransformFuture.create(input, function, executor);
705  }
706
707  /**
708   * Like {@link #transform(ListenableFuture, Function, Executor)} except that the transformation
709   * {@code function} is invoked on each call to {@link Future#get() get()} on the returned future.
710   *
711   * <p>The returned {@code Future} reflects the input's cancellation state directly, and any
712   * attempt to cancel the returned Future is likewise passed through to the input Future.
713   *
714   * <p>Note that calls to {@linkplain Future#get(long, TimeUnit) timed get} only apply the timeout
715   * to the execution of the underlying {@code Future}, <em>not</em> to the execution of the
716   * transformation function.
717   *
718   * <p>The primary audience of this method is callers of {@code transform} who don't have a {@code
719   * ListenableFuture} available and do not mind repeated, lazy function evaluation.
720   *
721   * @param input The future to transform
722   * @param function A Function to transform the results of the provided future to the results of
723   *     the returned future.
724   * @return A future that returns the result of the transformation.
725   * @since 10.0
726   */
727  @GwtIncompatible // TODO
728  public static <I, O> Future<O> lazyTransform(
729      final Future<I> input, final Function<? super I, ? extends O> function) {
730    checkNotNull(input);
731    checkNotNull(function);
732    return new Future<O>() {
733
734      @Override
735      public boolean cancel(boolean mayInterruptIfRunning) {
736        return input.cancel(mayInterruptIfRunning);
737      }
738
739      @Override
740      public boolean isCancelled() {
741        return input.isCancelled();
742      }
743
744      @Override
745      public boolean isDone() {
746        return input.isDone();
747      }
748
749      @Override
750      public O get() throws InterruptedException, ExecutionException {
751        return applyTransformation(input.get());
752      }
753
754      @Override
755      public O get(long timeout, TimeUnit unit)
756          throws InterruptedException, ExecutionException, TimeoutException {
757        return applyTransformation(input.get(timeout, unit));
758      }
759
760      private O applyTransformation(I input) throws ExecutionException {
761        try {
762          return function.apply(input);
763        } catch (Throwable t) {
764          throw new ExecutionException(t);
765        }
766      }
767    };
768  }
769
770  /**
771   * Returns a new {@code ListenableFuture} whose result is the product of calling {@code get()} on
772   * the {@code Future} nested within the given {@code Future}, effectively chaining the futures one
773   * after the other. Example:
774   *
775   * <pre>{@code
776   * SettableFuture<ListenableFuture<String>> nested = SettableFuture.create();
777   * ListenableFuture<String> dereferenced = dereference(nested);
778   * }</pre>
779   *
780   * <p>Most users will not need this method. To create a {@code Future} that completes with the
781   * result of another {@code Future}, create a {@link SettableFuture}, and call {@link
782   * SettableFuture#setFuture setFuture(otherFuture)} on it.
783   *
784   * <p>{@code dereference} has the same cancellation and execution semantics as {@link
785   * #transformAsync(ListenableFuture, AsyncFunction, Executor)}, in that the returned {@code
786   * Future} attempts to keep its cancellation state in sync with both the input {@code Future} and
787   * the nested {@code Future}. The transformation is very lightweight and therefore takes place in
788   * the same thread (either the thread that called {@code dereference}, or the thread in which the
789   * dereferenced future completes).
790   *
791   * @deprecated Use {@link #submitAsync(AsyncCallable, Executor)} or {@link
792   *     SettableFuture#setFuture} instead. Or, if you're dereferencing the output of {@link
793   *     #transform} or {@link #catching}, switch to {@link #transformAsync} or {@link
794   *     #catchingAsync} (and likewise for similar APIs). If the cancellation of this method's
795   *     output future races with completion of the outer input future, cancellation may not be
796   *     propagated to the inner input future. This method is scheduled to be removed in January
797   *     2018.
798   * @param nested The nested future to transform.
799   * @return A future that holds result of the inner future.
800   * @since 13.0
801   */
802  @Deprecated
803  @SuppressWarnings({"rawtypes", "unchecked"})
804  public static <V> ListenableFuture<V> dereference(
805      ListenableFuture<? extends ListenableFuture<? extends V>> nested) {
806    return transformAsync(
807        (ListenableFuture) nested, (AsyncFunction) DEREFERENCER, directExecutor());
808  }
809
810  /** Helper {@code Function} for {@link #dereference}. */
811  private static final AsyncFunction<ListenableFuture<Object>, Object> DEREFERENCER =
812      new AsyncFunction<ListenableFuture<Object>, Object>() {
813        @Override
814        public ListenableFuture<Object> apply(ListenableFuture<Object> input) {
815          return input;
816        }
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.
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  @SafeVarargs
834  public static <V> ListenableFuture<List<V>> allAsList(ListenableFuture<? extends V>... futures) {
835    return new ListFuture<V>(ImmutableList.copyOf(futures), true);
836  }
837
838  /**
839   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
840   * input futures, if all succeed.
841   *
842   * <p>The list of results is in the same order as the input list.
843   *
844   * <p>Canceling this future will attempt to cancel all the component futures, and if any of the
845   * provided futures fails or is canceled, this one is, too.
846   *
847   * @param futures futures to combine
848   * @return a future that provides a list of the results of the component futures
849   * @since 10.0
850   */
851  @Beta
852  public static <V> ListenableFuture<List<V>> allAsList(
853      Iterable<? extends ListenableFuture<? extends V>> futures) {
854    return new ListFuture<V>(ImmutableList.copyOf(futures), true);
855  }
856
857  /**
858   * Creates a {@link FutureCombiner} that processes the completed futures whether or not they're
859   * successful.
860   *
861   * @since 20.0
862   */
863  @SafeVarargs
864  public static <V> FutureCombiner<V> whenAllComplete(ListenableFuture<? extends V>... futures) {
865    return new FutureCombiner<V>(false, ImmutableList.copyOf(futures));
866  }
867
868  /**
869   * Creates a {@link FutureCombiner} that processes the completed futures whether or not they're
870   * successful.
871   *
872   * @since 20.0
873   */
874  public static <V> FutureCombiner<V> whenAllComplete(
875      Iterable<? extends ListenableFuture<? extends V>> futures) {
876    return new FutureCombiner<V>(false, ImmutableList.copyOf(futures));
877  }
878
879  /**
880   * Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
881   *
882   * <p>If any input fails, the returned future fails immediately.
883   *
884   * @since 20.0
885   */
886  @SafeVarargs
887  public static <V> FutureCombiner<V> whenAllSucceed(ListenableFuture<? extends V>... futures) {
888    return new FutureCombiner<V>(true, ImmutableList.copyOf(futures));
889  }
890
891  /**
892   * Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
893   *
894   * <p>If any input fails, the returned future fails immediately.
895   *
896   * @since 20.0
897   */
898  public static <V> FutureCombiner<V> whenAllSucceed(
899      Iterable<? extends ListenableFuture<? extends V>> futures) {
900    return new FutureCombiner<V>(true, ImmutableList.copyOf(futures));
901  }
902
903  /**
904   * A helper to create a new {@code ListenableFuture} whose result is generated from a combination
905   * of input futures.
906   *
907   * <p>See {@link #whenAllComplete} and {@link #whenAllSucceed} for how to instantiate this class.
908   *
909   * <p>Example:
910   *
911   * <pre>{@code
912   * final ListenableFuture<Instant> loginDateFuture =
913   *     loginService.findLastLoginDate(username);
914   * final ListenableFuture<List<String>> recentCommandsFuture =
915   *     recentCommandsService.findRecentCommands(username);
916   * Callable<UsageHistory> usageComputation =
917   *     new Callable<UsageHistory>() {
918   *       public UsageHistory call() throws Exception {
919   *         return new UsageHistory(
920   *             username, loginDateFuture.get(), recentCommandsFuture.get());
921   *       }
922   *     };
923   * ListenableFuture<UsageHistory> usageFuture =
924   *     Futures.whenAllSucceed(loginDateFuture, recentCommandsFuture)
925   *         .call(usageComputation, executor);
926   * }</pre>
927   *
928   * @since 20.0
929   */
930  @Beta
931  @CanIgnoreReturnValue // TODO(cpovirk): Consider removing, especially if we provide run(Runnable)
932  @GwtCompatible
933  public static final class FutureCombiner<V> {
934    private final boolean allMustSucceed;
935    private final ImmutableList<ListenableFuture<? extends V>> futures;
936
937    private FutureCombiner(
938        boolean allMustSucceed, ImmutableList<ListenableFuture<? extends V>> futures) {
939      this.allMustSucceed = allMustSucceed;
940      this.futures = futures;
941    }
942
943    /**
944     * Creates the {@link ListenableFuture} which will return the result of calling {@link
945     * AsyncCallable#call} in {@code combiner} when all futures complete, using the specified {@code
946     * executor}.
947     *
948     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
949     * cancelled.
950     *
951     * <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code
952     * ExecutionException} will be extracted and returned as the cause of the new {@code
953     * ExecutionException} that gets thrown by the returned combined future.
954     *
955     * <p>Canceling this future will attempt to cancel all the component futures.
956     */
957    public <C> ListenableFuture<C> callAsync(AsyncCallable<C> combiner, Executor executor) {
958      return new CombinedFuture<C>(futures, allMustSucceed, executor, combiner);
959    }
960
961    /**
962     * Like {@link #callAsync(AsyncCallable, Executor)} but using {@linkplain
963     * MoreExecutors#directExecutor direct executor}.
964     *
965     * @deprecated Use {@linkplain #callAsync(AsyncCallable, Executor) the overload that requires an
966     *     executor}. For identical behavior, pass {@link MoreExecutors#directExecutor}, but
967     *     consider whether another executor would be safer, as discussed in the {@link
968     *     ListenableFuture#addListener ListenableFuture.addListener} documentation. This method is
969     *     scheduled to be removed in April 2018.
970     */
971    @Deprecated
972    public <C> ListenableFuture<C> callAsync(AsyncCallable<C> combiner) {
973      return callAsync(combiner, directExecutor());
974    }
975
976    /**
977     * Creates the {@link ListenableFuture} which will return the result of calling {@link
978     * Callable#call} in {@code combiner} when all futures complete, using the specified {@code
979     * executor}.
980     *
981     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
982     * cancelled.
983     *
984     * <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code
985     * ExecutionException} will be extracted and returned as the cause of the new {@code
986     * ExecutionException} that gets thrown by the returned combined future.
987     *
988     * <p>Canceling this future will attempt to cancel all the component futures.
989     */
990    @CanIgnoreReturnValue // TODO(cpovirk): Remove this
991    public <C> ListenableFuture<C> call(Callable<C> combiner, Executor executor) {
992      return new CombinedFuture<C>(futures, allMustSucceed, executor, combiner);
993    }
994
995    /**
996     * Like {@link #call(Callable, Executor)} but using {@linkplain MoreExecutors#directExecutor
997     * direct executor}.
998     *
999     * @deprecated Use {@linkplain #call(Callable, Executor) the overload that requires an
1000     *     executor}. For identical behavior, pass {@link MoreExecutors#directExecutor}, but
1001     *     consider whether another executor would be safer, as discussed in the {@link
1002     *     ListenableFuture#addListener ListenableFuture.addListener} documentation. This method is
1003     *     scheduled to be removed in April 2018.
1004     */
1005    @CanIgnoreReturnValue // TODO(cpovirk): Remove this
1006    @Deprecated
1007    public <C> ListenableFuture<C> call(Callable<C> combiner) {
1008      return call(combiner, directExecutor());
1009    }
1010
1011    /**
1012     * Creates the {@link ListenableFuture} which will return the result of running {@code combiner}
1013     * when all Futures complete. {@code combiner} will run using {@code executor}.
1014     *
1015     * <p>If the combiner throws a {@code CancellationException}, the returned future will be
1016     * cancelled.
1017     *
1018     * <p>Canceling this Future will attempt to cancel all the component futures.
1019     *
1020     * @since 23.6
1021     */
1022    public ListenableFuture<?> run(final Runnable combiner, Executor executor) {
1023      return call(
1024          new Callable<Void>() {
1025            @Override
1026            public Void call() throws Exception {
1027              combiner.run();
1028              return null;
1029            }
1030          },
1031          executor);
1032    }
1033  }
1034
1035  /**
1036   * Returns a {@code ListenableFuture} whose result is set from the supplied future when it
1037   * completes. Cancelling the supplied future will also cancel the returned future, but cancelling
1038   * the returned future will have no effect on the supplied future.
1039   *
1040   * @since 15.0
1041   */
1042  public static <V> ListenableFuture<V> nonCancellationPropagating(ListenableFuture<V> future) {
1043    if (future.isDone()) {
1044      return future;
1045    }
1046    NonCancellationPropagatingFuture<V> output = new NonCancellationPropagatingFuture<>(future);
1047    future.addListener(output, directExecutor());
1048    return output;
1049  }
1050
1051  /** A wrapped future that does not propagate cancellation to its delegate. */
1052  private static final class NonCancellationPropagatingFuture<V>
1053      extends AbstractFuture.TrustedFuture<V> implements Runnable {
1054    private ListenableFuture<V> delegate;
1055
1056    NonCancellationPropagatingFuture(final ListenableFuture<V> delegate) {
1057      this.delegate = delegate;
1058    }
1059
1060    @Override
1061    public void run() {
1062      // This prevents cancellation from propagating because we don't assign delegate until
1063      // delegate is already done, so calling cancel() on it is a no-op.
1064      ListenableFuture<V> localDelegate = delegate;
1065      if (localDelegate != null) {
1066        setFuture(localDelegate);
1067      }
1068    }
1069
1070    @Override
1071    protected String pendingToString() {
1072      ListenableFuture<V> localDelegate = delegate;
1073      if (localDelegate != null) {
1074        return "delegate=[" + localDelegate + "]";
1075      }
1076      return null;
1077    }
1078
1079    @Override
1080    protected void afterDone() {
1081      delegate = null;
1082    }
1083  }
1084
1085  /**
1086   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
1087   * successful input futures. The list of results is in the same order as the input list, and if
1088   * any of the provided futures fails or is canceled, its corresponding position will contain
1089   * {@code null} (which is indistinguishable from the future having a successful value of {@code
1090   * null}).
1091   *
1092   * <p>Canceling this future will attempt to cancel all the component futures.
1093   *
1094   * @param futures futures to combine
1095   * @return a future that provides a list of the results of the component futures
1096   * @since 10.0
1097   */
1098  @Beta
1099  @SafeVarargs
1100  public static <V> ListenableFuture<List<V>> successfulAsList(
1101      ListenableFuture<? extends V>... futures) {
1102    return new ListFuture<V>(ImmutableList.copyOf(futures), false);
1103  }
1104
1105  /**
1106   * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
1107   * successful input futures. The list of results is in the same order as the input list, and if
1108   * any of the provided futures fails or is canceled, its corresponding position will contain
1109   * {@code null} (which is indistinguishable from the future having a successful value of {@code
1110   * null}).
1111   *
1112   * <p>Canceling this future will attempt to cancel all the component futures.
1113   *
1114   * @param futures futures to combine
1115   * @return a future that provides a list of the results of the component futures
1116   * @since 10.0
1117   */
1118  @Beta
1119  public static <V> ListenableFuture<List<V>> successfulAsList(
1120      Iterable<? extends ListenableFuture<? extends V>> futures) {
1121    return new ListFuture<V>(ImmutableList.copyOf(futures), false);
1122  }
1123
1124  /**
1125   * Returns a list of delegate futures that correspond to the futures received in the order that
1126   * they complete. Delegate futures return the same value or throw the same exception as the
1127   * corresponding input future returns/throws.
1128   *
1129   * <p>"In the order that they complete" means, for practical purposes, about what you would
1130   * expect, but there are some subtleties. First, we do guarantee that, if the output future at
1131   * index n is done, the output future at index n-1 is also done. (But as usual with futures, some
1132   * listeners for future n may complete before some for future n-1.) However, it is possible, if
1133   * one input completes with result X and another later with result Y, for Y to come before X in
1134   * the output future list. (Such races are impossible to solve without global synchronization of
1135   * all future completions. And they should have little practical impact.)
1136   *
1137   * <p>Cancelling a delegate future propagates to input futures once all the delegates complete,
1138   * either from cancellation or because an input future has completed. If N futures are passed in,
1139   * and M delegates are cancelled, the remaining M input futures will be cancelled once N - M of
1140   * the input futures complete. If all the delegates are cancelled, all the input futures will be
1141   * too.
1142   *
1143   * @since 17.0
1144   */
1145  @Beta
1146  public static <T> ImmutableList<ListenableFuture<T>> inCompletionOrder(
1147      Iterable<? extends ListenableFuture<? extends T>> futures) {
1148    // Can't use Iterables.toArray because it's not gwt compatible
1149    final Collection<ListenableFuture<? extends T>> collection;
1150    if (futures instanceof Collection) {
1151      collection = (Collection<ListenableFuture<? extends T>>) futures;
1152    } else {
1153      collection = ImmutableList.copyOf(futures);
1154    }
1155    @SuppressWarnings("unchecked")
1156    ListenableFuture<? extends T>[] copy =
1157        (ListenableFuture<? extends T>[])
1158            collection.toArray(new ListenableFuture[collection.size()]);
1159    final InCompletionOrderState<T> state = new InCompletionOrderState<>(copy);
1160    ImmutableList.Builder<AbstractFuture<T>> delegatesBuilder = ImmutableList.builder();
1161    for (int i = 0; i < copy.length; i++) {
1162      delegatesBuilder.add(new InCompletionOrderFuture<T>(state));
1163    }
1164
1165    final ImmutableList<AbstractFuture<T>> delegates = delegatesBuilder.build();
1166    for (int i = 0; i < copy.length; i++) {
1167      final int localI = i;
1168      copy[i].addListener(
1169          new Runnable() {
1170            @Override
1171            public void run() {
1172              state.recordInputCompletion(delegates, localI);
1173            }
1174          },
1175          directExecutor());
1176    }
1177
1178    @SuppressWarnings("unchecked")
1179    ImmutableList<ListenableFuture<T>> delegatesCast = (ImmutableList) delegates;
1180    return delegatesCast;
1181  }
1182
1183  // This can't be a TrustedFuture, because TrustedFuture has clever optimizations that
1184  // mean cancel won't be called if this Future is passed into setFuture, and then
1185  // cancelled.
1186  private static final class InCompletionOrderFuture<T> extends AbstractFuture<T> {
1187    private InCompletionOrderState<T> state;
1188
1189    private InCompletionOrderFuture(InCompletionOrderState<T> state) {
1190      this.state = state;
1191    }
1192
1193    @Override
1194    public boolean cancel(boolean interruptIfRunning) {
1195      InCompletionOrderState<T> localState = state;
1196      if (super.cancel(interruptIfRunning)) {
1197        localState.recordOutputCancellation(interruptIfRunning);
1198        return true;
1199      }
1200      return false;
1201    }
1202
1203    @Override
1204    protected void afterDone() {
1205      state = null;
1206    }
1207
1208    @Override
1209    protected String pendingToString() {
1210      InCompletionOrderState<T> localState = state;
1211      if (localState != null) {
1212        // Don't print the actual array! We don't want inCompletionOrder(list).toString() to have
1213        // quadratic output.
1214        return "inputCount=["
1215            + localState.inputFutures.length
1216            + "], remaining=["
1217            + localState.incompleteOutputCount.get()
1218            + "]";
1219      }
1220      return null;
1221    }
1222  }
1223
1224  private static final class InCompletionOrderState<T> {
1225    // A happens-before edge between the writes of these fields and their reads exists, because
1226    // in order to read these fields, the corresponding write to incompleteOutputCount must have
1227    // been read.
1228    private boolean wasCancelled = false;
1229    private boolean shouldInterrupt = true;
1230    private final AtomicInteger incompleteOutputCount;
1231    private final ListenableFuture<? extends T>[] inputFutures;
1232    private volatile int delegateIndex = 0;
1233
1234    private InCompletionOrderState(ListenableFuture<? extends T>[] inputFutures) {
1235      this.inputFutures = inputFutures;
1236      incompleteOutputCount = new AtomicInteger(inputFutures.length);
1237    }
1238
1239    private void recordOutputCancellation(boolean interruptIfRunning) {
1240      wasCancelled = true;
1241      // If all the futures were cancelled with interruption, cancel the input futures
1242      // with interruption; otherwise cancel without
1243      if (!interruptIfRunning) {
1244        shouldInterrupt = false;
1245      }
1246      recordCompletion();
1247    }
1248
1249    private void recordInputCompletion(
1250        ImmutableList<AbstractFuture<T>> delegates, int inputFutureIndex) {
1251      ListenableFuture<? extends T> inputFuture = inputFutures[inputFutureIndex];
1252      // Null out our reference to this future, so it can be GCed
1253      inputFutures[inputFutureIndex] = null;
1254      for (int i = delegateIndex; i < delegates.size(); i++) {
1255        if (delegates.get(i).setFuture(inputFuture)) {
1256          recordCompletion();
1257          // this is technically unnecessary, but should speed up later accesses
1258          delegateIndex = i + 1;
1259          return;
1260        }
1261      }
1262      // If all the delegates were complete, no reason for the next listener to have to
1263      // go through the whole list. Avoids O(n^2) behavior when the entire output list is
1264      // cancelled.
1265      delegateIndex = delegates.size();
1266    }
1267
1268    private void recordCompletion() {
1269      if (incompleteOutputCount.decrementAndGet() == 0 && wasCancelled) {
1270        for (ListenableFuture<?> toCancel : inputFutures) {
1271          if (toCancel != null) {
1272            toCancel.cancel(shouldInterrupt);
1273          }
1274        }
1275      }
1276    }
1277  }
1278
1279  /**
1280   * Registers separate success and failure callbacks to be run when the {@code Future}'s
1281   * computation is {@linkplain java.util.concurrent.Future#isDone() complete} or, if the
1282   * computation is already complete, immediately.
1283   *
1284   * <p>There is no guaranteed ordering of execution of callbacks, but any callback added through
1285   * this method is guaranteed to be called once the computation is complete.
1286   *
1287   * <p>Example:
1288   *
1289   * <pre>{@code
1290   * ListenableFuture<QueryResult> future = ...;
1291   * addCallback(future,
1292   *     new FutureCallback<QueryResult>() {
1293   *       public void onSuccess(QueryResult result) {
1294   *         storeInCache(result);
1295   *       }
1296   *       public void onFailure(Throwable t) {
1297   *         reportError(t);
1298   *       }
1299   *     });
1300   * }</pre>
1301   *
1302   * <p>This overload, which does not accept an executor, uses {@code directExecutor}, a dangerous
1303   * choice in some cases. See the discussion in the {@link ListenableFuture#addListener
1304   * ListenableFuture.addListener} documentation. All its warnings about heavyweight listeners are
1305   * also applicable to heavyweight callbacks passed to this method.
1306   *
1307   * <p>For a more general interface to attach a completion listener to a {@code Future}, see {@link
1308   * ListenableFuture#addListener addListener}.
1309   *
1310   * @param future The future attach the callback to.
1311   * @param callback The callback to invoke when {@code future} is completed.
1312   * @since 10.0
1313   * @deprecated Use {@linkplain #addCallback(ListenableFuture, FutureCallback, Executor) the
1314   *     overload that requires an executor}. For identical behavior, pass {@link
1315   *     MoreExecutors#directExecutor}, but consider whether another executor would be safer, as
1316   *     discussed in the {@link ListenableFuture#addListener ListenableFuture.addListener}
1317   *     documentation. This method is scheduled to be removed in April 2018.
1318   */
1319  @Deprecated
1320  public static <V> void addCallback(
1321      ListenableFuture<V> future, FutureCallback<? super V> callback) {
1322    addCallback(future, callback, directExecutor());
1323  }
1324
1325  /**
1326   * Registers separate success and failure callbacks to be run when the {@code Future}'s
1327   * computation is {@linkplain java.util.concurrent.Future#isDone() complete} or, if the
1328   * computation is already complete, immediately.
1329   *
1330   * <p>The callback is run on {@code executor}. There is no guaranteed ordering of execution of
1331   * callbacks, but any callback added through this method is guaranteed to be called once the
1332   * computation is complete.
1333   *
1334   * <p>Example:
1335   *
1336   * <pre>{@code
1337   * ListenableFuture<QueryResult> future = ...;
1338   * Executor e = ...
1339   * addCallback(future,
1340   *     new FutureCallback<QueryResult>() {
1341   *       public void onSuccess(QueryResult result) {
1342   *         storeInCache(result);
1343   *       }
1344   *       public void onFailure(Throwable t) {
1345   *         reportError(t);
1346   *       }
1347   *     }, e);
1348   * }</pre>
1349   *
1350   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
1351   * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener}
1352   * documentation. All its warnings about heavyweight listeners are also applicable to heavyweight
1353   * callbacks passed to this method.
1354   *
1355   * <p>For a more general interface to attach a completion listener to a {@code Future}, see {@link
1356   * ListenableFuture#addListener addListener}.
1357   *
1358   * @param future The future attach the callback to.
1359   * @param callback The callback to invoke when {@code future} is completed.
1360   * @param executor The executor to run {@code callback} when the future completes.
1361   * @since 10.0
1362   */
1363  public static <V> void addCallback(
1364      final ListenableFuture<V> future,
1365      final FutureCallback<? super V> callback,
1366      Executor executor) {
1367    Preconditions.checkNotNull(callback);
1368    future.addListener(new CallbackListener<V>(future, callback), executor);
1369  }
1370
1371  /** See {@link #addCallback(ListenableFuture, FutureCallback, Executor)} for behavioral notes. */
1372  private static final class CallbackListener<V> implements Runnable {
1373    final Future<V> future;
1374    final FutureCallback<? super V> callback;
1375
1376    CallbackListener(Future<V> future, FutureCallback<? super V> callback) {
1377      this.future = future;
1378      this.callback = callback;
1379    }
1380
1381    @Override
1382    public void run() {
1383      final V value;
1384      try {
1385        value = getDone(future);
1386      } catch (ExecutionException e) {
1387        callback.onFailure(e.getCause());
1388        return;
1389      } catch (RuntimeException | Error e) {
1390        callback.onFailure(e);
1391        return;
1392      }
1393      callback.onSuccess(value);
1394    }
1395
1396    @Override
1397    public String toString() {
1398      return MoreObjects.toStringHelper(this).addValue(callback).toString();
1399    }
1400  }
1401
1402  /**
1403   * Returns the result of the input {@code Future}, which must have already completed.
1404   *
1405   * <p>The benefits of this method are twofold. First, the name "getDone" suggests to readers that
1406   * the {@code Future} is already done. Second, if buggy code calls {@code getDone} on a {@code
1407   * Future} that is still pending, the program will throw instead of block. This can be important
1408   * for APIs like {@link #whenAllComplete whenAllComplete(...)}{@code .}{@link
1409   * FutureCombiner#call(Callable, Executor) call(...)}, where it is easy to use a new input from
1410   * the {@code call} implementation but forget to add it to the arguments of {@code
1411   * whenAllComplete}.
1412   *
1413   * <p>If you are looking for a method to determine whether a given {@code Future} is done, use the
1414   * instance method {@link Future#isDone()}.
1415   *
1416   * @throws ExecutionException if the {@code Future} failed with an exception
1417   * @throws CancellationException if the {@code Future} was cancelled
1418   * @throws IllegalStateException if the {@code Future} is not done
1419   * @since 20.0
1420   */
1421  @CanIgnoreReturnValue
1422  // TODO(cpovirk): Consider calling getDone() in our own code.
1423  public static <V> V getDone(Future<V> future) throws ExecutionException {
1424    /*
1425     * We throw IllegalStateException, since the call could succeed later. Perhaps we "should" throw
1426     * IllegalArgumentException, since the call could succeed with a different argument. Those
1427     * exceptions' docs suggest that either is acceptable. Google's Java Practices page recommends
1428     * IllegalArgumentException here, in part to keep its recommendation simple: Static methods
1429     * should throw IllegalStateException only when they use static state.
1430     *
1431     *
1432     * Why do we deviate here? The answer: We want for fluentFuture.getDone() to throw the same
1433     * exception as Futures.getDone(fluentFuture).
1434     */
1435    checkState(future.isDone(), "Future was expected to be done: %s", future);
1436    return getUninterruptibly(future);
1437  }
1438
1439  /**
1440   * Returns the result of {@link Future#get()}, converting most exceptions to a new instance of the
1441   * given checked exception type. This reduces boilerplate for a common use of {@code Future} in
1442   * which it is unnecessary to programmatically distinguish between exception types or to extract
1443   * other information from the exception instance.
1444   *
1445   * <p>Exceptions from {@code Future.get} are treated as follows:
1446   *
1447   * <ul>
1448   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1449   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1450   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1451   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1452   *       interrupt).
1453   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1454   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1455   *       exceptions).
1456   * </ul>
1457   *
1458   * <p>The overall principle is to continue to treat every checked exception as a checked
1459   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1460   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1461   * new stack trace matches that of the current thread.
1462   *
1463   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1464   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1465   * (preferring constructors with at least one {@code String}) and calling the constructor via
1466   * reflection. If the exception did not already have a cause, one is set by calling {@link
1467   * Throwable#initCause(Throwable)} on it. If no such constructor exists, an {@code
1468   * IllegalArgumentException} is thrown.
1469   *
1470   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1471   *     whose cause is not itself a checked exception
1472   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1473   *     {@code RuntimeException} as its cause
1474   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1475   *     Error} as its cause
1476   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1477   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1478   *     does not have a suitable constructor
1479   * @since 19.0 (in 10.0 as {@code get})
1480   */
1481  @CanIgnoreReturnValue
1482  @GwtIncompatible // reflection
1483  public static <V, X extends Exception> V getChecked(Future<V> future, Class<X> exceptionClass)
1484      throws X {
1485    return FuturesGetChecked.getChecked(future, exceptionClass);
1486  }
1487
1488  /**
1489   * Returns the result of {@link Future#get(long, TimeUnit)}, converting most exceptions to a new
1490   * instance of the given checked exception type. This reduces boilerplate for a common use of
1491   * {@code Future} in which it is unnecessary to programmatically distinguish between exception
1492   * types or to extract other information from the exception instance.
1493   *
1494   * <p>Exceptions from {@code Future.get} are treated as follows:
1495   *
1496   * <ul>
1497   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause
1498   *       is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code
1499   *       RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}.
1500   *   <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the
1501   *       interrupt).
1502   *   <li>Any {@link TimeoutException} is wrapped in an {@code X}.
1503   *   <li>Any {@link CancellationException} is propagated untouched, as is any other {@link
1504   *       RuntimeException} (though {@code get} implementations are discouraged from throwing such
1505   *       exceptions).
1506   * </ul>
1507   *
1508   * <p>The overall principle is to continue to treat every checked exception as a checked
1509   * exception, every unchecked exception as an unchecked exception, and every error as an error. In
1510   * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the
1511   * new stack trace matches that of the current thread.
1512   *
1513   * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor
1514   * that accepts zero or more arguments, all of type {@code String} or {@code Throwable}
1515   * (preferring constructors with at least one {@code String}) and calling the constructor via
1516   * reflection. If the exception did not already have a cause, one is set by calling {@link
1517   * Throwable#initCause(Throwable)} on it. If no such constructor exists, an {@code
1518   * IllegalArgumentException} is thrown.
1519   *
1520   * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException}
1521   *     whose cause is not itself a checked exception
1522   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a
1523   *     {@code RuntimeException} as its cause
1524   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1525   *     Error} as its cause
1526   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1527   * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or
1528   *     does not have a suitable constructor
1529   * @since 19.0 (in 10.0 as {@code get} and with different parameter order)
1530   */
1531  @CanIgnoreReturnValue
1532  @GwtIncompatible // reflection
1533  public static <V, X extends Exception> V getChecked(
1534      Future<V> future, Class<X> exceptionClass, long timeout, TimeUnit unit) throws X {
1535    return FuturesGetChecked.getChecked(future, exceptionClass, timeout, unit);
1536  }
1537
1538  /**
1539   * Returns the result of calling {@link Future#get()} uninterruptibly on a task known not to throw
1540   * a checked exception. This makes {@code Future} more suitable for lightweight, fast-running
1541   * tasks that, barring bugs in the code, will not fail. This gives it exception-handling behavior
1542   * similar to that of {@code ForkJoinTask.join}.
1543   *
1544   * <p>Exceptions from {@code Future.get} are treated as follows:
1545   *
1546   * <ul>
1547   *   <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@link
1548   *       UncheckedExecutionException} (if the cause is an {@code Exception}) or {@link
1549   *       ExecutionError} (if the cause is an {@code Error}).
1550   *   <li>Any {@link InterruptedException} causes a retry of the {@code get} call. The interrupt is
1551   *       restored before {@code getUnchecked} returns.
1552   *   <li>Any {@link CancellationException} is propagated untouched. So is any other {@link
1553   *       RuntimeException} ({@code get} implementations are discouraged from throwing such
1554   *       exceptions).
1555   * </ul>
1556   *
1557   * <p>The overall principle is to eliminate all checked exceptions: to loop to avoid {@code
1558   * InterruptedException}, to pass through {@code CancellationException}, and to wrap any exception
1559   * from the underlying computation in an {@code UncheckedExecutionException} or {@code
1560   * ExecutionError}.
1561   *
1562   * <p>For an uninterruptible {@code get} that preserves other exceptions, see {@link
1563   * Uninterruptibles#getUninterruptibly(Future)}.
1564   *
1565   * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with an
1566   *     {@code Exception} as its cause
1567   * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code
1568   *     Error} as its cause
1569   * @throws CancellationException if {@code get} throws a {@code CancellationException}
1570   * @since 10.0
1571   */
1572  @CanIgnoreReturnValue
1573  public static <V> V getUnchecked(Future<V> future) {
1574    checkNotNull(future);
1575    try {
1576      return getUninterruptibly(future);
1577    } catch (ExecutionException e) {
1578      wrapAndThrowUnchecked(e.getCause());
1579      throw new AssertionError();
1580    }
1581  }
1582
1583  private static void wrapAndThrowUnchecked(Throwable cause) {
1584    if (cause instanceof Error) {
1585      throw new ExecutionError((Error) cause);
1586    }
1587    /*
1588     * It's an Exception. (Or it's a non-Error, non-Exception Throwable. From my survey of such
1589     * classes, I believe that most users intended to extend Exception, so we'll treat it like an
1590     * Exception.)
1591     */
1592    throw new UncheckedExecutionException(cause);
1593  }
1594
1595  /*
1596   * Arguably we don't need a timed getUnchecked because any operation slow enough to require a
1597   * timeout is heavyweight enough to throw a checked exception and therefore be inappropriate to
1598   * use with getUnchecked. Further, it's not clear that converting the checked TimeoutException to
1599   * a RuntimeException -- especially to an UncheckedExecutionException, since it wasn't thrown by
1600   * the computation -- makes sense, and if we don't convert it, the user still has to write a
1601   * try-catch block.
1602   *
1603   * If you think you would use this method, let us know. You might also also look into the
1604   * Fork-Join framework: http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html
1605   */
1606
1607  /**
1608   * A checked future that uses a function to map from exceptions to the appropriate checked type.
1609   */
1610  @GwtIncompatible // TODO
1611  private static class MappingCheckedFuture<V, X extends Exception>
1612      extends AbstractCheckedFuture<V, X> {
1613
1614    final Function<? super Exception, X> mapper;
1615
1616    MappingCheckedFuture(ListenableFuture<V> delegate, Function<? super Exception, X> mapper) {
1617      super(delegate);
1618
1619      this.mapper = checkNotNull(mapper);
1620    }
1621
1622    @Override
1623    protected X mapException(Exception e) {
1624      return mapper.apply(e);
1625    }
1626  }
1627}