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