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.Uninterruptibles.getUninterruptibly;
023 import static com.google.common.util.concurrent.Uninterruptibles.putUninterruptibly;
024 import static com.google.common.util.concurrent.Uninterruptibles.takeUninterruptibly;
025 import static java.lang.Thread.currentThread;
026 import static java.util.Arrays.asList;
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 * <p>Many of these methods use the {@link ListenableFuture} API; consult the
057 * Guava User Guide article on <a href=
058 * "http://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained">
059 * {@code ListenableFuture}</a>.
060 *
061 * @author Kevin Bourrillion
062 * @author Nishant Thakkar
063 * @author Sven Mawson
064 * @since 1.0
065 */
066 @Beta
067 public final class Futures {
068 private Futures() {}
069
070 /**
071 * Creates a {@link CheckedFuture} out of a normal {@link ListenableFuture}
072 * and a {@link Function} that maps from {@link Exception} instances into the
073 * appropriate checked type.
074 *
075 * <p>The given mapping function will be applied to an
076 * {@link InterruptedException}, a {@link CancellationException}, or an
077 * {@link ExecutionException} with the actual cause of the exception.
078 * See {@link Future#get()} for details on the exceptions thrown.
079 *
080 * @since 9.0 (source-compatible since 1.0)
081 */
082 public static <V, X extends Exception> CheckedFuture<V, X> makeChecked(
083 ListenableFuture<V> future, Function<Exception, X> mapper) {
084 return new MappingCheckedFuture<V, X>(checkNotNull(future), mapper);
085 }
086
087 /**
088 * Creates a {@code ListenableFuture} which has its value set immediately upon
089 * construction. The getters just return the value. This {@code Future} can't
090 * be canceled or timed out and its {@code isDone()} method always returns
091 * {@code true}.
092 */
093 public static <V> ListenableFuture<V> immediateFuture(@Nullable V value) {
094 SettableFuture<V> future = SettableFuture.create();
095 future.set(value);
096 return future;
097 }
098
099 /**
100 * Returns a {@code CheckedFuture} which has its value set immediately upon
101 * construction.
102 *
103 * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()}
104 * method always returns {@code true}. Calling {@code get()} or {@code
105 * checkedGet()} will immediately return the provided value.
106 */
107 public static <V, X extends Exception> CheckedFuture<V, X>
108 immediateCheckedFuture(@Nullable V value) {
109 SettableFuture<V> future = SettableFuture.create();
110 future.set(value);
111 return Futures.makeChecked(future, new Function<Exception, X>() {
112 public X apply(Exception e) {
113 throw new AssertionError("impossible");
114 }
115 });
116 }
117
118 /**
119 * Returns a {@code ListenableFuture} which has an exception set immediately
120 * upon construction.
121 *
122 * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()}
123 * method always returns {@code true}. Calling {@code get()} will immediately
124 * throw the provided {@code Throwable} wrapped in an {@code
125 * ExecutionException}.
126 *
127 * @throws Error if the throwable is an {@link Error}.
128 */
129 public static <V> ListenableFuture<V> immediateFailedFuture(
130 Throwable throwable) {
131 checkNotNull(throwable);
132 SettableFuture<V> future = SettableFuture.create();
133 future.setException(throwable);
134 return future;
135 }
136
137 /**
138 * Returns a {@code CheckedFuture} which has an exception set immediately upon
139 * construction.
140 *
141 * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()}
142 * method always returns {@code true}. Calling {@code get()} will immediately
143 * throw the provided {@code Throwable} wrapped in an {@code
144 * ExecutionException}, and calling {@code checkedGet()} will throw the
145 * provided exception itself.
146 *
147 * @throws Error if the throwable is an {@link Error}.
148 */
149 public static <V, X extends Exception> CheckedFuture<V, X>
150 immediateFailedCheckedFuture(final X exception) {
151 checkNotNull(exception);
152 return makeChecked(Futures.<V>immediateFailedFuture(exception),
153 new Function<Exception, X>() {
154 public X apply(Exception e) {
155 return exception;
156 }
157 });
158 }
159
160 /**
161 * Returns a new {@code ListenableFuture} whose result is asynchronously
162 * derived from the result of the given {@code Future}. More precisely, the
163 * returned {@code Future} takes its result from a {@code Future} produced by
164 * applying the given {@code AsyncFunction} to the result of the original
165 * {@code Future}. Example:
166 *
167 * <pre> {@code
168 * ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
169 * AsyncFunction<RowKey, QueryResult> queryFunction =
170 * new AsyncFunction<RowKey, QueryResult>() {
171 * public ListenableFuture<QueryResult> apply(RowKey rowKey) {
172 * return dataService.read(rowKey);
173 * }
174 * };
175 * ListenableFuture<QueryResult> queryFuture =
176 * transform(rowKeyFuture, queryFunction);
177 * }</pre>
178 *
179 * Note: If the derived {@code Future} is slow or heavyweight to create
180 * (whether the {@code Future} itself is slow or heavyweight to complete is
181 * irrelevant), consider {@linkplain #transform(ListenableFuture,
182 * AsyncFunction, Executor) supplying an executor}. If you do not supply an
183 * executor, {@code transform} will use {@link
184 * MoreExecutors#sameThreadExecutor sameThreadExecutor}, which carries some
185 * caveats for heavier operations. For example, the call to {@code
186 * function.apply} may run on an unpredictable or undesirable thread:
187 *
188 * <ul>
189 * <li>If the input {@code Future} is done at the time {@code transform} is
190 * called, {@code transform} will call {@code function.apply} inline.
191 * <li>If the input {@code Future} is not yet done, {@code transform} will
192 * schedule {@code function.apply} to be run by the thread that completes the
193 * input {@code Future}, which may be an internal system thread such as an
194 * RPC network thread.
195 * </ul>
196 *
197 * Also note that, regardless of which thread executes {@code
198 * function.apply}, all other registered but unexecuted listeners are
199 * prevented from running during its execution, even if those listeners are
200 * to run in other executors.
201 *
202 * <p>The returned {@code Future} attempts to keep its cancellation state in
203 * sync with that of the input future and that of the future returned by the
204 * function. That is, if the returned {@code Future} is cancelled, it will
205 * attempt to cancel the other two, and if either of the other two is
206 * cancelled, the returned {@code Future} will receive a callback in which it
207 * will attempt to cancel itself.
208 *
209 * @param input The future to transform
210 * @param function A function to transform the result of the input future
211 * to the result of the output future
212 * @return A future that holds result of the function (if the input succeeded)
213 * or the original input's failure (if not)
214 * @since 11.0
215 */
216 public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
217 AsyncFunction<? super I, ? extends O> function) {
218 return transform(input, function, MoreExecutors.sameThreadExecutor());
219 }
220
221 /**
222 * Returns a new {@code ListenableFuture} whose result is asynchronously
223 * derived from the result of the given {@code Future}. More precisely, the
224 * returned {@code Future} takes its result from a {@code Future} produced by
225 * applying the given {@code AsyncFunction} to the result of the original
226 * {@code Future}. Example:
227 *
228 * <pre> {@code
229 * ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
230 * AsyncFunction<RowKey, QueryResult> queryFunction =
231 * new AsyncFunction<RowKey, QueryResult>() {
232 * public ListenableFuture<QueryResult> apply(RowKey rowKey) {
233 * return dataService.read(rowKey);
234 * }
235 * };
236 * ListenableFuture<QueryResult> queryFuture =
237 * transform(rowKeyFuture, queryFunction, executor);
238 * }</pre>
239 *
240 * <p>The returned {@code Future} attempts to keep its cancellation state in
241 * sync with that of the input future and that of the future returned by the
242 * chain function. That is, if the returned {@code Future} is cancelled, it
243 * will attempt to cancel the other two, and if either of the other two is
244 * cancelled, the returned {@code Future} will receive a callback in which it
245 * will attempt to cancel itself.
246 *
247 * <p>When the execution of {@code function.apply} is fast and lightweight
248 * (though the {@code Future} it returns need not meet these criteria),
249 * consider {@linkplain #transform(ListenableFuture, AsyncFunction) omitting
250 * the executor} or explicitly specifying {@code sameThreadExecutor}.
251 * However, be aware of the caveats documented in the link above.
252 *
253 * @param input The future to transform
254 * @param function A function to transform the result of the input future
255 * to the result of the output future
256 * @param executor Executor to run the function in.
257 * @return A future that holds result of the function (if the input succeeded)
258 * or the original input's failure (if not)
259 * @since 11.0
260 */
261 public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
262 AsyncFunction<? super I, ? extends O> function,
263 Executor executor) {
264 ChainingListenableFuture<I, O> output =
265 new ChainingListenableFuture<I, O>(function, input);
266 input.addListener(output, executor);
267 return output;
268 }
269
270 /**
271 * Returns a new {@code ListenableFuture} whose result is the product of
272 * applying the given {@code Function} to the result of the given {@code
273 * Future}. Example:
274 *
275 * <pre> {@code
276 * ListenableFuture<QueryResult> queryFuture = ...;
277 * Function<QueryResult, List<Row>> rowsFunction =
278 * new Function<QueryResult, List<Row>>() {
279 * public List<Row> apply(QueryResult queryResult) {
280 * return queryResult.getRows();
281 * }
282 * };
283 * ListenableFuture<List<Row>> rowsFuture =
284 * transform(queryFuture, rowsFunction);
285 * }</pre>
286 *
287 * Note: If the transformation is slow or heavyweight, consider {@linkplain
288 * #transform(ListenableFuture, Function, Executor) supplying an executor}.
289 * If you do not supply an executor, {@code transform} will use {@link
290 * MoreExecutors#sameThreadExecutor sameThreadExecutor}, which carries some
291 * caveats for heavier operations. For example, the call to {@code
292 * function.apply} may run on an unpredictable or undesirable thread:
293 *
294 * <ul>
295 * <li>If the input {@code Future} is done at the time {@code transform} is
296 * called, {@code transform} will call {@code function.apply} inline.
297 * <li>If the input {@code Future} is not yet done, {@code transform} will
298 * schedule {@code function.apply} to be run by the thread that completes the
299 * input {@code Future}, which may be an internal system thread such as an
300 * RPC network thread.
301 * </ul>
302 *
303 * Also note that, regardless of which thread executes {@code
304 * function.apply}, all other registered but unexecuted listeners are
305 * prevented from running during its execution, even if those listeners are
306 * to run in other executors.
307 *
308 * <p>The returned {@code Future} attempts to keep its cancellation state in
309 * sync with that of the input future. That is, if the returned {@code Future}
310 * is cancelled, it will attempt to cancel the input, and if the input is
311 * cancelled, the returned {@code Future} will receive a callback in which it
312 * will attempt to cancel itself.
313 *
314 * <p>An example use of this method is to convert a serializable object
315 * returned from an RPC into a POJO.
316 *
317 * @param input The future to transform
318 * @param function A Function to transform the results of the provided future
319 * to the results of the returned future. This will be run in the thread
320 * that notifies input it is complete.
321 * @return A future that holds result of the transformation.
322 * @since 9.0 (in 1.0 as {@code compose})
323 */
324 public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
325 final Function<? super I, ? extends O> function) {
326 return transform(input, function, MoreExecutors.sameThreadExecutor());
327 }
328
329 /**
330 * Returns a new {@code ListenableFuture} whose result is the product of
331 * applying the given {@code Function} to the result of the given {@code
332 * Future}. Example:
333 *
334 * <pre> {@code
335 * ListenableFuture<QueryResult> queryFuture = ...;
336 * Function<QueryResult, List<Row>> rowsFunction =
337 * new Function<QueryResult, List<Row>>() {
338 * public List<Row> apply(QueryResult queryResult) {
339 * return queryResult.getRows();
340 * }
341 * };
342 * ListenableFuture<List<Row>> rowsFuture =
343 * transform(queryFuture, rowsFunction, executor);
344 * }</pre>
345 *
346 * <p>The returned {@code Future} attempts to keep its cancellation state in
347 * sync with that of the input future. That is, if the returned {@code Future}
348 * is cancelled, it will attempt to cancel the input, and if the input is
349 * cancelled, the returned {@code Future} will receive a callback in which it
350 * will attempt to cancel itself.
351 *
352 * <p>An example use of this method is to convert a serializable object
353 * returned from an RPC into a POJO.
354 *
355 * <p>When the transformation is fast and lightweight, consider {@linkplain
356 * #transform(ListenableFuture, Function) omitting the executor} or
357 * explicitly specifying {@code sameThreadExecutor}. However, be aware of the
358 * caveats documented in the link above.
359 *
360 * @param input The future to transform
361 * @param function A Function to transform the results of the provided future
362 * to the results of the returned future.
363 * @param executor Executor to run the function in.
364 * @return A future that holds result of the transformation.
365 * @since 9.0 (in 2.0 as {@code compose})
366 */
367 public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
368 final Function<? super I, ? extends O> function, Executor executor) {
369 checkNotNull(function);
370 AsyncFunction<I, O> wrapperFunction
371 = new AsyncFunction<I, O>() {
372 public ListenableFuture<O> apply(I input) {
373 O output = function.apply(input);
374 return immediateFuture(output);
375 }
376 };
377 return transform(input, wrapperFunction, executor);
378 }
379
380 /**
381 * Like {@link #transform(ListenableFuture, Function)} except that the
382 * transformation {@code function} is invoked on each call to
383 * {@link Future#get() get()} on the returned future.
384 *
385 * <p>The returned {@code Future} reflects the input's cancellation
386 * state directly, and any attempt to cancel the returned Future is likewise
387 * passed through to the input Future.
388 *
389 * <p>Note that calls to {@linkplain Future#get(long, TimeUnit) timed get}
390 * only apply the timeout to the execution of the underlying {@code Future},
391 * <em>not</em> to the execution of the transformation function.
392 *
393 * <p>The primary audience of this method is callers of {@code transform}
394 * who don't have a {@code ListenableFuture} available and
395 * do not mind repeated, lazy function evaluation.
396 *
397 * @param input The future to transform
398 * @param function A Function to transform the results of the provided future
399 * to the results of the returned future.
400 * @return A future that returns the result of the transformation.
401 * @since 10.0
402 */
403 @Beta
404 public static <I, O> Future<O> lazyTransform(final Future<I> input,
405 final Function<? super I, ? extends O> function) {
406 checkNotNull(input);
407 checkNotNull(function);
408 return new Future<O>() {
409
410 public boolean cancel(boolean mayInterruptIfRunning) {
411 return input.cancel(mayInterruptIfRunning);
412 }
413
414 public boolean isCancelled() {
415 return input.isCancelled();
416 }
417
418 public boolean isDone() {
419 return input.isDone();
420 }
421
422 public O get() throws InterruptedException, ExecutionException {
423 return applyTransformation(input.get());
424 }
425
426 public O get(long timeout, TimeUnit unit)
427 throws InterruptedException, ExecutionException, TimeoutException {
428 return applyTransformation(input.get(timeout, unit));
429 }
430
431 private O applyTransformation(I input) throws ExecutionException {
432 try {
433 return function.apply(input);
434 } catch (Throwable t) {
435 throw new ExecutionException(t);
436 }
437 }
438 };
439 }
440
441 /**
442 * An implementation of {@code ListenableFuture} that also implements
443 * {@code Runnable} so that it can be used to nest ListenableFutures.
444 * Once the passed-in {@code ListenableFuture} is complete, it calls the
445 * passed-in {@code Function} to generate the result.
446 *
447 * <p>If the function throws any checked exceptions, they should be wrapped
448 * in a {@code UndeclaredThrowableException} so that this class can get
449 * access to the cause.
450 */
451 private static class ChainingListenableFuture<I, O>
452 extends AbstractFuture<O> implements Runnable {
453
454 private AsyncFunction<? super I, ? extends O> function;
455 private ListenableFuture<? extends I> inputFuture;
456 private volatile ListenableFuture<? extends O> outputFuture;
457 private final BlockingQueue<Boolean> mayInterruptIfRunningChannel =
458 new LinkedBlockingQueue<Boolean>(1);
459 private final CountDownLatch outputCreated = new CountDownLatch(1);
460
461 private ChainingListenableFuture(
462 AsyncFunction<? super I, ? extends O> function,
463 ListenableFuture<? extends I> inputFuture) {
464 this.function = checkNotNull(function);
465 this.inputFuture = checkNotNull(inputFuture);
466 }
467
468
469 @Override
470 public boolean cancel(boolean mayInterruptIfRunning) {
471 /*
472 * Our additional cancellation work needs to occur even if
473 * !mayInterruptIfRunning, so we can't move it into interruptTask().
474 */
475 if (super.cancel(mayInterruptIfRunning)) {
476 // This should never block since only one thread is allowed to cancel
477 // this Future.
478 putUninterruptibly(mayInterruptIfRunningChannel, mayInterruptIfRunning);
479 cancel(inputFuture, mayInterruptIfRunning);
480 cancel(outputFuture, mayInterruptIfRunning);
481 return true;
482 }
483 return false;
484 }
485
486 private void cancel(@Nullable Future<?> future,
487 boolean mayInterruptIfRunning) {
488 if (future != null) {
489 future.cancel(mayInterruptIfRunning);
490 }
491 }
492
493 public void run() {
494 try {
495 I sourceResult;
496 try {
497 sourceResult = getUninterruptibly(inputFuture);
498 } catch (CancellationException e) {
499 // Cancel this future and return.
500 // At this point, inputFuture is cancelled and outputFuture doesn't
501 // exist, so the value of mayInterruptIfRunning is irrelevant.
502 cancel(false);
503 return;
504 } catch (ExecutionException e) {
505 // Set the cause of the exception as this future's exception
506 setException(e.getCause());
507 return;
508 }
509
510 final ListenableFuture<? extends O> outputFuture = this.outputFuture =
511 function.apply(sourceResult);
512 if (isCancelled()) {
513 // Handles the case where cancel was called while the function was
514 // being applied.
515 // There is a gap in cancel(boolean) between calling sync.cancel()
516 // and storing the value of mayInterruptIfRunning, so this thread
517 // needs to block, waiting for that value.
518 outputFuture.cancel(
519 takeUninterruptibly(mayInterruptIfRunningChannel));
520 this.outputFuture = null;
521 return;
522 }
523 outputFuture.addListener(new Runnable() {
524 public void run() {
525 try {
526 // Here it would have been nice to have had an
527 // UninterruptibleListenableFuture, but we don't want to start a
528 // combinatorial explosion of interfaces, so we have to make do.
529 set(getUninterruptibly(outputFuture));
530 } catch (CancellationException e) {
531 // Cancel this future and return.
532 // At this point, inputFuture and outputFuture are done, so the
533 // value of mayInterruptIfRunning is irrelevant.
534 cancel(false);
535 return;
536 } catch (ExecutionException e) {
537 // Set the cause of the exception as this future's exception
538 setException(e.getCause());
539 } finally {
540 // Don't pin inputs beyond completion
541 ChainingListenableFuture.this.outputFuture = null;
542 }
543 }
544 }, MoreExecutors.sameThreadExecutor());
545 } catch (UndeclaredThrowableException e) {
546 // Set the cause of the exception as this future's exception
547 setException(e.getCause());
548 } catch (Exception e) {
549 // This exception is irrelevant in this thread, but useful for the
550 // client
551 setException(e);
552 } catch (Error e) {
553 // Propagate errors up ASAP - our superclass will rethrow the error
554 setException(e);
555 } finally {
556 // Don't pin inputs beyond completion
557 function = null;
558 inputFuture = null;
559 // Allow our get routines to examine outputFuture now.
560 outputCreated.countDown();
561 }
562 }
563 }
564
565 /**
566 * Returns a new {@code ListenableFuture} whose result is the product of
567 * calling {@code get()} on the {@code Future} nested within the given {@code
568 * Future}, effectively chaining the futures one after the other. Example:
569 *
570 * <pre> {@code
571 * SettableFuture<ListenableFuture<String>> nested = SettableFuture.create();
572 * ListenableFuture<String> dereferenced = dereference(nested);
573 * }</pre>
574 *
575 * <p>This call has the same cancellation and execution semantics as {@link
576 * #transform(ListenableFuture, AsyncFunction)}, in that the returned {@code
577 * Future} attempts to keep its cancellation state in sync with both the
578 * input {@code Future} and the nested {@code Future}. The transformation
579 * is very lightweight and therefore takes place in the thread that called
580 * {@code dereference}.
581 *
582 * @param nested The nested future to transform.
583 * @return A future that holds result of the inner future.
584 * @since 13.0
585 */
586 @Beta
587 @SuppressWarnings({"rawtypes", "unchecked"})
588 public static <V> ListenableFuture<V> dereference(
589 ListenableFuture<? extends ListenableFuture<? extends V>> nested) {
590 return Futures.transform((ListenableFuture) nested, (AsyncFunction) DEREFERENCER);
591 }
592
593 /**
594 * Helper {@code Function} for {@link #dereference}.
595 */
596 private static final AsyncFunction<ListenableFuture<Object>, Object> DEREFERENCER =
597 new AsyncFunction<ListenableFuture<Object>, Object>() {
598 public ListenableFuture<Object> apply(ListenableFuture<Object> input) {
599 return input;
600 }
601 };
602
603 /**
604 * Creates a new {@code ListenableFuture} whose value is a list containing the
605 * values of all its input futures, if all succeed. If any input fails, the
606 * returned future fails.
607 *
608 * <p>The list of results is in the same order as the input list.
609 *
610 * <p>Canceling this future does not cancel any of the component futures;
611 * however, if any of the provided futures fails or is canceled, this one is,
612 * too.
613 *
614 * @param futures futures to combine
615 * @return a future that provides a list of the results of the component
616 * futures
617 * @since 10.0
618 */
619 @Beta
620 public static <V> ListenableFuture<List<V>> allAsList(
621 ListenableFuture<? extends V>... futures) {
622 return new ListFuture<V>(ImmutableList.copyOf(futures), true,
623 MoreExecutors.sameThreadExecutor());
624 }
625
626 /**
627 * Creates a new {@code ListenableFuture} whose value is a list containing the
628 * values of all its input futures, if all succeed. If any input fails, the
629 * returned future fails.
630 *
631 * <p>The list of results is in the same order as the input list.
632 *
633 * <p>Canceling this future does not cancel any of the component futures;
634 * however, if any of the provided futures fails or is canceled, this one is,
635 * too.
636 *
637 * @param futures futures to combine
638 * @return a future that provides a list of the results of the component
639 * futures
640 * @since 10.0
641 */
642 @Beta
643 public static <V> ListenableFuture<List<V>> allAsList(
644 Iterable<? extends ListenableFuture<? extends V>> futures) {
645 return new ListFuture<V>(ImmutableList.copyOf(futures), true,
646 MoreExecutors.sameThreadExecutor());
647 }
648
649 /**
650 * Creates a new {@code ListenableFuture} whose value is a list containing the
651 * values of all its successful input futures. The list of results is in the
652 * same order as the input list, and if any of the provided futures fails or
653 * is canceled, its corresponding position will contain {@code null} (which is
654 * indistinguishable from the future having a successful value of
655 * {@code null}).
656 *
657 * @param futures futures to combine
658 * @return a future that provides a list of the results of the component
659 * futures
660 * @since 10.0
661 */
662 @Beta
663 public static <V> ListenableFuture<List<V>> successfulAsList(
664 ListenableFuture<? extends V>... futures) {
665 return new ListFuture<V>(ImmutableList.copyOf(futures), false,
666 MoreExecutors.sameThreadExecutor());
667 }
668
669 /**
670 * Creates a new {@code ListenableFuture} whose value is a list containing the
671 * values of all its successful input futures. The list of results is in the
672 * same order as the input list, and if any of the provided futures fails or
673 * is canceled, its corresponding position will contain {@code null} (which is
674 * indistinguishable from the future having a successful value of
675 * {@code null}).
676 *
677 * @param futures futures to combine
678 * @return a future that provides a list of the results of the component
679 * futures
680 * @since 10.0
681 */
682 @Beta
683 public static <V> ListenableFuture<List<V>> successfulAsList(
684 Iterable<? extends ListenableFuture<? extends V>> futures) {
685 return new ListFuture<V>(ImmutableList.copyOf(futures), false,
686 MoreExecutors.sameThreadExecutor());
687 }
688
689 /**
690 * Registers separate success and failure callbacks to be run when the {@code
691 * Future}'s computation is {@linkplain java.util.concurrent.Future#isDone()
692 * complete} or, if the computation is already complete, immediately.
693 *
694 * <p>There is no guaranteed ordering of execution of callbacks, but any
695 * callback added through this method is guaranteed to be called once the
696 * computation is complete.
697 *
698 * Example: <pre> {@code
699 * ListenableFuture<QueryResult> future = ...;
700 * addCallback(future,
701 * new FutureCallback<QueryResult> {
702 * public void onSuccess(QueryResult result) {
703 * storeInCache(result);
704 * }
705 * public void onFailure(Throwable t) {
706 * reportError(t);
707 * }
708 * });}</pre>
709 *
710 * Note: If the callback is slow or heavyweight, consider {@linkplain
711 * #addCallback(ListenableFuture, FutureCallback, Executor) supplying an
712 * executor}. If you do not supply an executor, {@code addCallback} will use
713 * {@link MoreExecutors#sameThreadExecutor sameThreadExecutor}, which carries
714 * some caveats for heavier operations. For example, the callback may run on
715 * an unpredictable or undesirable thread:
716 *
717 * <ul>
718 * <li>If the input {@code Future} is done at the time {@code addCallback} is
719 * called, {@code addCallback} will execute the callback inline.
720 * <li>If the input {@code Future} is not yet done, {@code addCallback} will
721 * schedule the callback to be run by the thread that completes the input
722 * {@code Future}, which may be an internal system thread such as an RPC
723 * network thread.
724 * </ul>
725 *
726 * Also note that, regardless of which thread executes the callback, all
727 * other registered but unexecuted listeners are prevented from running
728 * during its execution, even if those listeners are to run in other
729 * executors.
730 *
731 * <p>For a more general interface to attach a completion listener to a
732 * {@code Future}, see {@link ListenableFuture#addListener addListener}.
733 *
734 * @param future The future attach the callback to.
735 * @param callback The callback to invoke when {@code future} is completed.
736 * @since 10.0
737 */
738 public static <V> void addCallback(ListenableFuture<V> future,
739 FutureCallback<? super V> callback) {
740 addCallback(future, callback, MoreExecutors.sameThreadExecutor());
741 }
742
743 /**
744 * Registers separate success and failure callbacks to be run when the {@code
745 * Future}'s computation is {@linkplain java.util.concurrent.Future#isDone()
746 * complete} or, if the computation is already complete, immediately.
747 *
748 * <p>The callback is run in {@code executor}.
749 * There is no guaranteed ordering of execution of callbacks, but any
750 * callback added through this method is guaranteed to be called once the
751 * computation is complete.
752 *
753 * Example: <pre> {@code
754 * ListenableFuture<QueryResult> future = ...;
755 * Executor e = ...
756 * addCallback(future, e,
757 * new FutureCallback<QueryResult> {
758 * public void onSuccess(QueryResult result) {
759 * storeInCache(result);
760 * }
761 * public void onFailure(Throwable t) {
762 * reportError(t);
763 * }
764 * });}</pre>
765 *
766 * When the callback is fast and lightweight, consider {@linkplain
767 * #addCallback(ListenableFuture, FutureCallback) omitting the executor} or
768 * explicitly specifying {@code sameThreadExecutor}. However, be aware of the
769 * caveats documented in the link above.
770 *
771 * <p>For a more general interface to attach a completion listener to a
772 * {@code Future}, see {@link ListenableFuture#addListener addListener}.
773 *
774 * @param future The future attach the callback to.
775 * @param callback The callback to invoke when {@code future} is completed.
776 * @param executor The executor to run {@code callback} when the future
777 * completes.
778 * @since 10.0
779 */
780 public static <V> void addCallback(final ListenableFuture<V> future,
781 final FutureCallback<? super V> callback, Executor executor) {
782 Preconditions.checkNotNull(callback);
783 Runnable callbackListener = new Runnable() {
784 public void run() {
785 try {
786 // TODO(user): (Before Guava release), validate that this
787 // is the thing for IE.
788 V value = getUninterruptibly(future);
789 callback.onSuccess(value);
790 } catch (ExecutionException e) {
791 callback.onFailure(e.getCause());
792 } catch (RuntimeException e) {
793 callback.onFailure(e);
794 } catch (Error e) {
795 callback.onFailure(e);
796 }
797 }
798 };
799 future.addListener(callbackListener, executor);
800 }
801
802 /**
803 * Returns the result of {@link Future#get()}, converting most exceptions to a
804 * new instance of the given checked exception type. This reduces boilerplate
805 * for a common use of {@code Future} in which it is unnecessary to
806 * programmatically distinguish between exception types or to extract other
807 * information from the exception instance.
808 *
809 * <p>Exceptions from {@code Future.get} are treated as follows:
810 * <ul>
811 * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an
812 * {@code X} if the cause is a checked exception, an {@link
813 * UncheckedExecutionException} if the cause is a {@code
814 * RuntimeException}, or an {@link ExecutionError} if the cause is an
815 * {@code Error}.
816 * <li>Any {@link InterruptedException} is wrapped in an {@code X} (after
817 * restoring the interrupt).
818 * <li>Any {@link CancellationException} is propagated untouched, as is any
819 * other {@link RuntimeException} (though {@code get} implementations are
820 * discouraged from throwing such exceptions).
821 * </ul>
822 *
823 * The overall principle is to continue to treat every checked exception as a
824 * checked exception, every unchecked exception as an unchecked exception, and
825 * every error as an error. In addition, the cause of any {@code
826 * ExecutionException} is wrapped in order to ensure that the new stack trace
827 * matches that of the current thread.
828 *
829 * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary
830 * public constructor that accepts zero or more arguments, all of type {@code
831 * String} or {@code Throwable} (preferring constructors with at least one
832 * {@code String}) and calling the constructor via reflection. If the
833 * exception did not already have a cause, one is set by calling {@link
834 * Throwable#initCause(Throwable)} on it. If no such constructor exists, an
835 * {@code IllegalArgumentException} is thrown.
836 *
837 * @throws X if {@code get} throws any checked exception except for an {@code
838 * ExecutionException} whose cause is not itself a checked exception
839 * @throws UncheckedExecutionException if {@code get} throws an {@code
840 * ExecutionException} with a {@code RuntimeException} as its cause
841 * @throws ExecutionError if {@code get} throws an {@code ExecutionException}
842 * with an {@code Error} as its cause
843 * @throws CancellationException if {@code get} throws a {@code
844 * CancellationException}
845 * @throws IllegalArgumentException if {@code exceptionClass} extends {@code
846 * RuntimeException} or does not have a suitable constructor
847 * @since 10.0
848 */
849 @Beta
850 public static <V, X extends Exception> V get(
851 Future<V> future, Class<X> exceptionClass) throws X {
852 checkNotNull(future);
853 checkArgument(!RuntimeException.class.isAssignableFrom(exceptionClass),
854 "Futures.get exception type (%s) must not be a RuntimeException",
855 exceptionClass);
856 try {
857 return future.get();
858 } catch (InterruptedException e) {
859 currentThread().interrupt();
860 throw newWithCause(exceptionClass, e);
861 } catch (ExecutionException e) {
862 wrapAndThrowExceptionOrError(e.getCause(), exceptionClass);
863 throw new AssertionError();
864 }
865 }
866
867 /**
868 * Returns the result of {@link Future#get(long, TimeUnit)}, converting most
869 * exceptions to a new instance of the given checked exception type. This
870 * reduces boilerplate for a common use of {@code Future} in which it is
871 * unnecessary to programmatically distinguish between exception types or to
872 * extract other information from the exception instance.
873 *
874 * <p>Exceptions from {@code Future.get} are treated as follows:
875 * <ul>
876 * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an
877 * {@code X} if the cause is a checked exception, an {@link
878 * UncheckedExecutionException} if the cause is a {@code
879 * RuntimeException}, or an {@link ExecutionError} if the cause is an
880 * {@code Error}.
881 * <li>Any {@link InterruptedException} is wrapped in an {@code X} (after
882 * restoring the interrupt).
883 * <li>Any {@link TimeoutException} is wrapped in an {@code X}.
884 * <li>Any {@link CancellationException} is propagated untouched, as is any
885 * other {@link RuntimeException} (though {@code get} implementations are
886 * discouraged from throwing such exceptions).
887 * </ul>
888 *
889 * The overall principle is to continue to treat every checked exception as a
890 * checked exception, every unchecked exception as an unchecked exception, and
891 * every error as an error. In addition, the cause of any {@code
892 * ExecutionException} is wrapped in order to ensure that the new stack trace
893 * matches that of the current thread.
894 *
895 * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary
896 * public constructor that accepts zero or more arguments, all of type {@code
897 * String} or {@code Throwable} (preferring constructors with at least one
898 * {@code String}) and calling the constructor via reflection. If the
899 * exception did not already have a cause, one is set by calling {@link
900 * Throwable#initCause(Throwable)} on it. If no such constructor exists, an
901 * {@code IllegalArgumentException} is thrown.
902 *
903 * @throws X if {@code get} throws any checked exception except for an {@code
904 * ExecutionException} whose cause is not itself a checked exception
905 * @throws UncheckedExecutionException if {@code get} throws an {@code
906 * ExecutionException} with a {@code RuntimeException} as its cause
907 * @throws ExecutionError if {@code get} throws an {@code ExecutionException}
908 * with an {@code Error} as its cause
909 * @throws CancellationException if {@code get} throws a {@code
910 * CancellationException}
911 * @throws IllegalArgumentException if {@code exceptionClass} extends {@code
912 * RuntimeException} or does not have a suitable constructor
913 * @since 10.0
914 */
915 @Beta
916 public static <V, X extends Exception> V get(
917 Future<V> future, long timeout, TimeUnit unit, Class<X> exceptionClass)
918 throws X {
919 checkNotNull(future);
920 checkNotNull(unit);
921 checkArgument(!RuntimeException.class.isAssignableFrom(exceptionClass),
922 "Futures.get exception type (%s) must not be a RuntimeException",
923 exceptionClass);
924 try {
925 return future.get(timeout, unit);
926 } catch (InterruptedException e) {
927 currentThread().interrupt();
928 throw newWithCause(exceptionClass, e);
929 } catch (TimeoutException e) {
930 throw newWithCause(exceptionClass, e);
931 } catch (ExecutionException e) {
932 wrapAndThrowExceptionOrError(e.getCause(), exceptionClass);
933 throw new AssertionError();
934 }
935 }
936
937 private static <X extends Exception> void wrapAndThrowExceptionOrError(
938 Throwable cause, Class<X> exceptionClass) throws X {
939 if (cause instanceof Error) {
940 throw new ExecutionError((Error) cause);
941 }
942 if (cause instanceof RuntimeException) {
943 throw new UncheckedExecutionException(cause);
944 }
945 throw newWithCause(exceptionClass, cause);
946 }
947
948 /**
949 * Returns the result of calling {@link Future#get()} uninterruptibly on a
950 * task known not to throw a checked exception. This makes {@code Future} more
951 * suitable for lightweight, fast-running tasks that, barring bugs in the
952 * code, will not fail. This gives it exception-handling behavior similar to
953 * that of {@code ForkJoinTask.join}.
954 *
955 * <p>Exceptions from {@code Future.get} are treated as follows:
956 * <ul>
957 * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an
958 * {@link UncheckedExecutionException} (if the cause is an {@code
959 * Exception}) or {@link ExecutionError} (if the cause is an {@code
960 * Error}).
961 * <li>Any {@link InterruptedException} causes a retry of the {@code get}
962 * call. The interrupt is restored before {@code getUnchecked} returns.
963 * <li>Any {@link CancellationException} is propagated untouched. So is any
964 * other {@link RuntimeException} ({@code get} implementations are
965 * discouraged from throwing such exceptions).
966 * </ul>
967 *
968 * The overall principle is to eliminate all checked exceptions: to loop to
969 * avoid {@code InterruptedException}, to pass through {@code
970 * CancellationException}, and to wrap any exception from the underlying
971 * computation in an {@code UncheckedExecutionException} or {@code
972 * ExecutionError}.
973 *
974 * <p>For an uninterruptible {@code get} that preserves other exceptions, see
975 * {@link Uninterruptibles#getUninterruptibly(Future)}.
976 *
977 * @throws UncheckedExecutionException if {@code get} throws an {@code
978 * ExecutionException} with an {@code Exception} as its cause
979 * @throws ExecutionError if {@code get} throws an {@code ExecutionException}
980 * with an {@code Error} as its cause
981 * @throws CancellationException if {@code get} throws a {@code
982 * CancellationException}
983 * @since 10.0
984 */
985 @Beta
986 public static <V> V getUnchecked(Future<V> future) {
987 checkNotNull(future);
988 try {
989 return getUninterruptibly(future);
990 } catch (ExecutionException e) {
991 wrapAndThrowUnchecked(e.getCause());
992 throw new AssertionError();
993 }
994 }
995
996 private static void wrapAndThrowUnchecked(Throwable cause) {
997 if (cause instanceof Error) {
998 throw new ExecutionError((Error) cause);
999 }
1000 /*
1001 * It's a non-Error, non-Exception Throwable. From my survey of such
1002 * classes, I believe that most users intended to extend Exception, so we'll
1003 * treat it like an Exception.
1004 */
1005 throw new UncheckedExecutionException(cause);
1006 }
1007
1008 /*
1009 * TODO(user): FutureChecker interface for these to be static methods on? If
1010 * so, refer to it in the (static-method) Futures.get documentation
1011 */
1012
1013 /*
1014 * Arguably we don't need a timed getUnchecked because any operation slow
1015 * enough to require a timeout is heavyweight enough to throw a checked
1016 * exception and therefore be inappropriate to use with getUnchecked. Further,
1017 * it's not clear that converting the checked TimeoutException to a
1018 * RuntimeException -- especially to an UncheckedExecutionException, since it
1019 * wasn't thrown by the computation -- makes sense, and if we don't convert
1020 * it, the user still has to write a try-catch block.
1021 *
1022 * If you think you would use this method, let us know.
1023 */
1024
1025 private static <X extends Exception> X newWithCause(
1026 Class<X> exceptionClass, Throwable cause) {
1027 // getConstructors() guarantees this as long as we don't modify the array.
1028 @SuppressWarnings("unchecked")
1029 List<Constructor<X>> constructors =
1030 (List) Arrays.asList(exceptionClass.getConstructors());
1031 for (Constructor<X> constructor : preferringStrings(constructors)) {
1032 @Nullable X instance = newFromConstructor(constructor, cause);
1033 if (instance != null) {
1034 if (instance.getCause() == null) {
1035 instance.initCause(cause);
1036 }
1037 return instance;
1038 }
1039 }
1040 throw new IllegalArgumentException(
1041 "No appropriate constructor for exception of type " + exceptionClass
1042 + " in response to chained exception", cause);
1043 }
1044
1045 private static <X extends Exception> List<Constructor<X>>
1046 preferringStrings(List<Constructor<X>> constructors) {
1047 return WITH_STRING_PARAM_FIRST.sortedCopy(constructors);
1048 }
1049
1050 private static final Ordering<Constructor<?>> WITH_STRING_PARAM_FIRST =
1051 Ordering.natural().onResultOf(new Function<Constructor<?>, Boolean>() {
1052 public Boolean apply(Constructor<?> input) {
1053 return asList(input.getParameterTypes()).contains(String.class);
1054 }
1055 }).reverse();
1056
1057 @Nullable private static <X> X newFromConstructor(
1058 Constructor<X> constructor, Throwable cause) {
1059 Class<?>[] paramTypes = constructor.getParameterTypes();
1060 Object[] params = new Object[paramTypes.length];
1061 for (int i = 0; i < paramTypes.length; i++) {
1062 Class<?> paramType = paramTypes[i];
1063 if (paramType.equals(String.class)) {
1064 params[i] = cause.toString();
1065 } else if (paramType.equals(Throwable.class)) {
1066 params[i] = cause;
1067 } else {
1068 return null;
1069 }
1070 }
1071 try {
1072 return constructor.newInstance(params);
1073 } catch (IllegalArgumentException e) {
1074 return null;
1075 } catch (InstantiationException e) {
1076 return null;
1077 } catch (IllegalAccessException e) {
1078 return null;
1079 } catch (InvocationTargetException e) {
1080 return null;
1081 }
1082 }
1083
1084 /**
1085 * Class that implements {@link #allAsList} and {@link #successfulAsList}.
1086 * The idea is to create a (null-filled) List and register a listener with
1087 * each component future to fill out the value in the List when that future
1088 * completes.
1089 */
1090 private static class ListFuture<V> extends AbstractFuture<List<V>> {
1091 ImmutableList<? extends ListenableFuture<? extends V>> futures;
1092 final boolean allMustSucceed;
1093 final AtomicInteger remaining;
1094 List<V> values;
1095
1096 /**
1097 * Constructor.
1098 *
1099 * @param futures all the futures to build the list from
1100 * @param allMustSucceed whether a single failure or cancellation should
1101 * propagate to this future
1102 * @param listenerExecutor used to run listeners on all the passed in
1103 * futures.
1104 */
1105 ListFuture(
1106 final ImmutableList<? extends ListenableFuture<? extends V>> futures,
1107 final boolean allMustSucceed, final Executor listenerExecutor) {
1108 this.futures = futures;
1109 this.values = Lists.newArrayListWithCapacity(futures.size());
1110 this.allMustSucceed = allMustSucceed;
1111 this.remaining = new AtomicInteger(futures.size());
1112
1113 init(listenerExecutor);
1114 }
1115
1116 private void init(final Executor listenerExecutor) {
1117 // First, schedule cleanup to execute when the Future is done.
1118 addListener(new Runnable() {
1119 public void run() {
1120 // By now the values array has either been set as the Future's value,
1121 // or (in case of failure) is no longer useful.
1122 ListFuture.this.values = null;
1123
1124 // Let go of the memory held by other futures
1125 ListFuture.this.futures = null;
1126 }
1127 }, MoreExecutors.sameThreadExecutor());
1128
1129 // Now begin the "real" initialization.
1130
1131 // Corner case: List is empty.
1132 if (futures.isEmpty()) {
1133 set(Lists.newArrayList(values));
1134 return;
1135 }
1136
1137 // Populate the results list with null initially.
1138 for (int i = 0; i < futures.size(); ++i) {
1139 values.add(null);
1140 }
1141
1142 // Register a listener on each Future in the list to update
1143 // the state of this future.
1144 // Note that if all the futures on the list are done prior to completing
1145 // this loop, the last call to addListener() will callback to
1146 // setOneValue(), transitively call our cleanup listener, and set
1147 // this.futures to null.
1148 // We store a reference to futures to avoid the NPE.
1149 ImmutableList<? extends ListenableFuture<? extends V>> localFutures = futures;
1150 for (int i = 0; i < localFutures.size(); i++) {
1151 final ListenableFuture<? extends V> listenable = localFutures.get(i);
1152 final int index = i;
1153 listenable.addListener(new Runnable() {
1154 public void run() {
1155 setOneValue(index, listenable);
1156 }
1157 }, listenerExecutor);
1158 }
1159 }
1160
1161 /**
1162 * Sets the value at the given index to that of the given future.
1163 */
1164 private void setOneValue(int index, Future<? extends V> future) {
1165 List<V> localValues = values;
1166 if (isDone() || localValues == null) {
1167 // Some other future failed or has been cancelled, causing this one to
1168 // also be cancelled or have an exception set. This should only happen
1169 // if allMustSucceed is true.
1170 checkState(allMustSucceed,
1171 "Future was done before all dependencies completed");
1172 return;
1173 }
1174
1175 try {
1176 checkState(future.isDone(),
1177 "Tried to set value from future which is not done");
1178 localValues.set(index, getUninterruptibly(future));
1179 } catch (CancellationException e) {
1180 if (allMustSucceed) {
1181 // Set ourselves as cancelled. Let the input futures keep running
1182 // as some of them may be used elsewhere.
1183 // (Currently we don't override interruptTask, so
1184 // mayInterruptIfRunning==false isn't technically necessary.)
1185 cancel(false);
1186 }
1187 } catch (ExecutionException e) {
1188 if (allMustSucceed) {
1189 // As soon as the first one fails, throw the exception up.
1190 // The result of all other inputs is then ignored.
1191 setException(e.getCause());
1192 }
1193 } catch (RuntimeException e) {
1194 if (allMustSucceed) {
1195 setException(e);
1196 }
1197 } catch (Error e) {
1198 // Propagate errors up ASAP - our superclass will rethrow the error
1199 setException(e);
1200 } finally {
1201 int newRemaining = remaining.decrementAndGet();
1202 checkState(newRemaining >= 0, "Less than 0 remaining futures");
1203 if (newRemaining == 0) {
1204 localValues = values;
1205 if (localValues != null) {
1206 set(Lists.newArrayList(localValues));
1207 } else {
1208 checkState(isDone());
1209 }
1210 }
1211 }
1212 }
1213
1214 }
1215
1216 /**
1217 * A checked future that uses a function to map from exceptions to the
1218 * appropriate checked type.
1219 */
1220 private static class MappingCheckedFuture<V, X extends Exception> extends
1221 AbstractCheckedFuture<V, X> {
1222
1223 final Function<Exception, X> mapper;
1224
1225 MappingCheckedFuture(ListenableFuture<V> delegate,
1226 Function<Exception, X> mapper) {
1227 super(delegate);
1228
1229 this.mapper = checkNotNull(mapper);
1230 }
1231
1232
1233 @Override
1234 protected X mapException(Exception e) {
1235 return mapper.apply(e);
1236 }
1237 }
1238 }