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