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