Class Futures
Future interface.
Many of these methods use the ListenableFuture API; consult the Guava User Guide
article on
ListenableFuture.
- Since:
- 1.0
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final classA helper to create a newListenableFuturewhose result is generated from a combination of input futures. -
Method Summary
Modifier and TypeMethodDescriptionstatic <V> voidaddCallback(ListenableFuture<V> future, FutureCallback<? super V> callback) Registers separate success and failure callbacks to be run when theFuture's computation is complete or, if the computation is already complete, immediately.static <V> voidaddCallback(ListenableFuture<V> future, FutureCallback<? super V> callback, Executor executor) Registers separate success and failure callbacks to be run when theFuture's computation is complete or, if the computation is already complete, immediately.static <V> ListenableFuture<List<V>> allAsList(ListenableFuture<? extends V>... futures) Creates a newListenableFuturewhose value is a list containing the values of all its input futures, if all succeed.static <V> ListenableFuture<List<V>> allAsList(Iterable<? extends ListenableFuture<? extends V>> futures) Creates a newListenableFuturewhose value is a list containing the values of all its input futures, if all succeed.static <V,X extends Throwable>
ListenableFuture<V> catching(ListenableFuture<? extends V> input, Class<X> exceptionType, Function<? super X, ? extends V> fallback) Returns aFuturewhose result is taken from the given primaryinputor, if the primary input fails with the givenexceptionType, from the result provided by thefallback.static <V,X extends Throwable>
ListenableFuture<V> catching(ListenableFuture<? extends V> input, Class<X> exceptionType, Function<? super X, ? extends V> fallback, Executor executor) Returns aFuturewhose result is taken from the given primaryinputor, if the primary input fails with the givenexceptionType, from the result provided by thefallback.static <V,X extends Throwable>
ListenableFuture<V> catchingAsync(ListenableFuture<? extends V> input, Class<X> exceptionType, AsyncFunction<? super X, ? extends V> fallback) Returns aFuturewhose result is taken from the given primaryinputor, if the primary input fails with the givenexceptionType, from the result provided by thefallback.static <V,X extends Throwable>
ListenableFuture<V> catchingAsync(ListenableFuture<? extends V> input, Class<X> exceptionType, AsyncFunction<? super X, ? extends V> fallback, Executor executor) Returns aFuturewhose result is taken from the given primaryinputor, if the primary input fails with the givenexceptionType, from the result provided by thefallback.static <V> ListenableFuture<V> dereference(ListenableFuture<? extends ListenableFuture<? extends V>> nested) Returns a newListenableFuturewhose result is the product of callingget()on theFuturenested within the givenFuture, effectively chaining the futures one after the other.static <V,X extends Exception>
VgetChecked(Future<V> future, Class<X> exceptionClass) Returns the result ofFuture.get(), converting most exceptions to a new instance of the given checked exception type.static <V,X extends Exception>
VgetChecked(Future<V> future, Class<X> exceptionClass, long timeout, TimeUnit unit) Returns the result ofFuture.get(long, TimeUnit), converting most exceptions to a new instance of the given checked exception type.static <V> VReturns the result of the inputFuture, which must have already completed.static <V> VgetUnchecked(Future<V> future) Returns the result of callingFuture.get()uninterruptibly on a task known not to throw a checked exception.static <V> ListenableFuture<V> Creates aListenableFuturewhich is cancelled immediately upon construction, so thatisCancelled()always returnstrue.static <V,X extends Exception>
CheckedFuture<V, X> immediateCheckedFuture(V value) Returns aCheckedFuturewhich has its value set immediately upon construction.static <V,X extends Exception>
CheckedFuture<V, X> immediateFailedCheckedFuture(X exception) Returns aCheckedFuturewhich has an exception set immediately upon construction.static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable) Returns aListenableFuturewhich has an exception set immediately upon construction.static <V> ListenableFuture<V> immediateFuture(V value) Creates aListenableFuturewhich has its value set immediately upon construction.static <T> ImmutableList<ListenableFuture<T>> inCompletionOrder(Iterable<? extends ListenableFuture<? extends T>> futures) Returns a list of delegate futures that correspond to the futures received in the order that they complete.static <I,O> Future <O> lazyTransform(Future<I> input, Function<? super I, ? extends O> function) Liketransform(ListenableFuture, Function)except that the transformationfunctionis invoked on each call toget()on the returned future.static <V,X extends Exception>
CheckedFuture<V, X> makeChecked(ListenableFuture<V> future, Function<? super Exception, X> mapper) Creates aCheckedFutureout of a normalListenableFutureand aFunctionthat maps fromExceptioninstances into the appropriate checked type.static <V> ListenableFuture<V> nonCancellationPropagating(ListenableFuture<V> future) Creates a newListenableFuturewhose result is set from the supplied future when it completes.static <V> ListenableFuture<List<V>> successfulAsList(ListenableFuture<? extends V>... futures) Creates a newListenableFuturewhose value is a list containing the values of all its successful input futures.static <V> ListenableFuture<List<V>> successfulAsList(Iterable<? extends ListenableFuture<? extends V>> futures) Creates a newListenableFuturewhose value is a list containing the values of all its successful input futures.static <I,O> ListenableFuture <O> transform(ListenableFuture<I> input, Function<? super I, ? extends O> function) Returns a newFuturewhose result is derived from the result of the givenFuture.static <I,O> ListenableFuture <O> transform(ListenableFuture<I> input, Function<? super I, ? extends O> function, Executor executor) Returns a newFuturewhose result is derived from the result of the givenFuture.static <I,O> ListenableFuture <O> transformAsync(ListenableFuture<I> input, AsyncFunction<? super I, ? extends O> function) Returns a newFuturewhose result is asynchronously derived from the result of the givenFuture.static <I,O> ListenableFuture <O> transformAsync(ListenableFuture<I> input, AsyncFunction<? super I, ? extends O> function, Executor executor) Returns a newFuturewhose result is asynchronously derived from the result of the givenFuture.static <V> Futures.FutureCombiner<V> whenAllComplete(ListenableFuture<? extends V>... futures) Creates aFutures.FutureCombinerthat processes the completed futures whether or not they're successful.static <V> Futures.FutureCombiner<V> whenAllComplete(Iterable<? extends ListenableFuture<? extends V>> futures) Creates aFutures.FutureCombinerthat processes the completed futures whether or not they're successful.static <V> Futures.FutureCombiner<V> whenAllSucceed(ListenableFuture<? extends V>... futures) Creates aFutures.FutureCombinerrequiring that all passed in futures are successful.static <V> Futures.FutureCombiner<V> whenAllSucceed(Iterable<? extends ListenableFuture<? extends V>> futures) Creates aFutures.FutureCombinerrequiring that all passed in futures are successful.static <V> ListenableFuture<V> withTimeout(ListenableFuture<V> delegate, long time, TimeUnit unit, ScheduledExecutorService scheduledExecutor) Returns a future that delegates to another but will finish early (via aTimeoutExceptionwrapped in anExecutionException) if the specified duration expires.
-
Method Details
-
makeChecked
@GwtIncompatible public static <V,X extends Exception> CheckedFuture<V,X> makeChecked(ListenableFuture<V> future, Function<? super Exception, X> mapper) Creates aCheckedFutureout of a normalListenableFutureand aFunctionthat maps fromExceptioninstances into the appropriate checked type.Warning: We recommend against using
CheckedFuturein new projects.CheckedFutureis difficult to build libraries atop.CheckedFutureports of methods liketransformAsync(com.google.common.util.concurrent.ListenableFuture<I>, com.google.common.util.concurrent.AsyncFunction<? super I, ? extends O>)have historically had bugs, and some of these bugs are necessary, unavoidable consequences of theCheckedFutureAPI. Additionally,CheckedFutureencourages users to take exceptions from one thread and rethrow them in another, producing confusing stack traces.The given mapping function will be applied to an
InterruptedException, aCancellationException, or anExecutionException. SeeFuture.get()for details on the exceptions thrown.- Since:
- 9.0 (source-compatible since 1.0)
-
immediateFuture
Creates aListenableFuturewhich has its value set immediately upon construction. The getters just return the value. ThisFuturecan't be canceled or timed out and itsisDone()method always returnstrue. -
immediateCheckedFuture
@GwtIncompatible public static <V,X extends Exception> CheckedFuture<V,X> immediateCheckedFuture(@Nullable V value) Returns aCheckedFuturewhich has its value set immediately upon construction.The returned
Futurecan't be cancelled, and itsisDone()method always returnstrue. Callingget()orcheckedGet()will immediately return the provided value. -
immediateFailedFuture
Returns aListenableFuturewhich has an exception set immediately upon construction.The returned
Futurecan't be cancelled, and itsisDone()method always returnstrue. Callingget()will immediately throw the providedThrowablewrapped in anExecutionException. -
immediateCancelledFuture
Creates aListenableFuturewhich is cancelled immediately upon construction, so thatisCancelled()always returnstrue.- Since:
- 14.0
-
immediateFailedCheckedFuture
@GwtIncompatible public static <V,X extends Exception> CheckedFuture<V,X> immediateFailedCheckedFuture(X exception) Returns aCheckedFuturewhich has an exception set immediately upon construction.The returned
Futurecan't be cancelled, and itsisDone()method always returnstrue. Callingget()will immediately throw the providedExceptionwrapped in anExecutionException, and callingcheckedGet()will throw the provided exception itself. -
catching
@GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class") public static <V,X extends Throwable> ListenableFuture<V> catching(ListenableFuture<? extends V> input, Class<X> exceptionType, Function<? super X, ? extends V> fallback) Returns aFuturewhose result is taken from the given primaryinputor, if the primary input fails with the givenexceptionType, from the result provided by thefallback.Function.apply(F)is not invoked until the primary input has failed, so if the primary input succeeds, it is never invoked. If, during the invocation offallback, an exception is thrown, this exception is used as the result of the outputFuture.Usage example:
ListenableFuture<Integer> fetchCounterFuture = ...; // Falling back to a zero counter in case an exception happens when // processing the RPC to fetch counters. ListenableFuture<Integer> faultTolerantFuture = Futures.catching( fetchCounterFuture, FetchException.class, new Function<FetchException, Integer>() { public Integer apply(FetchException e) { return 0; } });This overload, which does not accept an executor, uses
directExecutor, a dangerous choice in some cases. See the discussion in theListenableFuture.addListenerdocumentation. The documentation's warnings about "lightweight listeners" refer here to the work done duringFunction.apply.- Parameters:
input- the primary inputFutureexceptionType- the exception type that triggers use offallback. The exception type is matched against the input's exception. "The input's exception" means the cause of theExecutionExceptionthrown byinput.get()or, ifget()throws a different kind of exception, that exception itself. To avoid hiding bugs and other unrecoverable errors, callers should prefer more specific types, avoidingThrowable.classin particular.fallback- theFunctionto be called ifinputfails with the expected exception type. The function's argument is the input's exception. "The input's exception" means the cause of theExecutionExceptionthrown byinput.get()or, ifget()throws a different kind of exception, that exception itself.- Since:
- 19.0
-
catching
@GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class") public static <V,X extends Throwable> ListenableFuture<V> catching(ListenableFuture<? extends V> input, Class<X> exceptionType, Function<? super X, ? extends V> fallback, Executor executor) Returns aFuturewhose result is taken from the given primaryinputor, if the primary input fails with the givenexceptionType, from the result provided by thefallback.Function.apply(F)is not invoked until the primary input has failed, so if the primary input succeeds, it is never invoked. If, during the invocation offallback, an exception is thrown, this exception is used as the result of the outputFuture.Usage example:
ListenableFuture<Integer> fetchCounterFuture = ...; // Falling back to a zero counter in case an exception happens when // processing the RPC to fetch counters. ListenableFuture<Integer> faultTolerantFuture = Futures.catching( fetchCounterFuture, FetchException.class, new Function<FetchException, Integer>() { public Integer apply(FetchException e) { return 0; } }, directExecutor());When selecting an executor, note that
directExecutoris dangerous in some cases. See the discussion in theListenableFuture.addListenerdocumentation. The documentation's warnings about "lightweight listeners" refer here to the work done duringFunction.apply.- Parameters:
input- the primary inputFutureexceptionType- the exception type that triggers use offallback. The exception type is matched against the input's exception. "The input's exception" means the cause of theExecutionExceptionthrown byinput.get()or, ifget()throws a different kind of exception, that exception itself. To avoid hiding bugs and other unrecoverable errors, callers should prefer more specific types, avoidingThrowable.classin particular.fallback- theFunctionto be called ifinputfails with the expected exception type. The function's argument is the input's exception. "The input's exception" means the cause of theExecutionExceptionthrown byinput.get()or, ifget()throws a different kind of exception, that exception itself.executor- the executor that runsfallbackifinputfails- Since:
- 19.0
-
catchingAsync
@GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class") public static <V,X extends Throwable> ListenableFuture<V> catchingAsync(ListenableFuture<? extends V> input, Class<X> exceptionType, AsyncFunction<? super X, ? extends V> fallback) Returns aFuturewhose result is taken from the given primaryinputor, if the primary input fails with the givenexceptionType, from the result provided by thefallback.AsyncFunction.apply(I)is not invoked until the primary input has failed, so if the primary input succeeds, it is never invoked. If, during the invocation offallback, an exception is thrown, this exception is used as the result of the outputFuture.Usage examples:
ListenableFuture<Integer> fetchCounterFuture = ...; // Falling back to a zero counter in case an exception happens when // processing the RPC to fetch counters. ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync( fetchCounterFuture, FetchException.class, new AsyncFunction<FetchException, Integer>() { public ListenableFuture<Integer> apply(FetchException e) { return immediateFuture(0); } });The fallback can also choose to propagate the original exception when desired:
ListenableFuture<Integer> fetchCounterFuture = ...; // Falling back to a zero counter only in case the exception was a // TimeoutException. ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync( fetchCounterFuture, FetchException.class, new AsyncFunction<FetchException, Integer>() { public ListenableFuture<Integer> apply(FetchException e) throws FetchException { if (omitDataOnFetchFailure) { return immediateFuture(0); } throw e; } });This overload, which does not accept an executor, uses
directExecutor, a dangerous choice in some cases. See the discussion in theListenableFuture.addListenerdocumentation. The documentation's warnings about "lightweight listeners" refer here to the work done duringAsyncFunction.apply, not to any work done to complete the returnedFuture.- Parameters:
input- the primary inputFutureexceptionType- the exception type that triggers use offallback. The exception type is matched against the input's exception. "The input's exception" means the cause of theExecutionExceptionthrown byinput.get()or, ifget()throws a different kind of exception, that exception itself. To avoid hiding bugs and other unrecoverable errors, callers should prefer more specific types, avoidingThrowable.classin particular.fallback- theAsyncFunctionto be called ifinputfails with the expected exception type. The function's argument is the input's exception. "The input's exception" means the cause of theExecutionExceptionthrown byinput.get()or, ifget()throws a different kind of exception, that exception itself.- Since:
- 19.0 (similar functionality in 14.0 as
withFallback)
-
catchingAsync
@GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class") public static <V,X extends Throwable> ListenableFuture<V> catchingAsync(ListenableFuture<? extends V> input, Class<X> exceptionType, AsyncFunction<? super X, ? extends V> fallback, Executor executor) Returns aFuturewhose result is taken from the given primaryinputor, if the primary input fails with the givenexceptionType, from the result provided by thefallback.AsyncFunction.apply(I)is not invoked until the primary input has failed, so if the primary input succeeds, it is never invoked. If, during the invocation offallback, an exception is thrown, this exception is used as the result of the outputFuture.Usage examples:
ListenableFuture<Integer> fetchCounterFuture = ...; // Falling back to a zero counter in case an exception happens when // processing the RPC to fetch counters. ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync( fetchCounterFuture, FetchException.class, new AsyncFunction<FetchException, Integer>() { public ListenableFuture<Integer> apply(FetchException e) { return immediateFuture(0); } }, directExecutor());The fallback can also choose to propagate the original exception when desired:
ListenableFuture<Integer> fetchCounterFuture = ...; // Falling back to a zero counter only in case the exception was a // TimeoutException. ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync( fetchCounterFuture, FetchException.class, new AsyncFunction<FetchException, Integer>() { public ListenableFuture<Integer> apply(FetchException e) throws FetchException { if (omitDataOnFetchFailure) { return immediateFuture(0); } throw e; } }, directExecutor());When selecting an executor, note that
directExecutoris dangerous in some cases. See the discussion in theListenableFuture.addListenerdocumentation. The documentation's warnings about "lightweight listeners" refer here to the work done duringAsyncFunction.apply, not to any work done to complete the returnedFuture.- Parameters:
input- the primary inputFutureexceptionType- the exception type that triggers use offallback. The exception type is matched against the input's exception. "The input's exception" means the cause of theExecutionExceptionthrown byinput.get()or, ifget()throws a different kind of exception, that exception itself. To avoid hiding bugs and other unrecoverable errors, callers should prefer more specific types, avoidingThrowable.classin particular.fallback- theAsyncFunctionto be called ifinputfails with the expected exception type. The function's argument is the input's exception. "The input's exception" means the cause of theExecutionExceptionthrown byinput.get()or, ifget()throws a different kind of exception, that exception itself.executor- the executor that runsfallbackifinputfails- Since:
- 19.0 (similar functionality in 14.0 as
withFallback)
-
withTimeout
@GwtIncompatible public static <V> ListenableFuture<V> withTimeout(ListenableFuture<V> delegate, long time, TimeUnit unit, ScheduledExecutorService scheduledExecutor) Returns a future that delegates to another but will finish early (via aTimeoutExceptionwrapped in anExecutionException) if the specified duration expires.The delegate future is interrupted and cancelled if it times out.
- Parameters:
delegate- The future to delegate to.time- when to timeout the futureunit- the time unit of the time parameterscheduledExecutor- The executor service to enforce the timeout.- Since:
- 19.0
-
transformAsync
public static <I,O> ListenableFuture<O> transformAsync(ListenableFuture<I> input, AsyncFunction<? super I, ? extends O> function) Returns a newFuturewhose result is asynchronously derived from the result of the givenFuture. If the givenFuturefails, the returnedFuturefails with the same exception (and the function is not invoked).More precisely, the returned
Futuretakes its result from aFutureproduced by applying the givenAsyncFunctionto the result of the originalFuture. Example usage:ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query); AsyncFunction<RowKey, QueryResult> queryFunction = new AsyncFunction<RowKey, QueryResult>() { public ListenableFuture<QueryResult> apply(RowKey rowKey) { return dataService.read(rowKey); } }; ListenableFuture<QueryResult> queryFuture = transformAsync(rowKeyFuture, queryFunction);This overload, which does not accept an executor, uses
directExecutor, a dangerous choice in some cases. See the discussion in theListenableFuture.addListenerdocumentation. The documentation's warnings about "lightweight listeners" refer here to the work done duringAsyncFunction.apply, not to any work done to complete the returnedFuture.The returned
Futureattempts to keep its cancellation state in sync with that of the input future and that of the future returned by the function. That is, if the returnedFutureis cancelled, it will attempt to cancel the other two, and if either of the other two is cancelled, the returnedFuturewill receive a callback in which it will attempt to cancel itself.- Parameters:
input- The future to transformfunction- A function to transform the result of the input future to the result of the output future- Returns:
- A future that holds result of the function (if the input succeeded) or the original input's failure (if not)
- Since:
- 19.0 (in 11.0 as
transform)
-
transformAsync
public static <I,O> ListenableFuture<O> transformAsync(ListenableFuture<I> input, AsyncFunction<? super I, ? extends O> function, Executor executor) Returns a newFuturewhose result is asynchronously derived from the result of the givenFuture. If the givenFuturefails, the returnedFuturefails with the same exception (and the function is not invoked).More precisely, the returned
Futuretakes its result from aFutureproduced by applying the givenAsyncFunctionto the result of the originalFuture. Example usage:ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query); AsyncFunction<RowKey, QueryResult> queryFunction = new AsyncFunction<RowKey, QueryResult>() { public ListenableFuture<QueryResult> apply(RowKey rowKey) { return dataService.read(rowKey); } }; ListenableFuture<QueryResult> queryFuture = transformAsync(rowKeyFuture, queryFunction, executor);When selecting an executor, note that
directExecutoris dangerous in some cases. See the discussion in theListenableFuture.addListenerdocumentation. The documentation's warnings about "lightweight listeners" refer here to the work done duringAsyncFunction.apply, not to any work done to complete the returnedFuture.The returned
Futureattempts to keep its cancellation state in sync with that of the input future and that of the future returned by the chain function. That is, if the returnedFutureis cancelled, it will attempt to cancel the other two, and if either of the other two is cancelled, the returnedFuturewill receive a callback in which it will attempt to cancel itself.- Parameters:
input- The future to transformfunction- A function to transform the result of the input future to the result of the output futureexecutor- Executor to run the function in.- Returns:
- A future that holds result of the function (if the input succeeded) or the original input's failure (if not)
- Since:
- 19.0 (in 11.0 as
transform)
-
transform
public static <I,O> ListenableFuture<O> transform(ListenableFuture<I> input, Function<? super I, ? extends O> function) Returns a newFuturewhose result is derived from the result of the givenFuture. Ifinputfails, the returnedFuturefails with the same exception (and the function is not invoked). Example usage:ListenableFuture<QueryResult> queryFuture = ...; Function<QueryResult, List<Row>> rowsFunction = new Function<QueryResult, List<Row>>() { public List<Row> apply(QueryResult queryResult) { return queryResult.getRows(); } }; ListenableFuture<List<Row>> rowsFuture = transform(queryFuture, rowsFunction);This overload, which does not accept an executor, uses
directExecutor, a dangerous choice in some cases. See the discussion in theListenableFuture.addListenerdocumentation. The documentation's warnings about "lightweight listeners" refer here to the work done duringFunction.apply.The returned
Futureattempts to keep its cancellation state in sync with that of the input future. That is, if the returnedFutureis cancelled, it will attempt to cancel the input, and if the input is cancelled, the returnedFuturewill receive a callback in which it will attempt to cancel itself.An example use of this method is to convert a serializable object returned from an RPC into a POJO.
- Parameters:
input- The future to transformfunction- A Function to transform the results of the provided future to the results of the returned future. This will be run in the thread that notifies input it is complete.- Returns:
- A future that holds result of the transformation.
- Since:
- 9.0 (in 1.0 as
compose)
-
transform
public static <I,O> ListenableFuture<O> transform(ListenableFuture<I> input, Function<? super I, ? extends O> function, Executor executor) Returns a newFuturewhose result is derived from the result of the givenFuture. Ifinputfails, the returnedFuturefails with the same exception (and the function is not invoked). Example usage:ListenableFuture<QueryResult> queryFuture = ...; Function<QueryResult, List<Row>> rowsFunction = new Function<QueryResult, List<Row>>() { public List<Row> apply(QueryResult queryResult) { return queryResult.getRows(); } }; ListenableFuture<List<Row>> rowsFuture = transform(queryFuture, rowsFunction, executor);When selecting an executor, note that
directExecutoris dangerous in some cases. See the discussion in theListenableFuture.addListenerdocumentation. The documentation's warnings about "lightweight listeners" refer here to the work done duringFunction.apply.The returned
Futureattempts to keep its cancellation state in sync with that of the input future. That is, if the returnedFutureis cancelled, it will attempt to cancel the input, and if the input is cancelled, the returnedFuturewill receive a callback in which it will attempt to cancel itself.An example use of this method is to convert a serializable object returned from an RPC into a POJO.
- Parameters:
input- The future to transformfunction- A Function to transform the results of the provided future to the results of the returned future.executor- Executor to run the function in.- Returns:
- A future that holds result of the transformation.
- Since:
- 9.0 (in 2.0 as
compose)
-
lazyTransform
@GwtIncompatible public static <I,O> Future<O> lazyTransform(Future<I> input, Function<? super I, ? extends O> function) Liketransform(ListenableFuture, Function)except that the transformationfunctionis invoked on each call toget()on the returned future.The returned
Futurereflects the input's cancellation state directly, and any attempt to cancel the returned Future is likewise passed through to the input Future.Note that calls to timed get only apply the timeout to the execution of the underlying
Future, not to the execution of the transformation function.The primary audience of this method is callers of
transformwho don't have aListenableFutureavailable and do not mind repeated, lazy function evaluation.- Parameters:
input- The future to transformfunction- A Function to transform the results of the provided future to the results of the returned future.- Returns:
- A future that returns the result of the transformation.
- Since:
- 10.0
-
dereference
public static <V> ListenableFuture<V> dereference(ListenableFuture<? extends ListenableFuture<? extends V>> nested) Returns a newListenableFuturewhose result is the product of callingget()on theFuturenested within the givenFuture, effectively chaining the futures one after the other. Example:SettableFuture<ListenableFuture<String>> nested = SettableFuture.create(); ListenableFuture<String> dereferenced = dereference(nested);Most users will not need this method. To create a
Futurethat completes with the result of anotherFuture, create aSettableFuture, and callsetFuture(otherFuture)on it.dereferencehas the same cancellation and execution semantics astransformAsync(ListenableFuture, AsyncFunction), in that the returnedFutureattempts to keep its cancellation state in sync with both the inputFutureand the nestedFuture. The transformation is very lightweight and therefore takes place in the same thread (either the thread that calleddereference, or the thread in which the dereferenced future completes).- Parameters:
nested- The nested future to transform.- Returns:
- A future that holds result of the inner future.
- Since:
- 13.0
-
allAsList
@Beta @SafeVarargs public static <V> ListenableFuture<List<V>> allAsList(ListenableFuture<? extends V>... futures) Creates a newListenableFuturewhose value is a list containing the values of all its input futures, if all succeed. If any input fails, the returned future fails immediately.The list of results is in the same order as the input list.
Canceling this future will attempt to cancel all the component futures, and if any of the provided futures fails or is canceled, this one is, too.
- Parameters:
futures- futures to combine- Returns:
- a future that provides a list of the results of the component futures
- Since:
- 10.0
-
allAsList
@Beta public static <V> ListenableFuture<List<V>> allAsList(Iterable<? extends ListenableFuture<? extends V>> futures) Creates a newListenableFuturewhose value is a list containing the values of all its input futures, if all succeed. If any input fails, the returned future fails immediately.The list of results is in the same order as the input list.
Canceling this future will attempt to cancel all the component futures, and if any of the provided futures fails or is canceled, this one is, too.
- Parameters:
futures- futures to combine- Returns:
- a future that provides a list of the results of the component futures
- Since:
- 10.0
-
whenAllComplete
@SafeVarargs public static <V> Futures.FutureCombiner<V> whenAllComplete(ListenableFuture<? extends V>... futures) Creates aFutures.FutureCombinerthat processes the completed futures whether or not they're successful.- Since:
- 20.0
-
whenAllComplete
public static <V> Futures.FutureCombiner<V> whenAllComplete(Iterable<? extends ListenableFuture<? extends V>> futures) Creates aFutures.FutureCombinerthat processes the completed futures whether or not they're successful.- Since:
- 20.0
-
whenAllSucceed
@SafeVarargs public static <V> Futures.FutureCombiner<V> whenAllSucceed(ListenableFuture<? extends V>... futures) Creates aFutures.FutureCombinerrequiring that all passed in futures are successful.If any input fails, the returned future fails immediately.
- Since:
- 20.0
-
whenAllSucceed
public static <V> Futures.FutureCombiner<V> whenAllSucceed(Iterable<? extends ListenableFuture<? extends V>> futures) Creates aFutures.FutureCombinerrequiring that all passed in futures are successful.If any input fails, the returned future fails immediately.
- Since:
- 20.0
-
nonCancellationPropagating
Creates a newListenableFuturewhose result is set from the supplied future when it completes. Cancelling the supplied future will also cancel the returned future, but cancelling the returned future will have no effect on the supplied future.- Since:
- 15.0
-
successfulAsList
@Beta @SafeVarargs public static <V> ListenableFuture<List<V>> successfulAsList(ListenableFuture<? extends V>... futures) Creates a newListenableFuturewhose value is a list containing the values of all its successful input futures. The list of results is in the same order as the input list, and if any of the provided futures fails or is canceled, its corresponding position will containnull(which is indistinguishable from the future having a successful value ofnull).Canceling this future will attempt to cancel all the component futures.
- Parameters:
futures- futures to combine- Returns:
- a future that provides a list of the results of the component futures
- Since:
- 10.0
-
successfulAsList
@Beta public static <V> ListenableFuture<List<V>> successfulAsList(Iterable<? extends ListenableFuture<? extends V>> futures) Creates a newListenableFuturewhose value is a list containing the values of all its successful input futures. The list of results is in the same order as the input list, and if any of the provided futures fails or is canceled, its corresponding position will containnull(which is indistinguishable from the future having a successful value ofnull).Canceling this future will attempt to cancel all the component futures.
- Parameters:
futures- futures to combine- Returns:
- a future that provides a list of the results of the component futures
- Since:
- 10.0
-
inCompletionOrder
@Beta @GwtIncompatible public static <T> ImmutableList<ListenableFuture<T>> inCompletionOrder(Iterable<? extends ListenableFuture<? extends T>> futures) Returns a list of delegate futures that correspond to the futures received in the order that they complete. Delegate futures return the same value or throw the same exception as the corresponding input future returns/throws.Cancelling a delegate future has no effect on any input future, since the delegate future does not correspond to a specific input future until the appropriate number of input futures have completed. At that point, it is too late to cancel the input future. The input future's result, which cannot be stored into the cancelled delegate future, is ignored.
- Since:
- 17.0
-
addCallback
Registers separate success and failure callbacks to be run when theFuture's computation is complete or, if the computation is already complete, immediately.There is no guaranteed ordering of execution of callbacks, but any callback added through this method is guaranteed to be called once the computation is complete. Example:
ListenableFuture<QueryResult> future = ...; addCallback(future, new FutureCallback<QueryResult>() { public void onSuccess(QueryResult result) { storeInCache(result); } public void onFailure(Throwable t) { reportError(t); } });This overload, which does not accept an executor, uses
directExecutor, a dangerous choice in some cases. See the discussion in theListenableFuture.addListenerdocumentation.For a more general interface to attach a completion listener to a
Future, seeaddListener.- Parameters:
future- The future attach the callback to.callback- The callback to invoke whenfutureis completed.- Since:
- 10.0
-
addCallback
public static <V> void addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback, Executor executor) Registers separate success and failure callbacks to be run when theFuture's computation is complete or, if the computation is already complete, immediately.The callback is run in
executor. There is no guaranteed ordering of execution of callbacks, but any callback added through this method is guaranteed to be called once the computation is complete. Example:ListenableFuture<QueryResult> future = ...; Executor e = ... addCallback(future, new FutureCallback<QueryResult>() { public void onSuccess(QueryResult result) { storeInCache(result); } public void onFailure(Throwable t) { reportError(t); } }, e);When selecting an executor, note that
directExecutoris dangerous in some cases. See the discussion in theListenableFuture.addListenerdocumentation.For a more general interface to attach a completion listener to a
Future, seeaddListener.- Parameters:
future- The future attach the callback to.callback- The callback to invoke whenfutureis completed.executor- The executor to runcallbackwhen the future completes.- Since:
- 10.0
-
getDone
Returns the result of the inputFuture, which must have already completed.The benefits of this method are twofold. First, the name "getDone" suggests to readers that the
Futureis already done. Second, if buggy code callsgetDoneon aFuturethat is still pending, the program will throw instead of block. This can be important for APIs likewhenAllComplete(...).call(...), where it is easy to use a new input from thecallimplementation but forget to add it to the arguments ofwhenAllComplete.If you are looking for a method to determine whether a given
Futureis done, use the instance methodFuture.isDone().- Throws:
ExecutionException- if theFuturefailed with an exceptionCancellationException- if theFuturewas cancelledIllegalStateException- if theFutureis not done- Since:
- 20.0
-
getChecked
@GwtIncompatible public static <V,X extends Exception> V getChecked(Future<V> future, Class<X> exceptionClass) throws X Returns the result ofFuture.get(), converting most exceptions to a new instance of the given checked exception type. This reduces boilerplate for a common use ofFuturein which it is unnecessary to programmatically distinguish between exception types or to extract other information from the exception instance.Exceptions from
Future.getare treated as follows:- Any
ExecutionExceptionhas its cause wrapped in anXif the cause is a checked exception, anUncheckedExecutionExceptionif the cause is aRuntimeException, or anExecutionErrorif the cause is anError. - Any
InterruptedExceptionis wrapped in anX(after restoring the interrupt). - Any
CancellationExceptionis propagated untouched, as is any otherRuntimeException(thoughgetimplementations are discouraged from throwing such exceptions).
The overall principle is to continue to treat every checked exception as a checked exception, every unchecked exception as an unchecked exception, and every error as an error. In addition, the cause of any
ExecutionExceptionis wrapped in order to ensure that the new stack trace matches that of the current thread.Instances of
exceptionClassare created by choosing an arbitrary public constructor that accepts zero or more arguments, all of typeStringorThrowable(preferring constructors with at least oneString) and calling the constructor via reflection. If the exception did not already have a cause, one is set by callingThrowable.initCause(Throwable)on it. If no such constructor exists, anIllegalArgumentExceptionis thrown.- Throws:
X- ifgetthrows any checked exception except for anExecutionExceptionwhose cause is not itself a checked exceptionUncheckedExecutionException- ifgetthrows anExecutionExceptionwith aRuntimeExceptionas its causeExecutionError- ifgetthrows anExecutionExceptionwith anErroras its causeCancellationException- ifgetthrows aCancellationExceptionIllegalArgumentException- ifexceptionClassextendsRuntimeExceptionor does not have a suitable constructor- Since:
- 19.0 (in 10.0 as
get)
- Any
-
getChecked
@GwtIncompatible public static <V,X extends Exception> V getChecked(Future<V> future, Class<X> exceptionClass, long timeout, TimeUnit unit) throws X Returns the result ofFuture.get(long, TimeUnit), converting most exceptions to a new instance of the given checked exception type. This reduces boilerplate for a common use ofFuturein which it is unnecessary to programmatically distinguish between exception types or to extract other information from the exception instance.Exceptions from
Future.getare treated as follows:- Any
ExecutionExceptionhas its cause wrapped in anXif the cause is a checked exception, anUncheckedExecutionExceptionif the cause is aRuntimeException, or anExecutionErrorif the cause is anError. - Any
InterruptedExceptionis wrapped in anX(after restoring the interrupt). - Any
TimeoutExceptionis wrapped in anX. - Any
CancellationExceptionis propagated untouched, as is any otherRuntimeException(thoughgetimplementations are discouraged from throwing such exceptions).
The overall principle is to continue to treat every checked exception as a checked exception, every unchecked exception as an unchecked exception, and every error as an error. In addition, the cause of any
ExecutionExceptionis wrapped in order to ensure that the new stack trace matches that of the current thread.Instances of
exceptionClassare created by choosing an arbitrary public constructor that accepts zero or more arguments, all of typeStringorThrowable(preferring constructors with at least oneString) and calling the constructor via reflection. If the exception did not already have a cause, one is set by callingThrowable.initCause(Throwable)on it. If no such constructor exists, anIllegalArgumentExceptionis thrown.- Throws:
X- ifgetthrows any checked exception except for anExecutionExceptionwhose cause is not itself a checked exceptionUncheckedExecutionException- ifgetthrows anExecutionExceptionwith aRuntimeExceptionas its causeExecutionError- ifgetthrows anExecutionExceptionwith anErroras its causeCancellationException- ifgetthrows aCancellationExceptionIllegalArgumentException- ifexceptionClassextendsRuntimeExceptionor does not have a suitable constructor- Since:
- 19.0 (in 10.0 as
getand with different parameter order)
- Any
-
getUnchecked
Returns the result of callingFuture.get()uninterruptibly on a task known not to throw a checked exception. This makesFuturemore suitable for lightweight, fast-running tasks that, barring bugs in the code, will not fail. This gives it exception-handling behavior similar to that ofForkJoinTask.join.Exceptions from
Future.getare treated as follows:- Any
ExecutionExceptionhas its cause wrapped in anUncheckedExecutionException(if the cause is anException) orExecutionError(if the cause is anError). - Any
InterruptedExceptioncauses a retry of thegetcall. The interrupt is restored beforegetUncheckedreturns. - Any
CancellationExceptionis propagated untouched. So is any otherRuntimeException(getimplementations are discouraged from throwing such exceptions).
The overall principle is to eliminate all checked exceptions: to loop to avoid
InterruptedException, to pass throughCancellationException, and to wrap any exception from the underlying computation in anUncheckedExecutionExceptionorExecutionError.For an uninterruptible
getthat preserves other exceptions, seeUninterruptibles.getUninterruptibly(Future).- Throws:
UncheckedExecutionException- ifgetthrows anExecutionExceptionwith anExceptionas its causeExecutionError- ifgetthrows anExecutionExceptionwith anErroras its causeCancellationException- ifgetthrows aCancellationException- Since:
- 10.0
- Any
-