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