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.Internal.toNanosSaturated; 020import static com.google.common.util.concurrent.MoreExecutors.directExecutor; 021import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly; 022 023import com.google.common.annotations.Beta; 024import com.google.common.annotations.GwtCompatible; 025import com.google.common.annotations.GwtIncompatible; 026import com.google.common.base.Function; 027import com.google.common.base.MoreObjects; 028import com.google.common.base.Preconditions; 029import com.google.common.collect.ImmutableList; 030import com.google.common.util.concurrent.CollectionFuture.ListFuture; 031import com.google.common.util.concurrent.ImmediateFuture.ImmediateCancelledFuture; 032import com.google.common.util.concurrent.ImmediateFuture.ImmediateFailedFuture; 033import com.google.common.util.concurrent.internal.InternalFutureFailureAccess; 034import com.google.common.util.concurrent.internal.InternalFutures; 035import com.google.errorprone.annotations.CanIgnoreReturnValue; 036import java.time.Duration; 037import java.util.Collection; 038import java.util.List; 039import java.util.concurrent.Callable; 040import java.util.concurrent.CancellationException; 041import java.util.concurrent.ExecutionException; 042import java.util.concurrent.Executor; 043import java.util.concurrent.Future; 044import java.util.concurrent.RejectedExecutionException; 045import java.util.concurrent.ScheduledExecutorService; 046import java.util.concurrent.TimeUnit; 047import java.util.concurrent.TimeoutException; 048import java.util.concurrent.atomic.AtomicInteger; 049import org.checkerframework.checker.nullness.qual.Nullable; 050 051/** 052 * Static utility methods pertaining to the {@link Future} interface. 053 * 054 * <p>Many of these methods use the {@link ListenableFuture} API; consult the Guava User Guide 055 * article on <a href="https://github.com/google/guava/wiki/ListenableFutureExplained">{@code 056 * ListenableFuture}</a>. 057 * 058 * <p>The main purpose of {@code ListenableFuture} is to help you chain together a graph of 059 * asynchronous operations. You can chain them together manually with calls to methods like {@link 060 * Futures#transform(ListenableFuture, Function, Executor) Futures.transform}, but you will often 061 * find it easier to use a framework. Frameworks automate the process, often adding features like 062 * monitoring, debugging, and cancellation. Examples of frameworks include: 063 * 064 * <ul> 065 * <li><a href="https://dagger.dev/producers.html">Dagger Producers</a> 066 * </ul> 067 * 068 * <p>If you do chain your operations manually, you may want to use {@link FluentFuture}. 069 * 070 * @author Kevin Bourrillion 071 * @author Nishant Thakkar 072 * @author Sven Mawson 073 * @since 1.0 074 */ 075@GwtCompatible(emulated = true) 076public final class Futures extends GwtFuturesCatchingSpecialization { 077 078 // A note on memory visibility. 079 // Many of the utilities in this class (transform, withFallback, withTimeout, asList, combine) 080 // have two requirements that significantly complicate their design. 081 // 1. Cancellation should propagate from the returned future to the input future(s). 082 // 2. The returned futures shouldn't unnecessarily 'pin' their inputs after completion. 083 // 084 // A consequence of these requirements is that the delegate futures cannot be stored in 085 // final fields. 086 // 087 // For simplicity the rest of this description will discuss Futures.catching since it is the 088 // simplest instance, though very similar descriptions apply to many other classes in this file. 089 // 090 // In the constructor of AbstractCatchingFuture, the delegate future is assigned to a field 091 // 'inputFuture'. That field is non-final and non-volatile. There are 2 places where the 092 // 'inputFuture' field is read and where we will have to consider visibility of the write 093 // operation in the constructor. 094 // 095 // 1. In the listener that performs the callback. In this case it is fine since inputFuture is 096 // assigned prior to calling addListener, and addListener happens-before any invocation of the 097 // listener. Notably, this means that 'volatile' is unnecessary to make 'inputFuture' visible 098 // to the listener. 099 // 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 // Can't use Iterables.toArray because it's not gwt compatible 871 final Collection<ListenableFuture<? extends T>> collection; 872 if (futures instanceof Collection) { 873 collection = (Collection<ListenableFuture<? extends T>>) futures; 874 } else { 875 collection = ImmutableList.copyOf(futures); 876 } 877 @SuppressWarnings("unchecked") 878 ListenableFuture<? extends T>[] copy = 879 (ListenableFuture<? extends T>[]) 880 collection.toArray(new ListenableFuture[collection.size()]); 881 final InCompletionOrderState<T> state = new InCompletionOrderState<>(copy); 882 ImmutableList.Builder<AbstractFuture<T>> delegatesBuilder = ImmutableList.builder(); 883 for (int i = 0; i < copy.length; i++) { 884 delegatesBuilder.add(new InCompletionOrderFuture<T>(state)); 885 } 886 887 final ImmutableList<AbstractFuture<T>> delegates = delegatesBuilder.build(); 888 for (int i = 0; i < copy.length; i++) { 889 final int localI = i; 890 copy[i].addListener( 891 new Runnable() { 892 @Override 893 public void run() { 894 state.recordInputCompletion(delegates, localI); 895 } 896 }, 897 directExecutor()); 898 } 899 900 @SuppressWarnings("unchecked") 901 ImmutableList<ListenableFuture<T>> delegatesCast = (ImmutableList) delegates; 902 return delegatesCast; 903 } 904 905 // This can't be a TrustedFuture, because TrustedFuture has clever optimizations that 906 // mean cancel won't be called if this Future is passed into setFuture, and then 907 // cancelled. 908 private static final class InCompletionOrderFuture<T> extends AbstractFuture<T> { 909 private InCompletionOrderState<T> state; 910 911 private InCompletionOrderFuture(InCompletionOrderState<T> state) { 912 this.state = state; 913 } 914 915 @Override 916 public boolean cancel(boolean interruptIfRunning) { 917 InCompletionOrderState<T> localState = state; 918 if (super.cancel(interruptIfRunning)) { 919 localState.recordOutputCancellation(interruptIfRunning); 920 return true; 921 } 922 return false; 923 } 924 925 @Override 926 protected void afterDone() { 927 state = null; 928 } 929 930 @Override 931 protected String pendingToString() { 932 InCompletionOrderState<T> localState = state; 933 if (localState != null) { 934 // Don't print the actual array! We don't want inCompletionOrder(list).toString() to have 935 // quadratic output. 936 return "inputCount=[" 937 + localState.inputFutures.length 938 + "], remaining=[" 939 + localState.incompleteOutputCount.get() 940 + "]"; 941 } 942 return null; 943 } 944 } 945 946 private static final class InCompletionOrderState<T> { 947 // A happens-before edge between the writes of these fields and their reads exists, because 948 // in order to read these fields, the corresponding write to incompleteOutputCount must have 949 // been read. 950 private boolean wasCancelled = false; 951 private boolean shouldInterrupt = true; 952 private final AtomicInteger incompleteOutputCount; 953 private final ListenableFuture<? extends T>[] inputFutures; 954 private volatile int delegateIndex = 0; 955 956 private InCompletionOrderState(ListenableFuture<? extends T>[] inputFutures) { 957 this.inputFutures = inputFutures; 958 incompleteOutputCount = new AtomicInteger(inputFutures.length); 959 } 960 961 private void recordOutputCancellation(boolean interruptIfRunning) { 962 wasCancelled = true; 963 // If all the futures were cancelled with interruption, cancel the input futures 964 // with interruption; otherwise cancel without 965 if (!interruptIfRunning) { 966 shouldInterrupt = false; 967 } 968 recordCompletion(); 969 } 970 971 private void recordInputCompletion( 972 ImmutableList<AbstractFuture<T>> delegates, int inputFutureIndex) { 973 ListenableFuture<? extends T> inputFuture = inputFutures[inputFutureIndex]; 974 // Null out our reference to this future, so it can be GCed 975 inputFutures[inputFutureIndex] = null; 976 for (int i = delegateIndex; i < delegates.size(); i++) { 977 if (delegates.get(i).setFuture(inputFuture)) { 978 recordCompletion(); 979 // this is technically unnecessary, but should speed up later accesses 980 delegateIndex = i + 1; 981 return; 982 } 983 } 984 // If all the delegates were complete, no reason for the next listener to have to 985 // go through the whole list. Avoids O(n^2) behavior when the entire output list is 986 // cancelled. 987 delegateIndex = delegates.size(); 988 } 989 990 private void recordCompletion() { 991 if (incompleteOutputCount.decrementAndGet() == 0 && wasCancelled) { 992 for (ListenableFuture<?> toCancel : inputFutures) { 993 if (toCancel != null) { 994 toCancel.cancel(shouldInterrupt); 995 } 996 } 997 } 998 } 999 } 1000 1001 /** 1002 * Registers separate success and failure callbacks to be run when the {@code Future}'s 1003 * computation is {@linkplain java.util.concurrent.Future#isDone() complete} or, if the 1004 * computation is already complete, immediately. 1005 * 1006 * <p>The callback is run on {@code executor}. There is no guaranteed ordering of execution of 1007 * callbacks, but any callback added through this method is guaranteed to be called once the 1008 * computation is complete. 1009 * 1010 * <p>Exceptions thrown by a {@code callback} will be propagated up to the executor. Any exception 1011 * thrown during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an 1012 * exception thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught 1013 * and logged. 1014 * 1015 * <p>Example: 1016 * 1017 * <pre>{@code 1018 * ListenableFuture<QueryResult> future = ...; 1019 * Executor e = ... 1020 * addCallback(future, 1021 * new FutureCallback<QueryResult>() { 1022 * public void onSuccess(QueryResult result) { 1023 * storeInCache(result); 1024 * } 1025 * public void onFailure(Throwable t) { 1026 * reportError(t); 1027 * } 1028 * }, e); 1029 * }</pre> 1030 * 1031 * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See 1032 * the warnings the {@link MoreExecutors#directExecutor} documentation. 1033 * 1034 * <p>For a more general interface to attach a completion listener to a {@code Future}, see {@link 1035 * ListenableFuture#addListener addListener}. 1036 * 1037 * @param future The future attach the callback to. 1038 * @param callback The callback to invoke when {@code future} is completed. 1039 * @param executor The executor to run {@code callback} when the future completes. 1040 * @since 10.0 1041 */ 1042 public static <V> void addCallback( 1043 final ListenableFuture<V> future, 1044 final FutureCallback<? super V> callback, 1045 Executor executor) { 1046 Preconditions.checkNotNull(callback); 1047 future.addListener(new CallbackListener<V>(future, callback), executor); 1048 } 1049 1050 /** See {@link #addCallback(ListenableFuture, FutureCallback, Executor)} for behavioral notes. */ 1051 private static final class CallbackListener<V> implements Runnable { 1052 final Future<V> future; 1053 final FutureCallback<? super V> callback; 1054 1055 CallbackListener(Future<V> future, FutureCallback<? super V> callback) { 1056 this.future = future; 1057 this.callback = callback; 1058 } 1059 1060 @Override 1061 public void run() { 1062 if (future instanceof InternalFutureFailureAccess) { 1063 Throwable failure = 1064 InternalFutures.tryInternalFastPathGetFailure((InternalFutureFailureAccess) future); 1065 if (failure != null) { 1066 callback.onFailure(failure); 1067 return; 1068 } 1069 } 1070 final V value; 1071 try { 1072 value = getDone(future); 1073 } catch (ExecutionException e) { 1074 callback.onFailure(e.getCause()); 1075 return; 1076 } catch (RuntimeException | Error e) { 1077 callback.onFailure(e); 1078 return; 1079 } 1080 callback.onSuccess(value); 1081 } 1082 1083 @Override 1084 public String toString() { 1085 return MoreObjects.toStringHelper(this).addValue(callback).toString(); 1086 } 1087 } 1088 1089 /** 1090 * Returns the result of the input {@code Future}, which must have already completed. 1091 * 1092 * <p>The benefits of this method are twofold. First, the name "getDone" suggests to readers that 1093 * the {@code Future} is already done. Second, if buggy code calls {@code getDone} on a {@code 1094 * Future} that is still pending, the program will throw instead of block. This can be important 1095 * for APIs like {@link #whenAllComplete whenAllComplete(...)}{@code .}{@link 1096 * FutureCombiner#call(Callable, Executor) call(...)}, where it is easy to use a new input from 1097 * the {@code call} implementation but forget to add it to the arguments of {@code 1098 * whenAllComplete}. 1099 * 1100 * <p>If you are looking for a method to determine whether a given {@code Future} is done, use the 1101 * instance method {@link Future#isDone()}. 1102 * 1103 * @throws ExecutionException if the {@code Future} failed with an exception 1104 * @throws CancellationException if the {@code Future} was cancelled 1105 * @throws IllegalStateException if the {@code Future} is not done 1106 * @since 20.0 1107 */ 1108 @CanIgnoreReturnValue 1109 // TODO(cpovirk): Consider calling getDone() in our own code. 1110 public static <V> V getDone(Future<V> future) throws ExecutionException { 1111 /* 1112 * We throw IllegalStateException, since the call could succeed later. Perhaps we "should" throw 1113 * IllegalArgumentException, since the call could succeed with a different argument. Those 1114 * exceptions' docs suggest that either is acceptable. Google's Java Practices page recommends 1115 * IllegalArgumentException here, in part to keep its recommendation simple: Static methods 1116 * should throw IllegalStateException only when they use static state. 1117 * 1118 * Why do we deviate here? The answer: We want for fluentFuture.getDone() to throw the same 1119 * exception as Futures.getDone(fluentFuture). 1120 */ 1121 checkState(future.isDone(), "Future was expected to be done: %s", future); 1122 return getUninterruptibly(future); 1123 } 1124 1125 /** 1126 * Returns the result of {@link Future#get()}, converting most exceptions to a new instance of the 1127 * given checked exception type. This reduces boilerplate for a common use of {@code Future} in 1128 * which it is unnecessary to programmatically distinguish between exception types or to extract 1129 * other information from the exception instance. 1130 * 1131 * <p>Exceptions from {@code Future.get} are treated as follows: 1132 * 1133 * <ul> 1134 * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause 1135 * is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code 1136 * RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}. 1137 * <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the 1138 * interrupt). 1139 * <li>Any {@link CancellationException} is propagated untouched, as is any other {@link 1140 * RuntimeException} (though {@code get} implementations are discouraged from throwing such 1141 * exceptions). 1142 * </ul> 1143 * 1144 * <p>The overall principle is to continue to treat every checked exception as a checked 1145 * exception, every unchecked exception as an unchecked exception, and every error as an error. In 1146 * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the 1147 * new stack trace matches that of the current thread. 1148 * 1149 * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor 1150 * that accepts zero or more arguments, all of type {@code String} or {@code Throwable} 1151 * (preferring constructors with at least one {@code String}) and calling the constructor via 1152 * reflection. If the exception did not already have a cause, one is set by calling {@link 1153 * Throwable#initCause(Throwable)} on it. If no such constructor exists, an {@code 1154 * IllegalArgumentException} is thrown. 1155 * 1156 * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException} 1157 * whose cause is not itself a checked exception 1158 * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a 1159 * {@code RuntimeException} as its cause 1160 * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code 1161 * Error} as its cause 1162 * @throws CancellationException if {@code get} throws a {@code CancellationException} 1163 * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or 1164 * does not have a suitable constructor 1165 * @since 19.0 (in 10.0 as {@code get}) 1166 */ 1167 @Beta 1168 @CanIgnoreReturnValue 1169 @GwtIncompatible // reflection 1170 public static <V, X extends Exception> V getChecked(Future<V> future, Class<X> exceptionClass) 1171 throws X { 1172 return FuturesGetChecked.getChecked(future, exceptionClass); 1173 } 1174 1175 /** 1176 * Returns the result of {@link Future#get(long, TimeUnit)}, converting most exceptions to a new 1177 * instance of the given checked exception type. This reduces boilerplate for a common use of 1178 * {@code Future} in which it is unnecessary to programmatically distinguish between exception 1179 * types or to extract other information from the exception instance. 1180 * 1181 * <p>Exceptions from {@code Future.get} are treated as follows: 1182 * 1183 * <ul> 1184 * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause 1185 * is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code 1186 * RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}. 1187 * <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the 1188 * interrupt). 1189 * <li>Any {@link TimeoutException} is wrapped in an {@code X}. 1190 * <li>Any {@link CancellationException} is propagated untouched, as is any other {@link 1191 * RuntimeException} (though {@code get} implementations are discouraged from throwing such 1192 * exceptions). 1193 * </ul> 1194 * 1195 * <p>The overall principle is to continue to treat every checked exception as a checked 1196 * exception, every unchecked exception as an unchecked exception, and every error as an error. In 1197 * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the 1198 * new stack trace matches that of the current thread. 1199 * 1200 * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor 1201 * that accepts zero or more arguments, all of type {@code String} or {@code Throwable} 1202 * (preferring constructors with at least one {@code String}) and calling the constructor via 1203 * reflection. If the exception did not already have a cause, one is set by calling {@link 1204 * Throwable#initCause(Throwable)} on it. If no such constructor exists, an {@code 1205 * IllegalArgumentException} is thrown. 1206 * 1207 * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException} 1208 * whose cause is not itself a checked exception 1209 * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a 1210 * {@code RuntimeException} as its cause 1211 * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code 1212 * Error} as its cause 1213 * @throws CancellationException if {@code get} throws a {@code CancellationException} 1214 * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or 1215 * does not have a suitable constructor 1216 * @since 28.0 1217 */ 1218 @Beta 1219 @CanIgnoreReturnValue 1220 @GwtIncompatible // reflection 1221 public static <V, X extends Exception> V getChecked( 1222 Future<V> future, Class<X> exceptionClass, Duration timeout) throws X { 1223 return getChecked(future, exceptionClass, toNanosSaturated(timeout), TimeUnit.NANOSECONDS); 1224 } 1225 1226 /** 1227 * Returns the result of {@link Future#get(long, TimeUnit)}, converting most exceptions to a new 1228 * instance of the given checked exception type. This reduces boilerplate for a common use of 1229 * {@code Future} in which it is unnecessary to programmatically distinguish between exception 1230 * types or to extract other information from the exception instance. 1231 * 1232 * <p>Exceptions from {@code Future.get} are treated as follows: 1233 * 1234 * <ul> 1235 * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@code X} if the cause 1236 * is a checked exception, an {@link UncheckedExecutionException} if the cause is a {@code 1237 * RuntimeException}, or an {@link ExecutionError} if the cause is an {@code Error}. 1238 * <li>Any {@link InterruptedException} is wrapped in an {@code X} (after restoring the 1239 * interrupt). 1240 * <li>Any {@link TimeoutException} is wrapped in an {@code X}. 1241 * <li>Any {@link CancellationException} is propagated untouched, as is any other {@link 1242 * RuntimeException} (though {@code get} implementations are discouraged from throwing such 1243 * exceptions). 1244 * </ul> 1245 * 1246 * <p>The overall principle is to continue to treat every checked exception as a checked 1247 * exception, every unchecked exception as an unchecked exception, and every error as an error. In 1248 * addition, the cause of any {@code ExecutionException} is wrapped in order to ensure that the 1249 * new stack trace matches that of the current thread. 1250 * 1251 * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary public constructor 1252 * that accepts zero or more arguments, all of type {@code String} or {@code Throwable} 1253 * (preferring constructors with at least one {@code String}) and calling the constructor via 1254 * reflection. If the exception did not already have a cause, one is set by calling {@link 1255 * Throwable#initCause(Throwable)} on it. If no such constructor exists, an {@code 1256 * IllegalArgumentException} is thrown. 1257 * 1258 * @throws X if {@code get} throws any checked exception except for an {@code ExecutionException} 1259 * whose cause is not itself a checked exception 1260 * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with a 1261 * {@code RuntimeException} as its cause 1262 * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code 1263 * Error} as its cause 1264 * @throws CancellationException if {@code get} throws a {@code CancellationException} 1265 * @throws IllegalArgumentException if {@code exceptionClass} extends {@code RuntimeException} or 1266 * does not have a suitable constructor 1267 * @since 19.0 (in 10.0 as {@code get} and with different parameter order) 1268 */ 1269 @Beta 1270 @CanIgnoreReturnValue 1271 @GwtIncompatible // reflection 1272 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 1273 public static <V, X extends Exception> V getChecked( 1274 Future<V> future, Class<X> exceptionClass, long timeout, TimeUnit unit) throws X { 1275 return FuturesGetChecked.getChecked(future, exceptionClass, timeout, unit); 1276 } 1277 1278 /** 1279 * Returns the result of calling {@link Future#get()} uninterruptibly on a task known not to throw 1280 * a checked exception. This makes {@code Future} more suitable for lightweight, fast-running 1281 * tasks that, barring bugs in the code, will not fail. This gives it exception-handling behavior 1282 * similar to that of {@code ForkJoinTask.join}. 1283 * 1284 * <p>Exceptions from {@code Future.get} are treated as follows: 1285 * 1286 * <ul> 1287 * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@link 1288 * UncheckedExecutionException} (if the cause is an {@code Exception}) or {@link 1289 * ExecutionError} (if the cause is an {@code Error}). 1290 * <li>Any {@link InterruptedException} causes a retry of the {@code get} call. The interrupt is 1291 * restored before {@code getUnchecked} returns. 1292 * <li>Any {@link CancellationException} is propagated untouched. So is any other {@link 1293 * RuntimeException} ({@code get} implementations are discouraged from throwing such 1294 * exceptions). 1295 * </ul> 1296 * 1297 * <p>The overall principle is to eliminate all checked exceptions: to loop to avoid {@code 1298 * InterruptedException}, to pass through {@code CancellationException}, and to wrap any exception 1299 * from the underlying computation in an {@code UncheckedExecutionException} or {@code 1300 * ExecutionError}. 1301 * 1302 * <p>For an uninterruptible {@code get} that preserves other exceptions, see {@link 1303 * Uninterruptibles#getUninterruptibly(Future)}. 1304 * 1305 * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with an 1306 * {@code Exception} as its cause 1307 * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code 1308 * Error} as its cause 1309 * @throws CancellationException if {@code get} throws a {@code CancellationException} 1310 * @since 10.0 1311 */ 1312 @CanIgnoreReturnValue 1313 public static <V> V getUnchecked(Future<V> future) { 1314 checkNotNull(future); 1315 try { 1316 return getUninterruptibly(future); 1317 } catch (ExecutionException e) { 1318 wrapAndThrowUnchecked(e.getCause()); 1319 throw new AssertionError(); 1320 } 1321 } 1322 1323 private static void wrapAndThrowUnchecked(Throwable cause) { 1324 if (cause instanceof Error) { 1325 throw new ExecutionError((Error) cause); 1326 } 1327 /* 1328 * It's an Exception. (Or it's a non-Error, non-Exception Throwable. From my survey of such 1329 * classes, I believe that most users intended to extend Exception, so we'll treat it like an 1330 * Exception.) 1331 */ 1332 throw new UncheckedExecutionException(cause); 1333 } 1334 1335 /* 1336 * Arguably we don't need a timed getUnchecked because any operation slow enough to require a 1337 * timeout is heavyweight enough to throw a checked exception and therefore be inappropriate to 1338 * use with getUnchecked. Further, it's not clear that converting the checked TimeoutException to 1339 * a RuntimeException -- especially to an UncheckedExecutionException, since it wasn't thrown by 1340 * the computation -- makes sense, and if we don't convert it, the user still has to write a 1341 * try-catch block. 1342 * 1343 * If you think you would use this method, let us know. You might also also look into the 1344 * Fork-Join framework: http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html 1345 */ 1346}