001/* 002 * Copyright (C) 2006 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.util.concurrent; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018import static com.google.common.base.Preconditions.checkState; 019import static com.google.common.util.concurrent.MoreExecutors.directExecutor; 020import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly; 021 022import com.google.common.annotations.Beta; 023import com.google.common.annotations.GwtCompatible; 024import com.google.common.annotations.GwtIncompatible; 025import com.google.common.base.Function; 026import com.google.common.base.MoreObjects; 027import com.google.common.base.Preconditions; 028import com.google.common.collect.ImmutableList; 029import com.google.common.util.concurrent.CollectionFuture.ListFuture; 030import com.google.common.util.concurrent.ImmediateFuture.ImmediateCancelledFuture; 031import com.google.common.util.concurrent.ImmediateFuture.ImmediateFailedFuture; 032import com.google.common.util.concurrent.ImmediateFuture.ImmediateSuccessfulFuture; 033import com.google.errorprone.annotations.CanIgnoreReturnValue; 034import java.util.Collection; 035import java.util.List; 036import java.util.concurrent.Callable; 037import java.util.concurrent.CancellationException; 038import java.util.concurrent.ExecutionException; 039import java.util.concurrent.Executor; 040import java.util.concurrent.Future; 041import java.util.concurrent.ScheduledExecutorService; 042import java.util.concurrent.TimeUnit; 043import java.util.concurrent.TimeoutException; 044import java.util.concurrent.atomic.AtomicInteger; 045import org.checkerframework.checker.nullness.compatqual.NullableDecl; 046 047/** 048 * Static utility methods pertaining to the {@link Future} interface. 049 * 050 * <p>Many of these methods use the {@link ListenableFuture} API; consult the Guava User Guide 051 * article on <a href="https://github.com/google/guava/wiki/ListenableFutureExplained">{@code 052 * ListenableFuture}</a>. 053 * 054 * <p>The main purpose of {@code ListenableFuture} is to help you chain together a graph of 055 * asynchronous operations. You can chain them together manually with calls to methods like {@link 056 * Futures#transform(ListenableFuture, Function, Executor) Futures.transform}, but you will often 057 * find it easier to use a framework. Frameworks automate the process, often adding features like 058 * monitoring, debugging, and cancellation. Examples of frameworks include: 059 * 060 * <ul> 061 * <li><a href="http://dagger.dev/producers.html">Dagger Producers</a> 062 * </ul> 063 * 064 * <p>If you do chain your operations manually, you may want to use {@link FluentFuture}. 065 * 066 * @author Kevin Bourrillion 067 * @author Nishant Thakkar 068 * @author Sven Mawson 069 * @since 1.0 070 */ 071@GwtCompatible(emulated = true) 072public final class Futures extends GwtFuturesCatchingSpecialization { 073 074 // A note on memory visibility. 075 // Many of the utilities in this class (transform, withFallback, withTimeout, asList, combine) 076 // have two requirements that significantly complicate their design. 077 // 1. Cancellation should propagate from the returned future to the input future(s). 078 // 2. The returned futures shouldn't unnecessarily 'pin' their inputs after completion. 079 // 080 // A consequence of these requirements is that the delegate futures cannot be stored in 081 // final fields. 082 // 083 // For simplicity the rest of this description will discuss Futures.catching since it is the 084 // simplest instance, though very similar descriptions apply to many other classes in this file. 085 // 086 // In the constructor of AbstractCatchingFuture, the delegate future is assigned to a field 087 // 'inputFuture'. That field is non-final and non-volatile. There are 2 places where the 088 // 'inputFuture' field is read and where we will have to consider visibility of the write 089 // operation in the constructor. 090 // 091 // 1. In the listener that performs the callback. In this case it is fine since inputFuture is 092 // assigned prior to calling addListener, and addListener happens-before any invocation of the 093 // listener. Notably, this means that 'volatile' is unnecessary to make 'inputFuture' visible 094 // to the listener. 095 // 096 // 2. In done() where we may propagate cancellation to the input. In this case it is _not_ fine. 097 // There is currently nothing that enforces that the write to inputFuture in the constructor is 098 // visible to done(). This is because there is no happens before edge between the write and a 099 // (hypothetical) unsafe read by our caller. Note: adding 'volatile' does not fix this issue, 100 // it would just add an edge such that if done() observed non-null, then it would also 101 // definitely observe all earlier writes, but we still have no guarantee that done() would see 102 // the inital write (just stronger guarantees if it does). 103 // 104 // See: http://cs.oswego.edu/pipermail/concurrency-interest/2015-January/013800.html 105 // For a (long) discussion about this specific issue and the general futility of life. 106 // 107 // For the time being we are OK with the problem discussed above since it requires a caller to 108 // introduce a very specific kind of data-race. And given the other operations performed by these 109 // methods that involve volatile read/write operations, in practice there is no issue. Also, the 110 // way in such a visibility issue would surface is most likely as a failure of cancel() to 111 // propagate to the input. Cancellation propagation is fundamentally racy so this is fine. 112 // 113 // Future versions of the JMM may revise safe construction semantics in such a way that we can 114 // safely publish these objects and we won't need this whole discussion. 115 // TODO(user,lukes): consider adding volatile to all these fields since in current known JVMs 116 // that should resolve the issue. This comes at the cost of adding more write barriers to the 117 // implementations. 118 119 private Futures() {} 120 121 /** 122 * Creates a {@code ListenableFuture} which has its value set immediately upon construction. The 123 * getters just return the value. This {@code Future} can't be canceled or timed out and its 124 * {@code isDone()} method always returns {@code true}. 125 */ 126 public static <V> ListenableFuture<V> immediateFuture(@NullableDecl V value) { 127 if (value == null) { 128 // This cast is safe because null is assignable to V for all V (i.e. it is covariant) 129 @SuppressWarnings({"unchecked", "rawtypes"}) 130 ListenableFuture<V> typedNull = (ListenableFuture) ImmediateSuccessfulFuture.NULL; 131 return typedNull; 132 } 133 return new ImmediateSuccessfulFuture<V>(value); 134 } 135 136 /** 137 * Returns a {@code ListenableFuture} which has an exception set immediately upon construction. 138 * 139 * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()} method always 140 * returns {@code true}. Calling {@code get()} will immediately throw the provided {@code 141 * Throwable} wrapped in an {@code ExecutionException}. 142 */ 143 public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable) { 144 checkNotNull(throwable); 145 return new ImmediateFailedFuture<V>(throwable); 146 } 147 148 /** 149 * Creates a {@code ListenableFuture} which is cancelled immediately upon construction, so that 150 * {@code isCancelled()} always returns {@code true}. 151 * 152 * @since 14.0 153 */ 154 public static <V> ListenableFuture<V> immediateCancelledFuture() { 155 return new ImmediateCancelledFuture<V>(); 156 } 157 158 /** 159 * Executes {@code callable} on the specified {@code executor}, returning a {@code Future}. 160 * 161 * @throws RejectedExecutionException if the task cannot be scheduled for execution 162 * @since 23.0 163 */ 164 @Beta 165 public static <O> ListenableFuture<O> submitAsync(AsyncCallable<O> callable, Executor executor) { 166 TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable); 167 executor.execute(task); 168 return task; 169 } 170 171 /** 172 * Schedules {@code callable} on the specified {@code executor}, returning a {@code Future}. 173 * 174 * @throws RejectedExecutionException if the task cannot be scheduled for execution 175 * @since 23.0 176 */ 177 @Beta 178 @GwtIncompatible // java.util.concurrent.ScheduledExecutorService 179 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 180 public static <O> ListenableFuture<O> scheduleAsync( 181 AsyncCallable<O> callable, 182 long delay, 183 TimeUnit timeUnit, 184 ScheduledExecutorService executorService) { 185 TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable); 186 final Future<?> scheduled = executorService.schedule(task, delay, timeUnit); 187 task.addListener( 188 new Runnable() { 189 @Override 190 public void run() { 191 // Don't want to interrupt twice 192 scheduled.cancel(false); 193 } 194 }, 195 directExecutor()); 196 return task; 197 } 198 199 /** 200 * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the 201 * primary input fails with the given {@code exceptionType}, from the result provided by the 202 * {@code fallback}. {@link Function#apply} is not invoked until the primary input has failed, so 203 * if the primary input succeeds, it is never invoked. If, during the invocation of {@code 204 * fallback}, an exception is thrown, this exception is used as the result of the output {@code 205 * Future}. 206 * 207 * <p>Usage example: 208 * 209 * <pre>{@code 210 * ListenableFuture<Integer> fetchCounterFuture = ...; 211 * 212 * // Falling back to a zero counter in case an exception happens when 213 * // processing the RPC to fetch counters. 214 * ListenableFuture<Integer> faultTolerantFuture = Futures.catching( 215 * fetchCounterFuture, FetchException.class, x -> 0, directExecutor()); 216 * }</pre> 217 * 218 * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See 219 * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener} 220 * documentation. All its warnings about heavyweight listeners are also applicable to heavyweight 221 * functions passed to this method. 222 * 223 * @param input the primary input {@code Future} 224 * @param exceptionType the exception type that triggers use of {@code fallback}. The exception 225 * type is matched against the input's exception. "The input's exception" means the cause of 226 * the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a 227 * different kind of exception, that exception itself. To avoid hiding bugs and other 228 * unrecoverable errors, callers should prefer more specific types, avoiding {@code 229 * Throwable.class} in particular. 230 * @param fallback the {@link Function} to be called if {@code input} fails with the expected 231 * exception type. The function's argument is the input's exception. "The input's exception" 232 * means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if 233 * {@code get()} throws a different kind of exception, that exception itself. 234 * @param executor the executor that runs {@code fallback} if {@code input} fails 235 * @since 19.0 236 */ 237 @Beta 238 @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class") 239 public static <V, X extends Throwable> ListenableFuture<V> catching( 240 ListenableFuture<? extends V> input, 241 Class<X> exceptionType, 242 Function<? super X, ? extends V> fallback, 243 Executor executor) { 244 return AbstractCatchingFuture.create(input, exceptionType, fallback, executor); 245 } 246 247 /** 248 * Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the 249 * primary input fails with the given {@code exceptionType}, from the result provided by the 250 * {@code fallback}. {@link AsyncFunction#apply} is not invoked until the primary input has 251 * failed, so if the primary input succeeds, it is never invoked. If, during the invocation of 252 * {@code fallback}, an exception is thrown, this exception is used as the result of the output 253 * {@code Future}. 254 * 255 * <p>Usage examples: 256 * 257 * <pre>{@code 258 * ListenableFuture<Integer> fetchCounterFuture = ...; 259 * 260 * // Falling back to a zero counter in case an exception happens when 261 * // processing the RPC to fetch counters. 262 * ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync( 263 * fetchCounterFuture, FetchException.class, x -> immediateFuture(0), directExecutor()); 264 * }</pre> 265 * 266 * <p>The fallback can also choose to propagate the original exception when desired: 267 * 268 * <pre>{@code 269 * ListenableFuture<Integer> fetchCounterFuture = ...; 270 * 271 * // Falling back to a zero counter only in case the exception was a 272 * // TimeoutException. 273 * ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync( 274 * fetchCounterFuture, 275 * FetchException.class, 276 * e -> { 277 * if (omitDataOnFetchFailure) { 278 * return immediateFuture(0); 279 * } 280 * throw e; 281 * }, 282 * directExecutor()); 283 * }</pre> 284 * 285 * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See 286 * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener} 287 * documentation. All its warnings about heavyweight listeners are also applicable to heavyweight 288 * functions passed to this method. (Specifically, {@code directExecutor} functions should avoid 289 * heavyweight operations inside {@code AsyncFunction.apply}. Any heavyweight operations should 290 * occur in other threads responsible for completing the returned {@code Future}.) 291 * 292 * @param input the primary input {@code Future} 293 * @param exceptionType the exception type that triggers use of {@code fallback}. The exception 294 * type is matched against the input's exception. "The input's exception" means the cause of 295 * the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a 296 * different kind of exception, that exception itself. To avoid hiding bugs and other 297 * unrecoverable errors, callers should prefer more specific types, avoiding {@code 298 * Throwable.class} in particular. 299 * @param fallback the {@link AsyncFunction} to be called if {@code input} fails with the expected 300 * exception type. The function's argument is the input's exception. "The input's exception" 301 * means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if 302 * {@code get()} throws a different kind of exception, that exception itself. 303 * @param executor the executor that runs {@code fallback} if {@code input} fails 304 * @since 19.0 (similar functionality in 14.0 as {@code withFallback}) 305 */ 306 @Beta 307 @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class") 308 public static <V, X extends Throwable> ListenableFuture<V> catchingAsync( 309 ListenableFuture<? extends V> input, 310 Class<X> exceptionType, 311 AsyncFunction<? super X, ? extends V> fallback, 312 Executor executor) { 313 return AbstractCatchingFuture.create(input, exceptionType, fallback, executor); 314 } 315 316 /** 317 * Returns a future that delegates to another but will finish early (via a {@link 318 * TimeoutException} wrapped in an {@link ExecutionException}) if the specified duration expires. 319 * 320 * <p>The delegate future is interrupted and cancelled if it times out. 321 * 322 * @param delegate The future to delegate to. 323 * @param time when to timeout the future 324 * @param unit the time unit of the time parameter 325 * @param scheduledExecutor The executor service to enforce the timeout. 326 * @since 19.0 327 */ 328 @Beta 329 @GwtIncompatible // java.util.concurrent.ScheduledExecutorService 330 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 331 public static <V> ListenableFuture<V> withTimeout( 332 ListenableFuture<V> delegate, 333 long time, 334 TimeUnit unit, 335 ScheduledExecutorService scheduledExecutor) { 336 if (delegate.isDone()) { 337 return delegate; 338 } 339 return TimeoutFuture.create(delegate, time, unit, scheduledExecutor); 340 } 341 342 /** 343 * Returns a new {@code Future} whose result is asynchronously derived from the result of the 344 * given {@code Future}. If the given {@code Future} fails, the returned {@code Future} fails with 345 * the same exception (and the function is not invoked). 346 * 347 * <p>More precisely, the returned {@code Future} takes its result from a {@code Future} produced 348 * by applying the given {@code AsyncFunction} to the result of the original {@code Future}. 349 * Example usage: 350 * 351 * <pre>{@code 352 * ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query); 353 * ListenableFuture<QueryResult> queryFuture = 354 * transformAsync(rowKeyFuture, dataService::readFuture, executor); 355 * }</pre> 356 * 357 * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See 358 * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener} 359 * documentation. All its warnings about heavyweight listeners are also applicable to heavyweight 360 * functions passed to this method. (Specifically, {@code directExecutor} functions should avoid 361 * heavyweight operations inside {@code AsyncFunction.apply}. Any heavyweight operations should 362 * occur in other threads responsible for completing the returned {@code Future}.) 363 * 364 * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the 365 * input future and that of the future returned by the chain function. That is, if the returned 366 * {@code Future} is cancelled, it will attempt to cancel the other two, and if either of the 367 * other two is cancelled, the returned {@code Future} will receive a callback in which it will 368 * attempt to cancel itself. 369 * 370 * @param input The future to transform 371 * @param function A function to transform the result of the input future to the result of the 372 * output future 373 * @param executor Executor to run the function in. 374 * @return A future that holds result of the function (if the input succeeded) or the original 375 * input's failure (if not) 376 * @since 19.0 (in 11.0 as {@code transform}) 377 */ 378 @Beta 379 public static <I, O> ListenableFuture<O> transformAsync( 380 ListenableFuture<I> input, 381 AsyncFunction<? super I, ? extends O> function, 382 Executor executor) { 383 return AbstractTransformFuture.create(input, function, executor); 384 } 385 386 /** 387 * Returns a new {@code Future} whose result is derived from the result of the given {@code 388 * Future}. If {@code input} fails, the returned {@code Future} fails with the same exception (and 389 * the function is not invoked). Example usage: 390 * 391 * <pre>{@code 392 * ListenableFuture<QueryResult> queryFuture = ...; 393 * ListenableFuture<List<Row>> rowsFuture = 394 * transform(queryFuture, QueryResult::getRows, executor); 395 * }</pre> 396 * 397 * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See 398 * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener} 399 * documentation. All its warnings about heavyweight listeners are also applicable to heavyweight 400 * functions passed to this method. 401 * 402 * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the 403 * input future. That is, if the returned {@code Future} is cancelled, it will attempt to cancel 404 * the input, and if the input is cancelled, the returned {@code Future} will receive a callback 405 * in which it will attempt to cancel itself. 406 * 407 * <p>An example use of this method is to convert a serializable object returned from an RPC into 408 * a POJO. 409 * 410 * @param input The future to transform 411 * @param function A Function to transform the results of the provided future to the results of 412 * the returned future. 413 * @param executor Executor to run the function in. 414 * @return A future that holds result of the transformation. 415 * @since 9.0 (in 2.0 as {@code compose}) 416 */ 417 @Beta 418 public static <I, O> ListenableFuture<O> transform( 419 ListenableFuture<I> input, Function<? super I, ? extends O> function, Executor executor) { 420 return AbstractTransformFuture.create(input, function, executor); 421 } 422 423 /** 424 * Like {@link #transform(ListenableFuture, Function, Executor)} except that the transformation 425 * {@code function} is invoked on each call to {@link Future#get() get()} on the returned future. 426 * 427 * <p>The returned {@code Future} reflects the input's cancellation state directly, and any 428 * attempt to cancel the returned Future is likewise passed through to the input Future. 429 * 430 * <p>Note that calls to {@linkplain Future#get(long, TimeUnit) timed get} only apply the timeout 431 * to the execution of the underlying {@code Future}, <em>not</em> to the execution of the 432 * transformation function. 433 * 434 * <p>The primary audience of this method is callers of {@code transform} who don't have a {@code 435 * ListenableFuture} available and do not mind repeated, lazy function evaluation. 436 * 437 * @param input The future to transform 438 * @param function A Function to transform the results of the provided future to the results of 439 * the returned future. 440 * @return A future that returns the result of the transformation. 441 * @since 10.0 442 */ 443 @Beta 444 @GwtIncompatible // TODO 445 public static <I, O> Future<O> lazyTransform( 446 final Future<I> input, final Function<? super I, ? extends O> function) { 447 checkNotNull(input); 448 checkNotNull(function); 449 return new Future<O>() { 450 451 @Override 452 public boolean cancel(boolean mayInterruptIfRunning) { 453 return input.cancel(mayInterruptIfRunning); 454 } 455 456 @Override 457 public boolean isCancelled() { 458 return input.isCancelled(); 459 } 460 461 @Override 462 public boolean isDone() { 463 return input.isDone(); 464 } 465 466 @Override 467 public O get() throws InterruptedException, ExecutionException { 468 return applyTransformation(input.get()); 469 } 470 471 @Override 472 public O get(long timeout, TimeUnit unit) 473 throws InterruptedException, ExecutionException, TimeoutException { 474 return applyTransformation(input.get(timeout, unit)); 475 } 476 477 private O applyTransformation(I input) throws ExecutionException { 478 try { 479 return function.apply(input); 480 } catch (Throwable t) { 481 throw new ExecutionException(t); 482 } 483 } 484 }; 485 } 486 487 /** 488 * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its 489 * input futures, if all succeed. 490 * 491 * <p>The list of results is in the same order as the input list. 492 * 493 * <p>Canceling this future will attempt to cancel all the component futures, and if any of the 494 * provided futures fails or is canceled, this one is, too. 495 * 496 * @param futures futures to combine 497 * @return a future that provides a list of the results of the component futures 498 * @since 10.0 499 */ 500 @Beta 501 @SafeVarargs 502 public static <V> ListenableFuture<List<V>> allAsList(ListenableFuture<? extends V>... futures) { 503 return new ListFuture<V>(ImmutableList.copyOf(futures), true); 504 } 505 506 /** 507 * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its 508 * input futures, if all succeed. 509 * 510 * <p>The list of results is in the same order as the input list. 511 * 512 * <p>Canceling this future will attempt to cancel all the component futures, and if any of the 513 * provided futures fails or is canceled, this one is, too. 514 * 515 * @param futures futures to combine 516 * @return a future that provides a list of the results of the component futures 517 * @since 10.0 518 */ 519 @Beta 520 public static <V> ListenableFuture<List<V>> allAsList( 521 Iterable<? extends ListenableFuture<? extends V>> futures) { 522 return new ListFuture<V>(ImmutableList.copyOf(futures), true); 523 } 524 525 /** 526 * Creates a {@link FutureCombiner} that processes the completed futures whether or not they're 527 * successful. 528 * 529 * @since 20.0 530 */ 531 @Beta 532 @SafeVarargs 533 public static <V> FutureCombiner<V> whenAllComplete(ListenableFuture<? extends V>... futures) { 534 return new FutureCombiner<V>(false, ImmutableList.copyOf(futures)); 535 } 536 537 /** 538 * Creates a {@link FutureCombiner} that processes the completed futures whether or not they're 539 * successful. 540 * 541 * @since 20.0 542 */ 543 @Beta 544 public static <V> FutureCombiner<V> whenAllComplete( 545 Iterable<? extends ListenableFuture<? extends V>> futures) { 546 return new FutureCombiner<V>(false, ImmutableList.copyOf(futures)); 547 } 548 549 /** 550 * Creates a {@link FutureCombiner} requiring that all passed in futures are successful. 551 * 552 * <p>If any input fails, the returned future fails immediately. 553 * 554 * @since 20.0 555 */ 556 @Beta 557 @SafeVarargs 558 public static <V> FutureCombiner<V> whenAllSucceed(ListenableFuture<? extends V>... futures) { 559 return new FutureCombiner<V>(true, ImmutableList.copyOf(futures)); 560 } 561 562 /** 563 * Creates a {@link FutureCombiner} requiring that all passed in futures are successful. 564 * 565 * <p>If any input fails, the returned future fails immediately. 566 * 567 * @since 20.0 568 */ 569 @Beta 570 public static <V> FutureCombiner<V> whenAllSucceed( 571 Iterable<? extends ListenableFuture<? extends V>> futures) { 572 return new FutureCombiner<V>(true, ImmutableList.copyOf(futures)); 573 } 574 575 /** 576 * A helper to create a new {@code ListenableFuture} whose result is generated from a combination 577 * of input futures. 578 * 579 * <p>See {@link #whenAllComplete} and {@link #whenAllSucceed} for how to instantiate this class. 580 * 581 * <p>Example: 582 * 583 * <pre>{@code 584 * final ListenableFuture<Instant> loginDateFuture = 585 * loginService.findLastLoginDate(username); 586 * final ListenableFuture<List<String>> recentCommandsFuture = 587 * recentCommandsService.findRecentCommands(username); 588 * ListenableFuture<UsageHistory> usageFuture = 589 * Futures.whenAllSucceed(loginDateFuture, recentCommandsFuture) 590 * .call( 591 * () -> 592 * new UsageHistory( 593 * username, 594 * Futures.getDone(loginDateFuture), 595 * Futures.getDone(recentCommandsFuture)), 596 * executor); 597 * }</pre> 598 * 599 * @since 20.0 600 */ 601 @Beta 602 @CanIgnoreReturnValue // TODO(cpovirk): Consider removing, especially if we provide run(Runnable) 603 @GwtCompatible 604 public static final class FutureCombiner<V> { 605 private final boolean allMustSucceed; 606 private final ImmutableList<ListenableFuture<? extends V>> futures; 607 608 private FutureCombiner( 609 boolean allMustSucceed, ImmutableList<ListenableFuture<? extends V>> futures) { 610 this.allMustSucceed = allMustSucceed; 611 this.futures = futures; 612 } 613 614 /** 615 * Creates the {@link ListenableFuture} which will return the result of calling {@link 616 * AsyncCallable#call} in {@code combiner} when all futures complete, using the specified {@code 617 * executor}. 618 * 619 * <p>If the combiner throws a {@code CancellationException}, the returned future will be 620 * cancelled. 621 * 622 * <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code 623 * ExecutionException} will be extracted and returned as the cause of the new {@code 624 * ExecutionException} that gets thrown by the returned combined future. 625 * 626 * <p>Canceling this future will attempt to cancel all the component futures. 627 */ 628 public <C> ListenableFuture<C> callAsync(AsyncCallable<C> combiner, Executor executor) { 629 return new CombinedFuture<C>(futures, allMustSucceed, executor, combiner); 630 } 631 632 /** 633 * Creates the {@link ListenableFuture} which will return the result of calling {@link 634 * Callable#call} in {@code combiner} when all futures complete, using the specified {@code 635 * executor}. 636 * 637 * <p>If the combiner throws a {@code CancellationException}, the returned future will be 638 * cancelled. 639 * 640 * <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code 641 * ExecutionException} will be extracted and returned as the cause of the new {@code 642 * ExecutionException} that gets thrown by the returned combined future. 643 * 644 * <p>Canceling this future will attempt to cancel all the component futures. 645 */ 646 @CanIgnoreReturnValue // TODO(cpovirk): Remove this 647 public <C> ListenableFuture<C> call(Callable<C> combiner, Executor executor) { 648 return new CombinedFuture<C>(futures, allMustSucceed, executor, combiner); 649 } 650 651 /** 652 * Creates the {@link ListenableFuture} which will return the result of running {@code combiner} 653 * when all Futures complete. {@code combiner} will run using {@code executor}. 654 * 655 * <p>If the combiner throws a {@code CancellationException}, the returned future will be 656 * cancelled. 657 * 658 * <p>Canceling this Future will attempt to cancel all the component futures. 659 * 660 * @since 23.6 661 */ 662 public ListenableFuture<?> run(final Runnable combiner, Executor executor) { 663 return call( 664 new Callable<Void>() { 665 @Override 666 public Void call() throws Exception { 667 combiner.run(); 668 return null; 669 } 670 }, 671 executor); 672 } 673 } 674 675 /** 676 * Returns a {@code ListenableFuture} whose result is set from the supplied future when it 677 * completes. Cancelling the supplied future will also cancel the returned future, but cancelling 678 * the returned future will have no effect on the supplied future. 679 * 680 * @since 15.0 681 */ 682 @Beta 683 public static <V> ListenableFuture<V> nonCancellationPropagating(ListenableFuture<V> future) { 684 if (future.isDone()) { 685 return future; 686 } 687 NonCancellationPropagatingFuture<V> output = new NonCancellationPropagatingFuture<>(future); 688 future.addListener(output, directExecutor()); 689 return output; 690 } 691 692 /** A wrapped future that does not propagate cancellation to its delegate. */ 693 private static final class NonCancellationPropagatingFuture<V> 694 extends AbstractFuture.TrustedFuture<V> implements Runnable { 695 private ListenableFuture<V> delegate; 696 697 NonCancellationPropagatingFuture(final ListenableFuture<V> delegate) { 698 this.delegate = delegate; 699 } 700 701 @Override 702 public void run() { 703 // This prevents cancellation from propagating because we don't call setFuture(delegate) until 704 // delegate is already done, so calling cancel() on this future won't affect it. 705 ListenableFuture<V> localDelegate = delegate; 706 if (localDelegate != null) { 707 setFuture(localDelegate); 708 } 709 } 710 711 @Override 712 protected String pendingToString() { 713 ListenableFuture<V> localDelegate = delegate; 714 if (localDelegate != null) { 715 return "delegate=[" + localDelegate + "]"; 716 } 717 return null; 718 } 719 720 @Override 721 protected void afterDone() { 722 delegate = null; 723 } 724 } 725 726 /** 727 * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its 728 * successful input futures. The list of results is in the same order as the input list, and if 729 * any of the provided futures fails or is canceled, its corresponding position will contain 730 * {@code null} (which is indistinguishable from the future having a successful value of {@code 731 * null}). 732 * 733 * <p>Canceling this future will attempt to cancel all the component futures. 734 * 735 * @param futures futures to combine 736 * @return a future that provides a list of the results of the component futures 737 * @since 10.0 738 */ 739 @Beta 740 @SafeVarargs 741 public static <V> ListenableFuture<List<V>> successfulAsList( 742 ListenableFuture<? extends V>... futures) { 743 return new ListFuture<V>(ImmutableList.copyOf(futures), false); 744 } 745 746 /** 747 * Creates a new {@code ListenableFuture} whose value is a list containing the values of all its 748 * successful input futures. The list of results is in the same order as the input list, and if 749 * any of the provided futures fails or is canceled, its corresponding position will contain 750 * {@code null} (which is indistinguishable from the future having a successful value of {@code 751 * null}). 752 * 753 * <p>Canceling this future will attempt to cancel all the component futures. 754 * 755 * @param futures futures to combine 756 * @return a future that provides a list of the results of the component futures 757 * @since 10.0 758 */ 759 @Beta 760 public static <V> ListenableFuture<List<V>> successfulAsList( 761 Iterable<? extends ListenableFuture<? extends V>> futures) { 762 return new ListFuture<V>(ImmutableList.copyOf(futures), false); 763 } 764 765 /** 766 * Returns a list of delegate futures that correspond to the futures received in the order that 767 * they complete. Delegate futures return the same value or throw the same exception as the 768 * corresponding input future returns/throws. 769 * 770 * <p>"In the order that they complete" means, for practical purposes, about what you would 771 * expect, but there are some subtleties. First, we do guarantee that, if the output future at 772 * index n is done, the output future at index n-1 is also done. (But as usual with futures, some 773 * listeners for future n may complete before some for future n-1.) However, it is possible, if 774 * one input completes with result X and another later with result Y, for Y to come before X in 775 * the output future list. (Such races are impossible to solve without global synchronization of 776 * all future completions. And they should have little practical impact.) 777 * 778 * <p>Cancelling a delegate future propagates to input futures once all the delegates complete, 779 * either from cancellation or because an input future has completed. If N futures are passed in, 780 * and M delegates are cancelled, the remaining M input futures will be cancelled once N - M of 781 * the input futures complete. If all the delegates are cancelled, all the input futures will be 782 * too. 783 * 784 * @since 17.0 785 */ 786 @Beta 787 public static <T> ImmutableList<ListenableFuture<T>> inCompletionOrder( 788 Iterable<? extends ListenableFuture<? extends T>> futures) { 789 // Can't use Iterables.toArray because it's not gwt compatible 790 final Collection<ListenableFuture<? extends T>> collection; 791 if (futures instanceof Collection) { 792 collection = (Collection<ListenableFuture<? extends T>>) futures; 793 } else { 794 collection = ImmutableList.copyOf(futures); 795 } 796 @SuppressWarnings("unchecked") 797 ListenableFuture<? extends T>[] copy = 798 (ListenableFuture<? extends T>[]) 799 collection.toArray(new ListenableFuture[collection.size()]); 800 final InCompletionOrderState<T> state = new InCompletionOrderState<>(copy); 801 ImmutableList.Builder<AbstractFuture<T>> delegatesBuilder = ImmutableList.builder(); 802 for (int i = 0; i < copy.length; i++) { 803 delegatesBuilder.add(new InCompletionOrderFuture<T>(state)); 804 } 805 806 final ImmutableList<AbstractFuture<T>> delegates = delegatesBuilder.build(); 807 for (int i = 0; i < copy.length; i++) { 808 final int localI = i; 809 copy[i].addListener( 810 new Runnable() { 811 @Override 812 public void run() { 813 state.recordInputCompletion(delegates, localI); 814 } 815 }, 816 directExecutor()); 817 } 818 819 @SuppressWarnings("unchecked") 820 ImmutableList<ListenableFuture<T>> delegatesCast = (ImmutableList) delegates; 821 return delegatesCast; 822 } 823 824 // This can't be a TrustedFuture, because TrustedFuture has clever optimizations that 825 // mean cancel won't be called if this Future is passed into setFuture, and then 826 // cancelled. 827 private static final class InCompletionOrderFuture<T> extends AbstractFuture<T> { 828 private InCompletionOrderState<T> state; 829 830 private InCompletionOrderFuture(InCompletionOrderState<T> state) { 831 this.state = state; 832 } 833 834 @Override 835 public boolean cancel(boolean interruptIfRunning) { 836 InCompletionOrderState<T> localState = state; 837 if (super.cancel(interruptIfRunning)) { 838 localState.recordOutputCancellation(interruptIfRunning); 839 return true; 840 } 841 return false; 842 } 843 844 @Override 845 protected void afterDone() { 846 state = null; 847 } 848 849 @Override 850 protected String pendingToString() { 851 InCompletionOrderState<T> localState = state; 852 if (localState != null) { 853 // Don't print the actual array! We don't want inCompletionOrder(list).toString() to have 854 // quadratic output. 855 return "inputCount=[" 856 + localState.inputFutures.length 857 + "], remaining=[" 858 + localState.incompleteOutputCount.get() 859 + "]"; 860 } 861 return null; 862 } 863 } 864 865 private static final class InCompletionOrderState<T> { 866 // A happens-before edge between the writes of these fields and their reads exists, because 867 // in order to read these fields, the corresponding write to incompleteOutputCount must have 868 // been read. 869 private boolean wasCancelled = false; 870 private boolean shouldInterrupt = true; 871 private final AtomicInteger incompleteOutputCount; 872 private final ListenableFuture<? extends T>[] inputFutures; 873 private volatile int delegateIndex = 0; 874 875 private InCompletionOrderState(ListenableFuture<? extends T>[] inputFutures) { 876 this.inputFutures = inputFutures; 877 incompleteOutputCount = new AtomicInteger(inputFutures.length); 878 } 879 880 private void recordOutputCancellation(boolean interruptIfRunning) { 881 wasCancelled = true; 882 // If all the futures were cancelled with interruption, cancel the input futures 883 // with interruption; otherwise cancel without 884 if (!interruptIfRunning) { 885 shouldInterrupt = false; 886 } 887 recordCompletion(); 888 } 889 890 private void recordInputCompletion( 891 ImmutableList<AbstractFuture<T>> delegates, int inputFutureIndex) { 892 ListenableFuture<? extends T> inputFuture = inputFutures[inputFutureIndex]; 893 // Null out our reference to this future, so it can be GCed 894 inputFutures[inputFutureIndex] = null; 895 for (int i = delegateIndex; i < delegates.size(); i++) { 896 if (delegates.get(i).setFuture(inputFuture)) { 897 recordCompletion(); 898 // this is technically unnecessary, but should speed up later accesses 899 delegateIndex = i + 1; 900 return; 901 } 902 } 903 // If all the delegates were complete, no reason for the next listener to have to 904 // go through the whole list. Avoids O(n^2) behavior when the entire output list is 905 // cancelled. 906 delegateIndex = delegates.size(); 907 } 908 909 private void recordCompletion() { 910 if (incompleteOutputCount.decrementAndGet() == 0 && wasCancelled) { 911 for (ListenableFuture<?> toCancel : inputFutures) { 912 if (toCancel != null) { 913 toCancel.cancel(shouldInterrupt); 914 } 915 } 916 } 917 } 918 } 919 920 /** 921 * Registers separate success and failure callbacks to be run when the {@code Future}'s 922 * computation is {@linkplain java.util.concurrent.Future#isDone() complete} or, if the 923 * computation is already complete, immediately. 924 * 925 * <p>The callback is run on {@code executor}. There is no guaranteed ordering of execution of 926 * callbacks, but any callback added through this method is guaranteed to be called once the 927 * computation is complete. 928 * 929 * <p>Example: 930 * 931 * <pre>{@code 932 * ListenableFuture<QueryResult> future = ...; 933 * Executor e = ... 934 * addCallback(future, 935 * new FutureCallback<QueryResult>() { 936 * public void onSuccess(QueryResult result) { 937 * storeInCache(result); 938 * } 939 * public void onFailure(Throwable t) { 940 * reportError(t); 941 * } 942 * }, e); 943 * }</pre> 944 * 945 * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See 946 * the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener} 947 * documentation. All its warnings about heavyweight listeners are also applicable to heavyweight 948 * callbacks passed to this method. 949 * 950 * <p>For a more general interface to attach a completion listener to a {@code Future}, see {@link 951 * ListenableFuture#addListener addListener}. 952 * 953 * @param future The future attach the callback to. 954 * @param callback The callback to invoke when {@code future} is completed. 955 * @param executor The executor to run {@code callback} when the future completes. 956 * @since 10.0 957 */ 958 public static <V> void addCallback( 959 final ListenableFuture<V> future, 960 final FutureCallback<? super V> callback, 961 Executor executor) { 962 Preconditions.checkNotNull(callback); 963 future.addListener(new CallbackListener<V>(future, callback), executor); 964 } 965 966 /** See {@link #addCallback(ListenableFuture, FutureCallback, Executor)} for behavioral notes. */ 967 private static final class CallbackListener<V> implements Runnable { 968 final Future<V> future; 969 final FutureCallback<? super V> callback; 970 971 CallbackListener(Future<V> future, FutureCallback<? super V> callback) { 972 this.future = future; 973 this.callback = callback; 974 } 975 976 @Override 977 public void run() { 978 final V value; 979 try { 980 value = getDone(future); 981 } catch (ExecutionException e) { 982 callback.onFailure(e.getCause()); 983 return; 984 } catch (RuntimeException | Error e) { 985 callback.onFailure(e); 986 return; 987 } 988 callback.onSuccess(value); 989 } 990 991 @Override 992 public String toString() { 993 return MoreObjects.toStringHelper(this).addValue(callback).toString(); 994 } 995 } 996 997 /** 998 * Returns the result of the input {@code Future}, which must have already completed. 999 * 1000 * <p>The benefits of this method are twofold. First, the name "getDone" suggests to readers that 1001 * the {@code Future} is already done. Second, if buggy code calls {@code getDone} on a {@code 1002 * Future} that is still pending, the program will throw instead of block. This can be important 1003 * for APIs like {@link #whenAllComplete whenAllComplete(...)}{@code .}{@link 1004 * FutureCombiner#call(Callable, Executor) call(...)}, where it is easy to use a new input from 1005 * the {@code call} implementation but forget to add it to the arguments of {@code 1006 * whenAllComplete}. 1007 * 1008 * <p>If you are looking for a method to determine whether a given {@code Future} is done, use the 1009 * instance method {@link Future#isDone()}. 1010 * 1011 * @throws ExecutionException if the {@code Future} failed with an exception 1012 * @throws CancellationException if the {@code Future} was cancelled 1013 * @throws IllegalStateException if the {@code Future} is not done 1014 * @since 20.0 1015 */ 1016 @CanIgnoreReturnValue 1017 // TODO(cpovirk): Consider calling getDone() in our own code. 1018 public static <V> V getDone(Future<V> future) throws ExecutionException { 1019 /* 1020 * We throw IllegalStateException, since the call could succeed later. Perhaps we "should" throw 1021 * IllegalArgumentException, since the call could succeed with a different argument. Those 1022 * exceptions' docs suggest that either is acceptable. Google's Java Practices page recommends 1023 * IllegalArgumentException here, in part to keep its recommendation simple: Static methods 1024 * should throw IllegalStateException only when they use static state. 1025 * 1026 * 1027 * Why do we deviate here? The answer: We want for fluentFuture.getDone() to throw the same 1028 * exception as Futures.getDone(fluentFuture). 1029 */ 1030 checkState(future.isDone(), "Future was expected to be done: %s", future); 1031 return getUninterruptibly(future); 1032 } 1033 1034 /** 1035 * Returns the result of {@link Future#get()}, converting most exceptions to a new instance of the 1036 * given checked exception type. This reduces boilerplate for a common use of {@code Future} in 1037 * which it is unnecessary to programmatically distinguish between exception types or to extract 1038 * other information from the exception instance. 1039 * 1040 * <p>Exceptions from {@code Future.get} are treated as follows: 1041 * 1042 * <ul> 1043 * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause 1044 * is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code 1045 * RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}. 1046 * <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the 1047 * interrupt). 1048 * <li>Any {@link CancellationException} is propagated untouched, as is any other {@link 1049 * RuntimeException} (though {@code get} implementations are discouraged from throwing such 1050 * exceptions). 1051 * </ul> 1052 * 1053 * <p>The overall principle is to continue to treat every checked exception as a checked 1054 * exception, every unchecked exception as an unchecked exception, and every error as an error. In 1055 * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the 1056 * new stack trace matches that of the current thread. 1057 * 1058 * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor 1059 * that accepts zero or more arguments, all of type {@code String} or {@code Throwable} 1060 * (preferring constructors with at least one {@code String}) and calling the constructor via 1061 * reflection. If the exception did not already have a cause, one is set by calling {@link 1062 * Throwable#initCause(Throwable)} on it. If no such constructor exists, an {@code 1063 * IllegalArgumentException} is thrown. 1064 * 1065 * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException} 1066 * whose cause is not itself a checked exception 1067 * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a 1068 * {@code RuntimeException} as its cause 1069 * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code 1070 * Error} as its cause 1071 * @throws CancellationException if {@code get} throws a {@code CancellationException} 1072 * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or 1073 * does not have a suitable constructor 1074 * @since 19.0 (in 10.0 as {@code get}) 1075 */ 1076 @Beta 1077 @CanIgnoreReturnValue 1078 @GwtIncompatible // reflection 1079 public static <V, X extends Exception> V getChecked(Future<V> future, Class<X> exceptionClass) 1080 throws X { 1081 return FuturesGetChecked.getChecked(future, exceptionClass); 1082 } 1083 1084 /** 1085 * Returns the result of {@link Future#get(long, TimeUnit)}, converting most exceptions to a new 1086 * instance of the given checked exception type. This reduces boilerplate for a common use of 1087 * {@code Future} in which it is unnecessary to programmatically distinguish between exception 1088 * types or to extract other information from the exception instance. 1089 * 1090 * <p>Exceptions from {@code Future.get} are treated as follows: 1091 * 1092 * <ul> 1093 * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause 1094 * is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code 1095 * RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}. 1096 * <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the 1097 * interrupt). 1098 * <li>Any {@link TimeoutException} is wrapped in an {@code X}. 1099 * <li>Any {@link CancellationException} is propagated untouched, as is any other {@link 1100 * RuntimeException} (though {@code get} implementations are discouraged from throwing such 1101 * exceptions). 1102 * </ul> 1103 * 1104 * <p>The overall principle is to continue to treat every checked exception as a checked 1105 * exception, every unchecked exception as an unchecked exception, and every error as an error. In 1106 * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the 1107 * new stack trace matches that of the current thread. 1108 * 1109 * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor 1110 * that accepts zero or more arguments, all of type {@code String} or {@code Throwable} 1111 * (preferring constructors with at least one {@code String}) and calling the constructor via 1112 * reflection. If the exception did not already have a cause, one is set by calling {@link 1113 * Throwable#initCause(Throwable)} on it. If no such constructor exists, an {@code 1114 * IllegalArgumentException} is thrown. 1115 * 1116 * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException} 1117 * whose cause is not itself a checked exception 1118 * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a 1119 * {@code RuntimeException} as its cause 1120 * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code 1121 * Error} as its cause 1122 * @throws CancellationException if {@code get} throws a {@code CancellationException} 1123 * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or 1124 * does not have a suitable constructor 1125 * @since 19.0 (in 10.0 as {@code get} and with different parameter order) 1126 */ 1127 @Beta 1128 @CanIgnoreReturnValue 1129 @GwtIncompatible // reflection 1130 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 1131 public static <V, X extends Exception> V getChecked( 1132 Future<V> future, Class<X> exceptionClass, long timeout, TimeUnit unit) throws X { 1133 return FuturesGetChecked.getChecked(future, exceptionClass, timeout, unit); 1134 } 1135 1136 /** 1137 * Returns the result of calling {@link Future#get()} uninterruptibly on a task known not to throw 1138 * a checked exception. This makes {@code Future} more suitable for lightweight, fast-running 1139 * tasks that, barring bugs in the code, will not fail. This gives it exception-handling behavior 1140 * similar to that of {@code ForkJoinTask.join}. 1141 * 1142 * <p>Exceptions from {@code Future.get} are treated as follows: 1143 * 1144 * <ul> 1145 * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@link 1146 * UncheckedExecutionException} (if the cause is an {@code Exception}) or {@link 1147 * ExecutionError} (if the cause is an {@code Error}). 1148 * <li>Any {@link InterruptedException} causes a retry of the {@code get} call. The interrupt is 1149 * restored before {@code getUnchecked} returns. 1150 * <li>Any {@link CancellationException} is propagated untouched. So is any other {@link 1151 * RuntimeException} ({@code get} implementations are discouraged from throwing such 1152 * exceptions). 1153 * </ul> 1154 * 1155 * <p>The overall principle is to eliminate all checked exceptions: to loop to avoid {@code 1156 * InterruptedException}, to pass through {@code CancellationException}, and to wrap any exception 1157 * from the underlying computation in an {@code UncheckedExecutionException} or {@code 1158 * ExecutionError}. 1159 * 1160 * <p>For an uninterruptible {@code get} that preserves other exceptions, see {@link 1161 * Uninterruptibles#getUninterruptibly(Future)}. 1162 * 1163 * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with an 1164 * {@code Exception} as its cause 1165 * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code 1166 * Error} as its cause 1167 * @throws CancellationException if {@code get} throws a {@code CancellationException} 1168 * @since 10.0 1169 */ 1170 @CanIgnoreReturnValue 1171 public static <V> V getUnchecked(Future<V> future) { 1172 checkNotNull(future); 1173 try { 1174 return getUninterruptibly(future); 1175 } catch (ExecutionException e) { 1176 wrapAndThrowUnchecked(e.getCause()); 1177 throw new AssertionError(); 1178 } 1179 } 1180 1181 private static void wrapAndThrowUnchecked(Throwable cause) { 1182 if (cause instanceof Error) { 1183 throw new ExecutionError((Error) cause); 1184 } 1185 /* 1186 * It's an Exception. (Or it's a non-Error, non-Exception Throwable. From my survey of such 1187 * classes, I believe that most users intended to extend Exception, so we'll treat it like an 1188 * Exception.) 1189 */ 1190 throw new UncheckedExecutionException(cause); 1191 } 1192 1193 /* 1194 * Arguably we don't need a timed getUnchecked because any operation slow enough to require a 1195 * timeout is heavyweight enough to throw a checked exception and therefore be inappropriate to 1196 * use with getUnchecked. Further, it's not clear that converting the checked TimeoutException to 1197 * a RuntimeException -- especially to an UncheckedExecutionException, since it wasn't thrown by 1198 * the computation -- makes sense, and if we don't convert it, the user still has to write a 1199 * try-catch block. 1200 * 1201 * If you think you would use this method, let us know. You might also also look into the 1202 * Fork-Join framework: http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html 1203 */ 1204}