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