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