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