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