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