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