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