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