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