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