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