001    /*
002     * Copyright (C) 2006 The Guava Authors
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package com.google.common.util.concurrent;
018    
019    import static com.google.common.base.Preconditions.checkArgument;
020    import static com.google.common.base.Preconditions.checkNotNull;
021    import static com.google.common.base.Preconditions.checkState;
022    import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor;
023    import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
024    import static java.lang.Thread.currentThread;
025    import static java.util.Arrays.asList;
026    import static java.util.concurrent.TimeUnit.NANOSECONDS;
027    
028    import com.google.common.annotations.Beta;
029    import com.google.common.base.Function;
030    import com.google.common.base.Preconditions;
031    import com.google.common.collect.ImmutableList;
032    import com.google.common.collect.Lists;
033    import com.google.common.collect.Ordering;
034    
035    import java.lang.reflect.Constructor;
036    import java.lang.reflect.InvocationTargetException;
037    import java.lang.reflect.UndeclaredThrowableException;
038    import java.util.Arrays;
039    import java.util.List;
040    import java.util.concurrent.BlockingQueue;
041    import java.util.concurrent.CancellationException;
042    import java.util.concurrent.CountDownLatch;
043    import java.util.concurrent.ExecutionException;
044    import java.util.concurrent.Executor;
045    import java.util.concurrent.Future;
046    import java.util.concurrent.LinkedBlockingQueue;
047    import java.util.concurrent.TimeUnit;
048    import java.util.concurrent.TimeoutException;
049    import java.util.concurrent.atomic.AtomicInteger;
050    
051    import javax.annotation.Nullable;
052    
053    /**
054     * Static utility methods pertaining to the {@link Future} interface.
055     *
056     * @author Kevin Bourrillion
057     * @author Nishant Thakkar
058     * @author Sven Mawson
059     * @since 1.0
060     */
061    @Beta
062    public final class Futures {
063      private Futures() {}
064    
065      /**
066       * Returns an uninterruptible view of a {@code Future}. If a thread is
067       * interrupted during an attempt to {@code get()} from the returned future, it
068       * continues to wait on the result until it is available or the timeout
069       * elapses, and only then re-interrupts the thread.
070       * @deprecated Use
071       * {@link Uninterruptibles#getUninterruptibly(Future) getUninterruptibly}.
072       * <b>This method is scheduled for deletion in Guava Release 11.</b>
073       */
074      @Deprecated @SuppressWarnings("deprecation")
075      public
076      static <V> UninterruptibleFuture<V> makeUninterruptible(
077          final Future<V> future) {
078        checkNotNull(future);
079        if (future instanceof UninterruptibleFuture<?>) {
080          return (UninterruptibleFuture<V>) future;
081        }
082        return new UninterruptibleFuture<V>() {
083          @Override
084          public boolean cancel(boolean mayInterruptIfRunning) {
085            return future.cancel(mayInterruptIfRunning);
086          }
087          @Override
088          public boolean isCancelled() {
089            return future.isCancelled();
090          }
091          @Override
092          public boolean isDone() {
093            return future.isDone();
094          }
095    
096          @Override
097          public V get(long timeout, TimeUnit unit)
098              throws TimeoutException, ExecutionException {
099            return Uninterruptibles.getUninterruptibly(future, timeout, unit);
100          }
101    
102          @Override
103          public V get() throws ExecutionException {
104            return Uninterruptibles.getUninterruptibly(future);
105          }
106        };
107      }
108    
109      /**
110       *
111       * <p>Creates a {@link ListenableFuture} out of a normal {@link Future}. The
112       * returned future will create a thread to wait for the source future to
113       * complete before executing the listeners.
114       *
115       * <p><b>Warning:</b> If the input future does not already implement {@link
116       * ListenableFuture}, the returned future will emulate {@link
117       * ListenableFuture#addListener} by taking a thread from an internal,
118       * unbounded pool at the first call to {@code addListener} and holding it
119       * until the future is {@linkplain Future#isDone() done}.
120       *
121       * @deprecated Prefer to create {@code ListenableFuture} instances with {@link
122       *     SettableFuture}, {@link MoreExecutors#listeningDecorator(
123       *     java.util.concurrent.ExecutorService)}, {@link ListenableFutureTask},
124       *     {@link AbstractFuture}, and other utilities over creating plain {@code
125       *     Future} instances to be upgraded to {@code ListenableFuture} after the
126       *     fact. If this is not possible, the functionality of {@code
127       *     makeListenable} is now available as {@link
128       *     JdkFutureAdapters#listenInPoolThread}. <b>This method is scheduled
129       *     for deletion from Guava in Guava release 11.0.</b>
130       */
131      @Deprecated
132      public
133      static <V> ListenableFuture<V> makeListenable(Future<V> future) {
134        return JdkFutureAdapters.listenInPoolThread(future);
135      }
136    
137      /**
138       * Creates a {@link CheckedFuture} out of a normal {@link Future} and a
139       * {@link Function} that maps from {@link Exception} instances into the
140       * appropriate checked type.
141       *
142       * <p><b>Warning:</b> If the input future does not implement {@link
143       * ListenableFuture}, the returned future will emulate {@link
144       * ListenableFuture#addListener} by taking a thread from an internal,
145       * unbounded pool at the first call to {@code addListener} and holding it
146       * until the future is {@linkplain Future#isDone() done}.
147       *
148       * <p>The given mapping function will be applied to an
149       * {@link InterruptedException}, a {@link CancellationException}, or an
150       * {@link ExecutionException} with the actual cause of the exception.
151       * See {@link Future#get()} for details on the exceptions thrown.
152       *
153       * @deprecated Obtain a {@link ListenableFuture}, following the advice in its
154       *     documentation and use {@link #makeChecked(ListenableFuture, Function)}.
155       *     <b>This method is scheduled for deletion from Guava in Guava release
156       *     11.0.</b>
157       */
158      @Deprecated
159      public
160      static <V, X extends Exception> CheckedFuture<V, X> makeChecked(
161          Future<V> future, Function<Exception, X> mapper) {
162        return new MappingCheckedFuture<V, X>(makeListenable(future), mapper);
163      }
164    
165      /**
166       * Creates a {@link CheckedFuture} out of a normal {@link ListenableFuture}
167       * and a {@link Function} that maps from {@link Exception} instances into the
168       * appropriate checked type.
169       *
170       * <p>The given mapping function will be applied to an
171       * {@link InterruptedException}, a {@link CancellationException}, or an
172       * {@link ExecutionException} with the actual cause of the exception.
173       * See {@link Future#get()} for details on the exceptions thrown.
174       *
175       * @since 9.0 (source-compatible since 1.0)
176       */
177      public static <V, X extends Exception> CheckedFuture<V, X> makeChecked(
178          ListenableFuture<V> future, Function<Exception, X> mapper) {
179        return new MappingCheckedFuture<V, X>(checkNotNull(future), mapper);
180      }
181    
182      /**
183       * Creates a {@code ListenableFuture} which has its value set immediately upon
184       * construction. The getters just return the value. This {@code Future} can't
185       * be canceled or timed out and its {@code isDone()} method always returns
186       * {@code true}.
187       */
188      public static <V> ListenableFuture<V> immediateFuture(@Nullable V value) {
189        SettableFuture<V> future = SettableFuture.create();
190        future.set(value);
191        return future;
192      }
193    
194      /**
195       * Returns a {@code CheckedFuture} which has its value set immediately upon
196       * construction.
197       *
198       * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()}
199       * method always returns {@code true}. Calling {@code get()} or {@code
200       * checkedGet()} will immediately return the provided value.
201       */
202      public static <V, X extends Exception> CheckedFuture<V, X>
203          immediateCheckedFuture(@Nullable V value) {
204        SettableFuture<V> future = SettableFuture.create();
205        future.set(value);
206        return Futures.makeChecked(future, new Function<Exception, X>() {
207          @Override
208          public X apply(Exception e) {
209            throw new AssertionError("impossible");
210          }
211        });
212      }
213    
214      /**
215       * Returns a {@code ListenableFuture} which has an exception set immediately
216       * upon construction.
217       *
218       * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()}
219       * method always returns {@code true}. Calling {@code get()} will immediately
220       * throw the provided {@code Throwable} wrapped in an {@code
221       * ExecutionException}.
222       *
223       * @throws Error if the throwable is an {@link Error}.
224       */
225      public static <V> ListenableFuture<V> immediateFailedFuture(
226          Throwable throwable) {
227        checkNotNull(throwable);
228        SettableFuture<V> future = SettableFuture.create();
229        future.setException(throwable);
230        return future;
231      }
232    
233      /**
234       * Returns a {@code CheckedFuture} which has an exception set immediately upon
235       * construction.
236       *
237       * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()}
238       * method always returns {@code true}. Calling {@code get()} will immediately
239       * throw the provided {@code Throwable} wrapped in an {@code
240       * ExecutionException}, and calling {@code checkedGet()} will throw the
241       * provided exception itself.
242       *
243       * @throws Error if the throwable is an {@link Error}.
244       */
245      public static <V, X extends Exception> CheckedFuture<V, X>
246          immediateFailedCheckedFuture(final X exception) {
247        checkNotNull(exception);
248        return makeChecked(Futures.<V>immediateFailedFuture(exception),
249            new Function<Exception, X>() {
250              @Override
251              public X apply(Exception e) {
252                return exception;
253              }
254            });
255      }
256    
257      /**
258       * Returns a new {@code ListenableFuture} whose result is asynchronously
259       * derived from the result of the given {@code Future}. More precisely, the
260       * returned {@code Future} takes its result from a {@code Future} produced by
261       * applying the given {@code Function} to the result of the original {@code
262       * Future}. Example:
263       *
264       * <pre>   {@code
265       *   ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
266       *   Function<RowKey, ListenableFuture<QueryResult>> queryFunction =
267       *       new Function<RowKey, ListenableFuture<QueryResult>>() {
268       *         public ListenableFuture<QueryResult> apply(RowKey rowKey) {
269       *           return dataService.read(rowKey);
270       *         }
271       *       };
272       *   ListenableFuture<QueryResult> queryFuture =
273       *       chain(queryFuture, queryFunction);
274       * }</pre>
275       *
276       * <p>Note: This overload of {@code chain} is designed for cases in which the
277       * work of creating the derived future is fast and lightweight, as the method
278       * does not accept an {@code Executor} to perform the the work in. For heavier
279       * derivations, this overload carries some caveats: First, the thread that the
280       * derivation runs in depends on whether the input {@code Future} is done at
281       * the time {@code chain} is called. In particular, if called late, {@code
282       * chain} will run the derivation in the thread that called {@code chain}.
283       * Second, derivations may run in an internal thread of the system responsible
284       * for the input {@code Future}, such as an RPC network thread. Finally,
285       * during the execution of a {@link MoreExecutors#sameThreadExecutor
286       * sameThreadExecutor} {@code chain} function, all other registered but
287       * unexecuted listeners are prevented from running, even if those listeners
288       * are to run in other executors.
289       *
290       * <p>The returned {@code Future} attempts to keep its cancellation state in
291       * sync with that of the input future and that of the future returned by the
292       * chain function. That is, if the returned {@code Future} is cancelled, it
293       * will attempt to cancel the other two, and if either of the other two is
294       * cancelled, the returned {@code Future} will receive a callback in which it
295       * will attempt to cancel itself.
296       *
297       * <p>The typical use for this method would be when a RPC call is dependent on
298       * the results of another RPC.  One would call the first RPC (input), create a
299       * function that calls another RPC based on input's result, and then call
300       * chain on input and that function to get a {@code ListenableFuture} of
301       * the result.
302       *
303       * @param input The future to chain
304       * @param function A function to chain the results of the provided future
305       *     to the results of the returned future.  This will be run in the thread
306       *     that notifies input it is complete.
307       * @return A future that holds result of the chain.
308       */
309      public static <I, O> ListenableFuture<O> chain(ListenableFuture<I> input,
310          Function<? super I, ? extends ListenableFuture<? extends O>> function) {
311        return chain(input, function, MoreExecutors.sameThreadExecutor());
312      }
313    
314      /**
315       * Returns a new {@code ListenableFuture} whose result is asynchronously
316       * derived from the result of the given {@code Future}. More precisely, the
317       * returned {@code Future} takes its result from a {@code Future} produced by
318       * applying the given {@code Function} to the result of the original {@code
319       * Future}. Example:
320       *
321       * <pre>   {@code
322       *   ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
323       *   Function<RowKey, ListenableFuture<QueryResult>> queryFunction =
324       *       new Function<RowKey, ListenableFuture<QueryResult>>() {
325       *         public ListenableFuture<QueryResult> apply(RowKey rowKey) {
326       *           return dataService.read(rowKey);
327       *         }
328       *       };
329       *   ListenableFuture<QueryResult> queryFuture =
330       *       chain(queryFuture, queryFunction, executor);
331       * }</pre>
332       *
333       * <p>The returned {@code Future} attempts to keep its cancellation state in
334       * sync with that of the input future and that of the future returned by the
335       * chain function. That is, if the returned {@code Future} is cancelled, it
336       * will attempt to cancel the other two, and if either of the other two is
337       * cancelled, the returned {@code Future} will receive a callback in which it
338       * will attempt to cancel itself.
339       *
340       * <p>Note: For cases in which the work of creating the derived future is fast
341       * and lightweight, consider {@linkplain Futures#chain(ListenableFuture,
342       * Function) the other overload} or explicit use of {@link
343       * MoreExecutors#sameThreadExecutor}. For heavier derivations, this choice
344       * carries some caveats: First, the thread that the derivation runs in depends
345       * on whether the input {@code Future} is done at the time {@code chain} is
346       * called. In particular, if called late, {@code chain} will run the
347       * derivation in the thread that called {@code chain}. Second, derivations may
348       * run in an internal thread of the system responsible for the input {@code
349       * Future}, such as an RPC network thread. Finally, during the execution of a
350       * {@link MoreExecutors#sameThreadExecutor sameThreadExecutor} {@code chain}
351       * function, all other registered but unexecuted listeners are prevented from
352       * running, even if those listeners are to run in other executors.
353       *
354       * @param input The future to chain
355       * @param function A function to chain the results of the provided future
356       *     to the results of the returned future.
357       * @param exec Executor to run the function in.
358       * @return A future that holds result of the chain.
359       */
360      public static <I, O> ListenableFuture<O> chain(ListenableFuture<I> input,
361          Function<? super I, ? extends ListenableFuture<? extends O>> function,
362          Executor exec) {
363        ChainingListenableFuture<I, O> chain =
364            new ChainingListenableFuture<I, O>(function, input);
365        input.addListener(chain, exec);
366        return chain;
367      }
368    
369      /**
370       * Returns a new {@code ListenableFuture} whose result is the product of
371       * applying the given {@code Function} to the result of the given {@code
372       * Future}. Example:
373       *
374       * <pre>   {@code
375       *   ListenableFuture<QueryResult> queryFuture = ...;
376       *   Function<QueryResult, List<Row>> rowsFunction =
377       *       new Function<QueryResult, List<Row>>() {
378       *         public List<Row> apply(QueryResult queryResult) {
379       *           return queryResult.getRows();
380       *         }
381       *       };
382       *   ListenableFuture<List<Row>> rowsFuture =
383       *       transform(queryFuture, rowsFunction);
384       * }</pre>
385       *
386       * <p>Note: This overload of {@code transform} is designed for cases in which
387       * the transformation is fast and lightweight, as the method does not accept
388       * an {@code Executor} to perform the the work in. For heavier
389       * transformations, this overload carries some caveats: First, the thread that
390       * the transformation runs in depends on whether the input {@code Future} is
391       * done at the time {@code transform} is called. In particular, if called
392       * late, {@code transform} will perform the transformation in the thread that
393       * called {@code transform}. Second, transformations may run in an internal
394       * thread of the system responsible for the input {@code Future}, such as an
395       * RPC network thread. Finally, during the execution of a {@link
396       * MoreExecutors#sameThreadExecutor sameThreadExecutor} transformation, all
397       * other registered but unexecuted listeners are prevented from running, even
398       * if those listeners are to run in other executors.
399       *
400       * <p>The returned {@code Future} attempts to keep its cancellation state in
401       * sync with that of the input future. That is, if the returned {@code Future}
402       * is cancelled, it will attempt to cancel the input, and if the input is
403       * cancelled, the returned {@code Future} will receive a callback in which it
404       * will attempt to cancel itself.
405       *
406       * <p>An example use of this method is to convert a serializable object
407       * returned from an RPC into a POJO.
408       *
409       * @param future The future to transform
410       * @param function A Function to transform the results of the provided future
411       *     to the results of the returned future.  This will be run in the thread
412       *     that notifies input it is complete.
413       * @return A future that holds result of the transformation.
414       * @since 9.0 (in 1.0 as {@code compose})
415       */
416      public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> future,
417          final Function<? super I, ? extends O> function) {
418        return transform(future, function, MoreExecutors.sameThreadExecutor());
419      }
420    
421      /**
422       * Returns a new {@code ListenableFuture} whose result is the product of
423       * applying the given {@code Function} to the result of the given {@code
424       * Future}. Example:
425       *
426       * <pre>   {@code
427       *   ListenableFuture<QueryResult> queryFuture = ...;
428       *   Function<QueryResult, List<Row>> rowsFunction =
429       *       new Function<QueryResult, List<Row>>() {
430       *         public List<Row> apply(QueryResult queryResult) {
431       *           return queryResult.getRows();
432       *         }
433       *       };
434       *   ListenableFuture<List<Row>> rowsFuture =
435       *       transform(queryFuture, rowsFunction, executor);
436       * }</pre>
437       *
438       * <p>The returned {@code Future} attempts to keep its cancellation state in
439       * sync with that of the input future. That is, if the returned {@code Future}
440       * is cancelled, it will attempt to cancel the input, and if the input is
441       * cancelled, the returned {@code Future} will receive a callback in which it
442       * will attempt to cancel itself.
443       *
444       * <p>An example use of this method is to convert a serializable object
445       * returned from an RPC into a POJO.
446       *
447       * <p>Note: For cases in which the transformation is fast and lightweight,
448       * consider {@linkplain Futures#transform(ListenableFuture, Function) the
449       * other overload} or explicit use of {@link
450       * MoreExecutors#sameThreadExecutor}. For heavier transformations, this choice
451       * carries some caveats: First, the thread that the transformation runs in
452       * depends on whether the input {@code Future} is done at the time {@code
453       * transform} is called. In particular, if called late, {@code transform} will
454       * perform the transformation in the thread that called {@code transform}.
455       * Second, transformations may run in an internal thread of the system
456       * responsible for the input {@code Future}, such as an RPC network thread.
457       * Finally, during the execution of a {@link MoreExecutors#sameThreadExecutor
458       * sameThreadExecutor} transformation, all other registered but unexecuted
459       * listeners are prevented from running, even if those listeners are to run
460       * in other executors.
461       *
462       * @param future The future to transform
463       * @param function A Function to transform the results of the provided future
464       *     to the results of the returned future.
465       * @param exec Executor to run the function in.
466       * @return A future that holds result of the transformation.
467       * @since 9.0 (in 2.0 as {@code compose})
468       */
469      public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> future,
470          final Function<? super I, ? extends O> function, Executor exec) {
471        checkNotNull(function);
472        Function<I, ListenableFuture<O>> wrapperFunction
473            = new Function<I, ListenableFuture<O>>() {
474                @Override public ListenableFuture<O> apply(I input) {
475                  O output = function.apply(input);
476                  return immediateFuture(output);
477                }
478            };
479        return chain(future, wrapperFunction, exec);
480      }
481    
482      /**
483       * Like {@link #transform(ListenableFuture, Function)} except that the
484       * transformation {@code function} is invoked on each call to
485       * {@link Future#get() get()} on the returned future.
486       *
487       * <p>The returned {@code Future} reflects the input's cancellation
488       * state directly, and any attempt to cancel the returned Future is likewise
489       * passed through to the input Future.
490       *
491       * <p>Note that calls to {@linkplain Future#get(long, TimeUnit) timed get}
492       * only apply the timeout to the execution of the underlying {@code Future},
493       * <em>not</em> to the execution of the transformation function.
494       *
495       * <p>The primary audience of this method is callers of {@code transform}
496       * who don't have a {@code ListenableFuture} available and
497       * do not mind repeated, lazy function evaluation.
498       *
499       * @param future The future to transform
500       * @param function A Function to transform the results of the provided future
501       *     to the results of the returned future.
502       * @return A future that returns the result of the transformation.
503       * @since 10.0
504       */
505      @Beta
506      public static <I, O> Future<O> lazyTransform(final Future<I> future,
507          final Function<? super I, ? extends O> function) {
508        checkNotNull(future);
509        checkNotNull(function);
510        return new Future<O>() {
511    
512          @Override
513          public boolean cancel(boolean mayInterruptIfRunning) {
514            return future.cancel(mayInterruptIfRunning);
515          }
516    
517          @Override
518          public boolean isCancelled() {
519            return future.isCancelled();
520          }
521    
522          @Override
523          public boolean isDone() {
524            return future.isDone();
525          }
526    
527          @Override
528          public O get() throws InterruptedException, ExecutionException {
529            return applyTransformation(future.get());
530          }
531    
532          @Override
533          public O get(long timeout, TimeUnit unit)
534              throws InterruptedException, ExecutionException, TimeoutException {
535            return applyTransformation(future.get(timeout, unit));
536          }
537    
538          private O applyTransformation(I input) throws ExecutionException {
539            try {
540              return function.apply(input);
541            } catch (Throwable t) {
542              throw new ExecutionException(t);
543            }
544          }
545        };
546      }
547    
548      /**
549       * Returns a new {@code Future} whose result is the product of applying the
550       * given {@code Function} to the result of the given {@code Future}. Example:
551       *
552       * <pre>   {@code
553       *   Future<QueryResult> queryFuture = ...;
554       *   Function<QueryResult, List<Row>> rowsFunction =
555       *       new Function<QueryResult, List<Row>>() {
556       *         public List<Row> apply(QueryResult queryResult) {
557       *           return queryResult.getRows();
558       *         }
559       *       };
560       *   Future<List<Row>> rowsFuture = transform(queryFuture, rowsFunction);
561       * }</pre>
562       *
563       * <p>Each call to {@code Future<O>.get(*)} results in a call to
564       * {@code Future<I>.get(*)}, but {@code function} is only applied once, so it
565       * is assumed that {@code Future<I>.get(*)} is idempotent.
566       *
567       * <p>When calling {@link Future#get(long, TimeUnit)} on the returned
568       * future, the timeout only applies to the future passed in to this method.
569       * Any additional time taken by applying {@code function} is not considered.
570       * (Exception: If the input future is a {@link ListenableFuture}, timeouts
571       * will be strictly enforced.)
572       *
573       * @param future The future to transform
574       * @param function A Function to transform the results of the provided future
575       *     to the results of the returned future.  This will be run in the thread
576       *     that calls one of the varieties of {@code get()}.
577       * @return A future that computes result of the transformation
578       * @since 9.0 (in 1.0 as {@code compose})
579       * @deprecated Obtain a {@code ListenableFuture} (following the advice in its
580       *     documentation) and use {@link #transform(ListenableFuture, Function)}
581       *     or use {@link #lazyTransform(Future, Function)}, which will apply the
582       *     transformation on each call to {@code get()}.
583       *     <b>This method is scheduled for deletion from Guava in Guava release
584       *     11.0.</b>
585       */
586      @Deprecated
587      public static <I, O> Future<O> transform(final Future<I> future,
588          final Function<? super I, ? extends O> function) {
589        if (future instanceof ListenableFuture) {
590          return transform((ListenableFuture<I>) future, function);
591        }
592        checkNotNull(future);
593        checkNotNull(function);
594        return new Future<O>() {
595    
596          /*
597           * Concurrency detail:
598           *
599           * <p>To preserve the idempotency of calls to this.get(*) calls to the
600           * function are only applied once. A lock is required to prevent multiple
601           * applications of the function. The calls to future.get(*) are performed
602           * outside the lock, as is required to prevent calls to
603           * get(long, TimeUnit) to persist beyond their timeout.
604           *
605           * <p>Calls to future.get(*) on every call to this.get(*) also provide
606           * the cancellation behavior for this.
607           *
608           * <p>(Consider: in thread A, call get(), in thread B call get(long,
609           * TimeUnit). Thread B may have to wait for Thread A to finish, which
610           * would be unacceptable.)
611           *
612           * <p>Note that each call to Future<O>.get(*) results in a call to
613           * Future<I>.get(*), but the function is only applied once, so
614           * Future<I>.get(*) is assumed to be idempotent.
615           */
616    
617          private final Object lock = new Object();
618          private boolean set = false;
619          private O value = null;
620          private ExecutionException exception = null;
621    
622          @Override
623          public O get() throws InterruptedException, ExecutionException {
624            return apply(future.get());
625          }
626    
627          @Override
628          public O get(long timeout, TimeUnit unit) throws InterruptedException,
629              ExecutionException, TimeoutException {
630            return apply(future.get(timeout, unit));
631          }
632    
633          private O apply(I raw) throws ExecutionException {
634            synchronized (lock) {
635              if (!set) {
636                try {
637                  value = function.apply(raw);
638                } catch (RuntimeException e) {
639                  exception = new ExecutionException(e);
640                } catch (Error e) {
641                  exception = new ExecutionException(e);
642                }
643                set = true;
644              }
645    
646              if (exception != null) {
647                throw exception;
648              }
649              return value;
650            }
651          }
652    
653          @Override
654          public boolean cancel(boolean mayInterruptIfRunning) {
655            return future.cancel(mayInterruptIfRunning);
656          }
657    
658          @Override
659          public boolean isCancelled() {
660            return future.isCancelled();
661          }
662    
663          @Override
664          public boolean isDone() {
665            return future.isDone();
666          }
667        };
668      }
669    
670      /**
671       * An implementation of {@code ListenableFuture} that also implements
672       * {@code Runnable} so that it can be used to nest ListenableFutures.
673       * Once the passed-in {@code ListenableFuture} is complete, it calls the
674       * passed-in {@code Function} to generate the result.
675       *
676       * <p>If the function throws any checked exceptions, they should be wrapped
677       * in a {@code UndeclaredThrowableException} so that this class can get
678       * access to the cause.
679       */
680      private static class ChainingListenableFuture<I, O>
681          extends AbstractFuture<O> implements Runnable {
682    
683        private Function<? super I, ? extends ListenableFuture<? extends O>>
684            function;
685        private ListenableFuture<? extends I> inputFuture;
686        private volatile ListenableFuture<? extends O> outputFuture;
687        private final BlockingQueue<Boolean> mayInterruptIfRunningChannel =
688            new LinkedBlockingQueue<Boolean>(1);
689        private final CountDownLatch outputCreated = new CountDownLatch(1);
690    
691        private ChainingListenableFuture(
692            Function<? super I, ? extends ListenableFuture<? extends O>> function,
693            ListenableFuture<? extends I> inputFuture) {
694          this.function = checkNotNull(function);
695          this.inputFuture = checkNotNull(inputFuture);
696        }
697    
698        /**
699         * Delegate the get() to the input and output futures, in case
700         * their implementations defer starting computation until their
701         * own get() is invoked.
702         */
703        @Override
704        public O get() throws InterruptedException, ExecutionException {
705          if (!isDone()) {
706            // Invoking get on the inputFuture will ensure our own run()
707            // method below is invoked as a listener when inputFuture sets
708            // its value.  Therefore when get() returns we should then see
709            // the outputFuture be created.
710            ListenableFuture<? extends I> inputFuture = this.inputFuture;
711            if (inputFuture != null) {
712              inputFuture.get();
713            }
714    
715            // If our listener was scheduled to run on an executor we may
716            // need to wait for our listener to finish running before the
717            // outputFuture has been constructed by the function.
718            outputCreated.await();
719    
720            // Like above with the inputFuture, we have a listener on
721            // the outputFuture that will set our own value when its
722            // value is set.  Invoking get will ensure the output can
723            // complete and invoke our listener, so that we can later
724            // get the result.
725            ListenableFuture<? extends O> outputFuture = this.outputFuture;
726            if (outputFuture != null) {
727              outputFuture.get();
728            }
729          }
730          return super.get();
731        }
732    
733        /**
734         * Delegate the get() to the input and output futures, in case
735         * their implementations defer starting computation until their
736         * own get() is invoked.
737         */
738        @Override
739        public O get(long timeout, TimeUnit unit) throws TimeoutException,
740            ExecutionException, InterruptedException {
741          if (!isDone()) {
742            // Use a single time unit so we can decrease remaining timeout
743            // as we wait for various phases to complete.
744            if (unit != NANOSECONDS) {
745              timeout = NANOSECONDS.convert(timeout, unit);
746              unit = NANOSECONDS;
747            }
748    
749            // Invoking get on the inputFuture will ensure our own run()
750            // method below is invoked as a listener when inputFuture sets
751            // its value.  Therefore when get() returns we should then see
752            // the outputFuture be created.
753            ListenableFuture<? extends I> inputFuture = this.inputFuture;
754            if (inputFuture != null) {
755              long start = System.nanoTime();
756              inputFuture.get(timeout, unit);
757              timeout -= Math.max(0, System.nanoTime() - start);
758            }
759    
760            // If our listener was scheduled to run on an executor we may
761            // need to wait for our listener to finish running before the
762            // outputFuture has been constructed by the function.
763            long start = System.nanoTime();
764            if (!outputCreated.await(timeout, unit)) {
765              throw new TimeoutException();
766            }
767            timeout -= Math.max(0, System.nanoTime() - start);
768    
769            // Like above with the inputFuture, we have a listener on
770            // the outputFuture that will set our own value when its
771            // value is set.  Invoking get will ensure the output can
772            // complete and invoke our listener, so that we can later
773            // get the result.
774            ListenableFuture<? extends O> outputFuture = this.outputFuture;
775            if (outputFuture != null) {
776              outputFuture.get(timeout, unit);
777            }
778          }
779          return super.get(timeout, unit);
780        }
781    
782        @Override
783        public boolean cancel(boolean mayInterruptIfRunning) {
784          /*
785           * Our additional cancellation work needs to occur even if
786           * !mayInterruptIfRunning, so we can't move it into interruptTask().
787           */
788          if (super.cancel(mayInterruptIfRunning)) {
789            try {
790              // This should never block since only one thread is allowed to cancel
791              // this Future.
792              mayInterruptIfRunningChannel.put(mayInterruptIfRunning);
793            } catch (InterruptedException ignored) {
794              Thread.currentThread().interrupt();
795            }
796            cancel(inputFuture, mayInterruptIfRunning);
797            cancel(outputFuture, mayInterruptIfRunning);
798            return true;
799          }
800          return false;
801        }
802    
803        private void cancel(@Nullable Future<?> future,
804            boolean mayInterruptIfRunning) {
805          if (future != null) {
806            future.cancel(mayInterruptIfRunning);
807          }
808        }
809    
810        @Override
811        public void run() {
812          try {
813            I sourceResult;
814            try {
815              sourceResult = getUninterruptibly(inputFuture);
816            } catch (CancellationException e) {
817              // Cancel this future and return.
818              // At this point, inputFuture is cancelled and outputFuture doesn't
819              // exist, so the value of mayInterruptIfRunning is irrelevant.
820              cancel(false);
821              return;
822            } catch (ExecutionException e) {
823              // Set the cause of the exception as this future's exception
824              setException(e.getCause());
825              return;
826            }
827    
828            final ListenableFuture<? extends O> outputFuture = this.outputFuture =
829                function.apply(sourceResult);
830            if (isCancelled()) {
831              // Handles the case where cancel was called while the function was
832              // being applied.
833              try {
834                // There is a gap in cancel(boolean) between calling sync.cancel()
835                // and storing the value of mayInterruptIfRunning, so this thread
836                // needs to block, waiting for that value.
837                outputFuture.cancel(mayInterruptIfRunningChannel.take());
838              } catch (InterruptedException ignored) {
839                Thread.currentThread().interrupt();
840              }
841              this.outputFuture = null;
842              return;
843            }
844            outputFuture.addListener(new Runnable() {
845                @Override
846                public void run() {
847                  try {
848                    // Here it would have been nice to have had an
849                    // UninterruptibleListenableFuture, but we don't want to start a
850                    // combinatorial explosion of interfaces, so we have to make do.
851                    set(getUninterruptibly(outputFuture));
852                  } catch (CancellationException e) {
853                    // Cancel this future and return.
854                    // At this point, inputFuture and outputFuture are done, so the
855                    // value of mayInterruptIfRunning is irrelevant.
856                    cancel(false);
857                    return;
858                  } catch (ExecutionException e) {
859                    // Set the cause of the exception as this future's exception
860                    setException(e.getCause());
861                  } finally {
862                    // Don't pin inputs beyond completion
863                    ChainingListenableFuture.this.outputFuture = null;
864                  }
865                }
866              }, MoreExecutors.sameThreadExecutor());
867          } catch (UndeclaredThrowableException e) {
868            // Set the cause of the exception as this future's exception
869            setException(e.getCause());
870          } catch (RuntimeException e) {
871            // This exception is irrelevant in this thread, but useful for the
872            // client
873            setException(e);
874          } catch (Error e) {
875            // Propagate errors up ASAP - our superclass will rethrow the error
876            setException(e);
877          } finally {
878            // Don't pin inputs beyond completion
879            function = null;
880            inputFuture = null;
881            // Allow our get routines to examine outputFuture now.
882            outputCreated.countDown();
883          }
884        }
885      }
886    
887      /**
888       * Creates a new {@code ListenableFuture} whose value is a list containing the
889       * values of all its input futures, if all succeed. If any input fails, the
890       * returned future fails.
891       *
892       * <p>The list of results is in the same order as the input list.
893       *
894       * <p>Canceling this future does not cancel any of the component futures;
895       * however, if any of the provided futures fails or is canceled, this one is,
896       * too.
897       *
898       * @param futures futures to combine
899       * @return a future that provides a list of the results of the component
900       *         futures
901       * @since 10.0
902       */
903      @Beta
904      public static <V> ListenableFuture<List<V>> allAsList(
905          ListenableFuture<? extends V>... futures) {
906        return new ListFuture<V>(ImmutableList.copyOf(futures), true,
907            MoreExecutors.sameThreadExecutor());
908      }
909    
910      /**
911       * Creates a new {@code ListenableFuture} whose value is a list containing the
912       * values of all its input futures, if all succeed. If any input fails, the
913       * returned future fails.
914       *
915       * <p>The list of results is in the same order as the input list.
916       *
917       * <p>Canceling this future does not cancel any of the component futures;
918       * however, if any of the provided futures fails or is canceled, this one is,
919       * too.
920       *
921       * @param futures futures to combine
922       * @return a future that provides a list of the results of the component
923       *         futures
924       * @since 10.0
925       */
926      @Beta
927      public static <V> ListenableFuture<List<V>> allAsList(
928          Iterable<? extends ListenableFuture<? extends V>> futures) {
929        return new ListFuture<V>(ImmutableList.copyOf(futures), true,
930            MoreExecutors.sameThreadExecutor());
931      }
932    
933      /**
934       * Creates a new {@code ListenableFuture} whose value is a list containing the
935       * values of all its successful input futures. The list of results is in the
936       * same order as the input list, and if any of the provided futures fails or
937       * is canceled, its corresponding position will contain {@code null} (which is
938       * indistinguishable from the future having a successful value of
939       * {@code null}).
940       *
941       * @param futures futures to combine
942       * @return a future that provides a list of the results of the component
943       *         futures
944       * @since 10.0
945       */
946      @Beta
947      public static <V> ListenableFuture<List<V>> successfulAsList(
948          ListenableFuture<? extends V>... futures) {
949        return new ListFuture<V>(ImmutableList.copyOf(futures), false,
950            MoreExecutors.sameThreadExecutor());
951      }
952    
953      /**
954       * Creates a new {@code ListenableFuture} whose value is a list containing the
955       * values of all its successful input futures. The list of results is in the
956       * same order as the input list, and if any of the provided futures fails or
957       * is canceled, its corresponding position will contain {@code null} (which is
958       * indistinguishable from the future having a successful value of
959       * {@code null}).
960       *
961       * @param futures futures to combine
962       * @return a future that provides a list of the results of the component
963       *         futures
964       * @since 10.0
965       */
966      @Beta
967      public static <V> ListenableFuture<List<V>> successfulAsList(
968          Iterable<? extends ListenableFuture<? extends V>> futures) {
969        return new ListFuture<V>(ImmutableList.copyOf(futures), false,
970            MoreExecutors.sameThreadExecutor());
971      }
972    
973      /**
974       * Registers separate success and failure callbacks to be run when the {@code
975       * Future}'s computation is {@linkplain java.util.concurrent.Future#isDone()
976       * complete} or, if the computation is already complete, immediately.
977       *
978       * <p>There is no guaranteed ordering of execution of callbacks, but any
979       * callback added through this method is guaranteed to be called once the
980       * computation is complete.
981       *
982       * Example: <pre> {@code
983       * ListenableFuture<QueryResult> future = ...;
984       * addCallback(future,
985       *     new FutureCallback<QueryResult> {
986       *       public void onSuccess(QueryResult result) {
987       *         storeInCache(result);
988       *       }
989       *       public void onFailure(Throwable t) {
990       *         reportError(t);
991       *       }
992       *     });}</pre>
993       *
994       * <p>Note: This overload of {@code addCallback} is designed for cases in
995       * which the callack is fast and lightweight, as the method does not accept
996       * an {@code Executor} to perform the the work in. For heavier
997       * callbacks, this overload carries some caveats: First, the thread that
998       * the callback runs in depends on whether the input {@code Future} is
999       * done at the time {@code addCallback} is called. In particular, if called
1000       * late, {@code addCallback} will execute the callback in the thread that
1001       * called {@code addCallback}. Second, callbacks may run in an internal
1002       * thread of the system responsible for the input {@code Future}, such as an
1003       * RPC network thread. Finally, during the execution of a {@link
1004       * MoreExecutors#sameThreadExecutor sameThreadExecutor} callback, all other
1005       * registered but unexecuted listeners are prevented from running, even if
1006       * those listeners are to run in other executors.
1007       *
1008       * <p>For a more general interface to attach a completion listener to a
1009       * {@code Future}, see {@link ListenableFuture#addListener addListener}.
1010       *
1011       * @param future The future attach the callback to.
1012       * @param callback The callback to invoke when {@code future} is completed.
1013       * @since 10.0
1014       */
1015      public static <V> void addCallback(ListenableFuture<V> future,
1016          FutureCallback<? super V> callback) {
1017        addCallback(future, callback, MoreExecutors.sameThreadExecutor());
1018      }
1019    
1020      /**
1021       * Registers separate success and failure callbacks to be run when the {@code
1022       * Future}'s computation is {@linkplain java.util.concurrent.Future#isDone()
1023       * complete} or, if the computation is already complete, immediately.
1024       *
1025       * <p>The callback is run in {@code executor}.
1026       * There is no guaranteed ordering of execution of callbacks, but any
1027       * callback added through this method is guaranteed to be called once the
1028       * computation is complete.
1029       *
1030       * Example: <pre> {@code
1031       * ListenableFuture<QueryResult> future = ...;
1032       * Executor e = ...
1033       * addCallback(future, e,
1034       *     new FutureCallback<QueryResult> {
1035       *       public void onSuccess(QueryResult result) {
1036       *         storeInCache(result);
1037       *       }
1038       *       public void onFailure(Throwable t) {
1039       *         reportError(t);
1040       *       }
1041       *     });}</pre>
1042       *
1043       * When the callback is fast and lightweight consider
1044       * {@linkplain Futures#addCallback(ListenableFuture, FutureCallback)
1045       * the other overload} or explicit use of
1046       * {@link MoreExecutors#sameThreadExecutor() sameThreadExecutor}. For heavier
1047       * callbacks, this choice carries some caveats: First, the thread that
1048       * the callback runs in depends on whether the input {@code Future} is
1049       * done at the time {@code addCallback} is called. In particular, if called
1050       * late, {@code addCallback} will execute the callback in the thread that
1051       * called {@code addCallback}. Second, callbacks may run in an internal
1052       * thread of the system responsible for the input {@code Future}, such as an
1053       * RPC network thread. Finally, during the execution of a {@link
1054       * MoreExecutors#sameThreadExecutor sameThreadExecutor} callback, all other
1055       * registered but unexecuted listeners are prevented from running, even if
1056       * those listeners are to run in other executors.
1057       *
1058       * <p>For a more general interface to attach a completion listener to a
1059       * {@code Future}, see {@link ListenableFuture#addListener addListener}.
1060       *
1061       * @param future The future attach the callback to.
1062       * @param callback The callback to invoke when {@code future} is completed.
1063       * @param executor The executor to run {@code callback} when the future
1064       *    completes.
1065       * @since 10.0
1066       */
1067      public static <V> void addCallback(final ListenableFuture<V> future,
1068          final FutureCallback<? super V> callback, Executor executor) {
1069        Preconditions.checkNotNull(callback);
1070        Runnable callbackListener = new Runnable() {
1071          @Override
1072          public void run() {
1073            try {
1074              // TODO(user): (Before Guava release), validate that this
1075              // is the thing for IE.
1076              V value = getUninterruptibly(future);
1077              callback.onSuccess(value);
1078            } catch (ExecutionException e) {
1079              callback.onFailure(e.getCause());
1080            } catch (RuntimeException e) {
1081              callback.onFailure(e);
1082            } catch (Error e) {
1083              callback.onFailure(e);
1084            }
1085          }
1086        };
1087        future.addListener(callbackListener, executor);
1088      }
1089    
1090      /**
1091       * Returns the result of {@link Future#get()}, converting most exceptions to a
1092       * new instance of the given checked exception type. This reduces boilerplate
1093       * for a common use of {@code Future} in which it is unnecessary to
1094       * programmatically distinguish between exception types or to extract other
1095       * information from the exception instance.
1096       *
1097       * <p>Exceptions from {@code Future.get} are treated as follows:
1098       * <ul>
1099       * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an
1100       *     {@code X} if the cause is a checked exception, an {@link
1101       *     UncheckedExecutionException} if the cause is a {@code
1102       *     RuntimeException}, or an {@link ExecutionError} if the cause is an
1103       *     {@code Error}.
1104       * <li>Any {@link InterruptedException} is wrapped in an {@code X} (after
1105       *     restoring the interrupt).
1106       * <li>Any {@link CancellationException} is propagated untouched, as is any
1107       *     other {@link RuntimeException} (though {@code get} implementations are
1108       *     discouraged from throwing such exceptions).
1109       * </ul>
1110       *
1111       * The overall principle is to continue to treat every checked exception as a
1112       * checked exception, every unchecked exception as an unchecked exception, and
1113       * every error as an error. In addition, the cause of any {@code
1114       * ExecutionException} is wrapped in order to ensure that the new stack trace
1115       * matches that of the current thread.
1116       *
1117       * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary
1118       * public constructor that accepts zero or more arguments, all of type {@code
1119       * String} or {@code Throwable} (preferring constructors with at least one
1120       * {@code String}) and calling the constructor via reflection. If the
1121       * exception did not already have a cause, one is set by calling {@link
1122       * Throwable#initCause(Throwable)} on it. If no such constructor exists, an
1123       * {@code IllegalArgumentException} is thrown.
1124       *
1125       * @throws X if {@code get} throws any checked exception except for an {@code
1126       *         ExecutionException} whose cause is not itself a checked exception
1127       * @throws UncheckedExecutionException if {@code get} throws an {@code
1128       *         ExecutionException} with a {@code RuntimeException} as its cause
1129       * @throws ExecutionError if {@code get} throws an {@code ExecutionException}
1130       *         with an {@code Error} as its cause
1131       * @throws CancellationException if {@code get} throws a {@code
1132       *         CancellationException}
1133       * @throws IllegalArgumentException if {@code exceptionClass} extends {@code
1134       *         RuntimeException} or does not have a suitable constructor
1135       * @since 10.0
1136       */
1137      @Beta
1138      public static <V, X extends Exception> V get(
1139          Future<V> future, Class<X> exceptionClass) throws X {
1140        checkNotNull(future);
1141        checkArgument(!RuntimeException.class.isAssignableFrom(exceptionClass),
1142            "Futures.get exception type (%s) must not be a RuntimeException",
1143            exceptionClass);
1144        try {
1145          return future.get();
1146        } catch (InterruptedException e) {
1147          currentThread().interrupt();
1148          throw newWithCause(exceptionClass, e);
1149        } catch (ExecutionException e) {
1150          wrapAndThrowExceptionOrError(e.getCause(), exceptionClass);
1151          throw new AssertionError();
1152        }
1153      }
1154    
1155      /**
1156       * Returns the result of {@link Future#get(long, TimeUnit)}, converting most
1157       * exceptions to a new instance of the given checked exception type. This
1158       * reduces boilerplate for a common use of {@code Future} in which it is
1159       * unnecessary to programmatically distinguish between exception types or to
1160       * extract other information from the exception instance.
1161       *
1162       * <p>Exceptions from {@code Future.get} are treated as follows:
1163       * <ul>
1164       * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an
1165       *     {@code X} if the cause is a checked exception, an {@link
1166       *     UncheckedExecutionException} if the cause is a {@code
1167       *     RuntimeException}, or an {@link ExecutionError} if the cause is an
1168       *     {@code Error}.
1169       * <li>Any {@link InterruptedException} is wrapped in an {@code X} (after
1170       *     restoring the interrupt).
1171       * <li>Any {@link TimeoutException} is wrapped in an {@code X}.
1172       * <li>Any {@link CancellationException} is propagated untouched, as is any
1173       *     other {@link RuntimeException} (though {@code get} implementations are
1174       *     discouraged from throwing such exceptions).
1175       * </ul>
1176       *
1177       * The overall principle is to continue to treat every checked exception as a
1178       * checked exception, every unchecked exception as an unchecked exception, and
1179       * every error as an error. In addition, the cause of any {@code
1180       * ExecutionException} is wrapped in order to ensure that the new stack trace
1181       * matches that of the current thread.
1182       *
1183       * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary
1184       * public constructor that accepts zero or more arguments, all of type {@code
1185       * String} or {@code Throwable} (preferring constructors with at least one
1186       * {@code String}) and calling the constructor via reflection. If the
1187       * exception did not already have a cause, one is set by calling {@link
1188       * Throwable#initCause(Throwable)} on it. If no such constructor exists, an
1189       * {@code IllegalArgumentException} is thrown.
1190       *
1191       * @throws X if {@code get} throws any checked exception except for an {@code
1192       *         ExecutionException} whose cause is not itself a checked exception
1193       * @throws UncheckedExecutionException if {@code get} throws an {@code
1194       *         ExecutionException} with a {@code RuntimeException} as its cause
1195       * @throws ExecutionError if {@code get} throws an {@code ExecutionException}
1196       *         with an {@code Error} as its cause
1197       * @throws CancellationException if {@code get} throws a {@code
1198       *         CancellationException}
1199       * @throws IllegalArgumentException if {@code exceptionClass} extends {@code
1200       *         RuntimeException} or does not have a suitable constructor
1201       * @since 10.0
1202       */
1203      @Beta
1204      public static <V, X extends Exception> V get(
1205          Future<V> future, long timeout, TimeUnit unit, Class<X> exceptionClass)
1206          throws X {
1207        checkNotNull(future);
1208        checkNotNull(unit);
1209        checkArgument(!RuntimeException.class.isAssignableFrom(exceptionClass),
1210            "Futures.get exception type (%s) must not be a RuntimeException",
1211            exceptionClass);
1212        try {
1213          return future.get(timeout, unit);
1214        } catch (InterruptedException e) {
1215          currentThread().interrupt();
1216          throw newWithCause(exceptionClass, e);
1217        } catch (TimeoutException e) {
1218          throw newWithCause(exceptionClass, e);
1219        } catch (ExecutionException e) {
1220          wrapAndThrowExceptionOrError(e.getCause(), exceptionClass);
1221          throw new AssertionError();
1222        }
1223      }
1224    
1225      private static <X extends Exception> void wrapAndThrowExceptionOrError(
1226          Throwable cause, Class<X> exceptionClass) throws X {
1227        if (cause instanceof Error) {
1228          throw new ExecutionError((Error) cause);
1229        }
1230        if (cause instanceof RuntimeException) {
1231          throw new UncheckedExecutionException((RuntimeException) cause);
1232        }
1233        throw newWithCause(exceptionClass, cause);
1234      }
1235    
1236      /**
1237       * Returns the result of calling {@link Future#get()} uninterruptibly on a
1238       * task known not to throw a checked exception. This makes {@code Future} more
1239       * suitable for lightweight, fast-running tasks that, barring bugs in the
1240       * code, will not fail.
1241       *
1242       * <p>Exceptions from {@code Future.get} are treated as follows:
1243       * <ul>
1244       * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an
1245       *     {@link UncheckedExecutionException} (if the cause is an {@code
1246       *     Exception}) or {@link ExecutionError} (if the cause is an {@code
1247       *     Error}).
1248       * <li>Any {@link InterruptedException} causes a retry of the {@code get}
1249       *     call. The interrupt is restored before {@code getUnchecked} returns.
1250       * <li>Any {@link CancellationException} is propagated untouched. So is any
1251       *     other {@link RuntimeException} ({@code get} implementations are
1252       *     discouraged from throwing such exceptions).
1253       * </ul>
1254       *
1255       * The overall principle is to eliminate all checked exceptions: to loop to
1256       * avoid {@code InterruptedException}, to pass through {@code
1257       * CancellationException}, and to wrap any exception from the underlying
1258       * computation in an {@code UncheckedExecutionException} or {@code
1259       * ExecutionError}.
1260       *
1261       * <p>For an uninterruptible {@code get} that preserves other exceptions, see
1262       * {@link Uninterruptibles#getUninterruptibly(Future)}.
1263       *
1264       * @throws UncheckedExecutionException if {@code get} throws an {@code
1265       *         ExecutionException} with an {@code Exception} as its cause
1266       * @throws ExecutionError if {@code get} throws an {@code ExecutionException}
1267       *         with an {@code Error} as its cause
1268       * @throws CancellationException if {@code get} throws a {@code
1269       *         CancellationException}
1270       * @since 10.0
1271       */
1272      @Beta
1273      public static <V> V getUnchecked(Future<V> future) {
1274        checkNotNull(future);
1275        try {
1276          return getUninterruptibly(future);
1277        } catch (ExecutionException e) {
1278          wrapAndThrowUnchecked(e.getCause());
1279          throw new AssertionError();
1280        }
1281      }
1282    
1283      private static void wrapAndThrowUnchecked(Throwable cause) {
1284        if (cause instanceof Error) {
1285          throw new ExecutionError((Error) cause);
1286        }
1287        /*
1288         * It's a non-Error, non-Exception Throwable. From my survey of such
1289         * classes, I believe that most users intended to extend Exception, so we'll
1290         * treat it like an Exception.
1291         */
1292        throw new UncheckedExecutionException(cause);
1293      }
1294    
1295      /*
1296       * TODO(user): FutureChecker interface for these to be static methods on? If
1297       * so, refer to it in the (static-method) Futures.get documentation
1298       */
1299    
1300      /*
1301       * Arguably we don't need a timed getUnchecked because any operation slow
1302       * enough to require a timeout is heavyweight enough to throw a checked
1303       * exception and therefore be inappropriate to use with getUnchecked. Further,
1304       * it's not clear that converting the checked TimeoutException to a
1305       * RuntimeException -- especially to an UncheckedExecutionException, since it
1306       * wasn't thrown by the computation -- makes sense, and if we don't convert
1307       * it, the user still has to write a try-catch block.
1308       *
1309       * If you think you would use this method, let us know.
1310       */
1311    
1312      private static <X extends Exception> X newWithCause(
1313          Class<X> exceptionClass, Throwable cause) {
1314        // getConstructors() guarantees this as long as we don't modify the array.
1315        @SuppressWarnings("unchecked")
1316        List<Constructor<X>> constructors =
1317            (List) Arrays.asList(exceptionClass.getConstructors());
1318        for (Constructor<X> constructor : preferringStrings(constructors)) {
1319          @Nullable X instance = newFromConstructor(constructor, cause);
1320          if (instance != null) {
1321            if (instance.getCause() == null) {
1322              instance.initCause(cause);
1323            }
1324            return instance;
1325          }
1326        }
1327        throw new IllegalArgumentException(
1328            "No appropriate constructor for exception of type " + exceptionClass
1329                + " in response to chained exception", cause);
1330      }
1331    
1332      private static <X extends Exception> List<Constructor<X>>
1333          preferringStrings(List<Constructor<X>> constructors) {
1334        return WITH_STRING_PARAM_FIRST.sortedCopy(constructors);
1335      }
1336    
1337      private static final Ordering<Constructor<?>> WITH_STRING_PARAM_FIRST =
1338          Ordering.natural().onResultOf(new Function<Constructor<?>, Boolean>() {
1339            @Override public Boolean apply(Constructor<?> input) {
1340              return asList(input.getParameterTypes()).contains(String.class);
1341            }
1342          }).reverse();
1343    
1344      @Nullable private static <X> X newFromConstructor(
1345          Constructor<X> constructor, Throwable cause) {
1346        Class<?>[] paramTypes = constructor.getParameterTypes();
1347        Object[] params = new Object[paramTypes.length];
1348        for (int i = 0; i < paramTypes.length; i++) {
1349          Class<?> paramType = paramTypes[i];
1350          if (paramType.equals(String.class)) {
1351            params[i] = cause.toString();
1352          } else if (paramType.equals(Throwable.class)) {
1353            params[i] = cause;
1354          } else {
1355            return null;
1356          }
1357        }
1358        try {
1359          return constructor.newInstance(params);
1360        } catch (IllegalArgumentException e) {
1361          return null;
1362        } catch (InstantiationException e) {
1363          return null;
1364        } catch (IllegalAccessException e) {
1365          return null;
1366        } catch (InvocationTargetException e) {
1367          return null;
1368        }
1369      }
1370    
1371      /**
1372       * Class that implements {@link #allAsList} and {@link #successfulAsList}.
1373       * The idea is to create a (null-filled) List and register a listener with
1374       * each component future to fill out the value in the List when that future
1375       * completes.
1376       */
1377      private static class ListFuture<V> extends AbstractFuture<List<V>> {
1378        ImmutableList<? extends ListenableFuture<? extends V>> futures;
1379        final boolean allMustSucceed;
1380        final AtomicInteger remaining;
1381        List<V> values;
1382    
1383        /**
1384         * Constructor.
1385         *
1386         * @param futures all the futures to build the list from
1387         * @param allMustSucceed whether a single failure or cancellation should
1388         *        propagate to this future
1389         * @param listenerExecutor used to run listeners on all the passed in
1390         *        futures.
1391         */
1392        ListFuture(
1393            final ImmutableList<? extends ListenableFuture<? extends V>> futures,
1394            final boolean allMustSucceed, final Executor listenerExecutor) {
1395          this.futures = futures;
1396          this.values = Lists.newArrayListWithCapacity(futures.size());
1397          this.allMustSucceed = allMustSucceed;
1398          this.remaining = new AtomicInteger(futures.size());
1399    
1400          init(listenerExecutor);
1401        }
1402    
1403        private void init(final Executor listenerExecutor) {
1404          // First, schedule cleanup to execute when the Future is done.
1405          addListener(new Runnable() {
1406            @Override
1407            public void run() {
1408              // By now the values array has either been set as the Future's value,
1409              // or (in case of failure) is no longer useful.
1410              ListFuture.this.values = null;
1411    
1412              // Let go of the memory held by other futures
1413              ListFuture.this.futures = null;
1414            }
1415          }, MoreExecutors.sameThreadExecutor());
1416    
1417          // Now begin the "real" initialization.
1418    
1419          // Corner case: List is empty.
1420          if (futures.isEmpty()) {
1421            set(Lists.newArrayList(values));
1422            return;
1423          }
1424    
1425          // Populate the results list with null initially.
1426          for (int i = 0; i < futures.size(); ++i) {
1427            values.add(null);
1428          }
1429    
1430          // Register a listener on each Future in the list to update
1431          // the state of this future.
1432          // Note that if all the futures on the list are done prior to completing
1433          // this loop, the last call to addListener() will callback to
1434          // setOneValue(), transitively call our cleanup listener, and set
1435          // this.futures to null.
1436          // We store a reference to futures to avoid the NPE.
1437          ImmutableList<? extends ListenableFuture<? extends V>> localFutures = futures;
1438          for (int i = 0; i < localFutures.size(); i++) {
1439            final ListenableFuture<? extends V> listenable = localFutures.get(i);
1440            final int index = i;
1441            listenable.addListener(new Runnable() {
1442              @Override
1443              public void run() {
1444                setOneValue(index, listenable);
1445              }
1446            }, listenerExecutor);
1447          }
1448        }
1449    
1450        /**
1451         * Sets the value at the given index to that of the given future.
1452         */
1453        private void setOneValue(int index, Future<? extends V> future) {
1454          List<V> localValues = values;
1455          if (isDone() || localValues == null) {
1456            // Some other future failed or has been cancelled, causing this one to
1457            // also be cancelled or have an exception set. This should only happen
1458            // if allMustSucceed is true.
1459            checkState(allMustSucceed,
1460                "Future was done before all dependencies completed");
1461            return;
1462          }
1463    
1464          try {
1465            checkState(future.isDone(),
1466                "Tried to set value from future which is not done");
1467            localValues.set(index, getUninterruptibly(future));
1468          } catch (CancellationException e) {
1469            if (allMustSucceed) {
1470              // Set ourselves as cancelled. Let the input futures keep running
1471              // as some of them may be used elsewhere.
1472              // (Currently we don't override interruptTask, so
1473              // mayInterruptIfRunning==false isn't technically necessary.)
1474              cancel(false);
1475            }
1476          } catch (ExecutionException e) {
1477            if (allMustSucceed) {
1478              // As soon as the first one fails, throw the exception up.
1479              // The result of all other inputs is then ignored.
1480              setException(e.getCause());
1481            }
1482          } catch (RuntimeException e) {
1483            if (allMustSucceed) {
1484              setException(e);
1485            }
1486          } catch (Error e) {
1487            // Propagate errors up ASAP - our superclass will rethrow the error
1488            setException(e);
1489          } finally {
1490            int newRemaining = remaining.decrementAndGet();
1491            checkState(newRemaining >= 0, "Less than 0 remaining futures");
1492            if (newRemaining == 0) {
1493              localValues = values;
1494              if (localValues != null) {
1495                set(Lists.newArrayList(localValues));
1496              } else {
1497                checkState(isDone());
1498              }
1499            }
1500          }
1501        }
1502    
1503        @Override
1504        public List<V> get() throws InterruptedException, ExecutionException {
1505          callAllGets();
1506    
1507          // This may still block in spite of the calls above, as the listeners may
1508          // be scheduled for execution in other threads.
1509          return super.get();
1510        }
1511    
1512        /**
1513         * Calls the get method of all dependency futures to work around a bug in
1514         * some ListenableFutures where the listeners aren't called until get() is
1515         * called.
1516         */
1517        private void callAllGets() throws InterruptedException {
1518          List<? extends ListenableFuture<? extends V>> oldFutures = futures;
1519          if (oldFutures != null && !isDone()) {
1520            for (ListenableFuture<? extends V> future : oldFutures) {
1521              // We wait for a little while for the future, but if it's not done,
1522              // we check that no other futures caused a cancellation or failure.
1523              // This can introduce a delay of up to 10ms in reporting an exception.
1524              while (!future.isDone()) {
1525                try {
1526                  future.get();
1527                } catch (Error e) {
1528                  throw e;
1529                } catch (InterruptedException e) {
1530                  throw e;
1531                } catch (Throwable e) {
1532                  // ExecutionException / CancellationException / RuntimeException
1533                  if (allMustSucceed) {
1534                    return;
1535                  } else {
1536                    continue;
1537                  }
1538                }
1539              }
1540            }
1541          }
1542        }
1543      }
1544    
1545      /**
1546       * A checked future that uses a function to map from exceptions to the
1547       * appropriate checked type.
1548       */
1549      private static class MappingCheckedFuture<V, X extends Exception> extends
1550          AbstractCheckedFuture<V, X> {
1551    
1552        final Function<Exception, X> mapper;
1553    
1554        MappingCheckedFuture(ListenableFuture<V> delegate,
1555            Function<Exception, X> mapper) {
1556          super(delegate);
1557    
1558          this.mapper = checkNotNull(mapper);
1559        }
1560    
1561        @Override
1562        protected X mapException(Exception e) {
1563          return mapper.apply(e);
1564        }
1565      }
1566    }