Class Futures
- java.lang.Object
-
- com.google.common.util.concurrent.Futures
-
@GwtCompatible(emulated=true) public final class Futures extends java.lang.Object
Static utility methods pertaining to theFuture
interface.Many of these methods use the
ListenableFuture
API; consult the Guava User Guide article onListenableFuture
.The main purpose of
ListenableFuture
is to help you chain together a graph of asynchronous operations. You can chain them together manually with calls to methods likeFutures.transform
, but you will often find it easier to use a framework. Frameworks automate the process, often adding features like monitoring, debugging, and cancellation. Examples of frameworks include:If you do chain your operations manually, you may want to use
FluentFuture
.- Since:
- 1.0
- Author:
- Kevin Bourrillion, Nishant Thakkar, Sven Mawson
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
Futures.FutureCombiner<V extends @Nullable java.lang.Object>
A helper to create a newListenableFuture
whose result is generated from a combination of input futures.
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static <V extends @Nullable java.lang.Object>
voidaddCallback(ListenableFuture<V> future, FutureCallback<? super V> callback, java.util.concurrent.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 extends @Nullable java.lang.Object>
ListenableFuture<java.util.List<V>>allAsList(ListenableFuture<? extends V>... futures)
Creates a newListenableFuture
whose value is a list containing the values of all its input futures, if all succeed.static <V extends @Nullable java.lang.Object>
ListenableFuture<java.util.List<V>>allAsList(java.lang.Iterable<? extends ListenableFuture<? extends V>> futures)
Creates a newListenableFuture
whose value is a list containing the values of all its input futures, if all succeed.static <V extends @Nullable java.lang.Object,X extends java.lang.Throwable>
ListenableFuture<V>catching(ListenableFuture<? extends V> input, java.lang.Class<X> exceptionType, Function<? super X,? extends V> fallback, java.util.concurrent.Executor executor)
Returns aFuture
whose result is taken from the given primaryinput
or, if the primary input fails with the givenexceptionType
, from the result provided by thefallback
.static <V extends @Nullable java.lang.Object,X extends java.lang.Throwable>
ListenableFuture<V>catchingAsync(ListenableFuture<? extends V> input, java.lang.Class<X> exceptionType, AsyncFunction<? super X,? extends V> fallback, java.util.concurrent.Executor executor)
Returns aFuture
whose result is taken from the given primaryinput
or, if the primary input fails with the givenexceptionType
, from the result provided by thefallback
.static <V extends @Nullable java.lang.Object,X extends java.lang.Exception>
VgetChecked(java.util.concurrent.Future<V> future, java.lang.Class<X> exceptionClass)
Returns the result ofFuture.get()
, converting most exceptions to a new instance of the given checked exception type.static <V extends @Nullable java.lang.Object,X extends java.lang.Exception>
VgetChecked(java.util.concurrent.Future<V> future, java.lang.Class<X> exceptionClass, long timeout, java.util.concurrent.TimeUnit unit)
Returns the result ofFuture.get(long, TimeUnit)
, converting most exceptions to a new instance of the given checked exception type.static <V extends @Nullable java.lang.Object,X extends java.lang.Exception>
VgetChecked(java.util.concurrent.Future<V> future, java.lang.Class<X> exceptionClass, java.time.Duration timeout)
Returns the result ofFuture.get(long, TimeUnit)
, converting most exceptions to a new instance of the given checked exception type.static <V extends @Nullable java.lang.Object>
VgetDone(java.util.concurrent.Future<V> future)
Returns the result of the inputFuture
, which must have already completed.static <V extends @Nullable java.lang.Object>
VgetUnchecked(java.util.concurrent.Future<V> future)
Returns the result of callingFuture.get()
uninterruptibly on a task known not to throw a checked exception.static <V extends @Nullable java.lang.Object>
ListenableFuture<V>immediateCancelledFuture()
Creates aListenableFuture
which is cancelled immediately upon construction, so thatisCancelled()
always returnstrue
.static <V extends @Nullable java.lang.Object>
ListenableFuture<V>immediateFailedFuture(java.lang.Throwable throwable)
Returns aListenableFuture
which has an exception set immediately upon construction.static <V extends @Nullable java.lang.Object>
ListenableFuture<V>immediateFuture(V value)
Creates aListenableFuture
which has its value set immediately upon construction.static ListenableFuture<@Nullable java.lang.Void>
immediateVoidFuture()
Returns a successfulListenableFuture<Void>
.static <T extends @Nullable java.lang.Object>
ImmutableList<ListenableFuture<T>>inCompletionOrder(java.lang.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 extends @Nullable java.lang.Object,O extends @Nullable java.lang.Object>
java.util.concurrent.Future<O>lazyTransform(java.util.concurrent.Future<I> input, Function<? super I,? extends O> function)
Liketransform(ListenableFuture, Function, Executor)
except that the transformationfunction
is invoked on each call toget()
on the returned future.static <V extends @Nullable java.lang.Object>
ListenableFuture<V>nonCancellationPropagating(ListenableFuture<V> future)
Returns aListenableFuture
whose result is set from the supplied future when it completes.static <O extends @Nullable java.lang.Object>
ListenableFuture<O>scheduleAsync(AsyncCallable<O> callable, long delay, java.util.concurrent.TimeUnit timeUnit, java.util.concurrent.ScheduledExecutorService executorService)
Schedulescallable
on the specifiedexecutor
, returning aFuture
.static <O extends @Nullable java.lang.Object>
ListenableFuture<O>scheduleAsync(AsyncCallable<O> callable, java.time.Duration delay, java.util.concurrent.ScheduledExecutorService executorService)
Schedulescallable
on the specifiedexecutor
, returning aFuture
.static ListenableFuture<@Nullable java.lang.Void>
submit(java.lang.Runnable runnable, java.util.concurrent.Executor executor)
Executesrunnable
on the specifiedexecutor
, returning aFuture
that will complete after execution.static <O extends @Nullable java.lang.Object>
ListenableFuture<O>submit(java.util.concurrent.Callable<O> callable, java.util.concurrent.Executor executor)
Executescallable
on the specifiedexecutor
, returning aFuture
.static <O extends @Nullable java.lang.Object>
ListenableFuture<O>submitAsync(AsyncCallable<O> callable, java.util.concurrent.Executor executor)
Executescallable
on the specifiedexecutor
, returning aFuture
.static <V extends @Nullable java.lang.Object>
ListenableFuture<java.util.List<@Nullable V>>successfulAsList(ListenableFuture<? extends V>... futures)
Creates a newListenableFuture
whose value is a list containing the values of all its successful input futures.static <V extends @Nullable java.lang.Object>
ListenableFuture<java.util.List<@Nullable V>>successfulAsList(java.lang.Iterable<? extends ListenableFuture<? extends V>> futures)
Creates a newListenableFuture
whose value is a list containing the values of all its successful input futures.static <I extends @Nullable java.lang.Object,O extends @Nullable java.lang.Object>
ListenableFuture<O>transform(ListenableFuture<I> input, Function<? super I,? extends O> function, java.util.concurrent.Executor executor)
Returns a newFuture
whose result is derived from the result of the givenFuture
.static <I extends @Nullable java.lang.Object,O extends @Nullable java.lang.Object>
ListenableFuture<O>transformAsync(ListenableFuture<I> input, AsyncFunction<? super I,? extends O> function, java.util.concurrent.Executor executor)
Returns a newFuture
whose result is asynchronously derived from the result of the givenFuture
.static <V extends @Nullable java.lang.Object>
Futures.FutureCombiner<V>whenAllComplete(ListenableFuture<? extends V>... futures)
Creates aFutures.FutureCombiner
that processes the completed futures whether or not they're successful.static <V extends @Nullable java.lang.Object>
Futures.FutureCombiner<V>whenAllComplete(java.lang.Iterable<? extends ListenableFuture<? extends V>> futures)
Creates aFutures.FutureCombiner
that processes the completed futures whether or not they're successful.static <V extends @Nullable java.lang.Object>
Futures.FutureCombiner<V>whenAllSucceed(ListenableFuture<? extends V>... futures)
Creates aFutures.FutureCombiner
requiring that all passed in futures are successful.static <V extends @Nullable java.lang.Object>
Futures.FutureCombiner<V>whenAllSucceed(java.lang.Iterable<? extends ListenableFuture<? extends V>> futures)
Creates aFutures.FutureCombiner
requiring that all passed in futures are successful.static <V extends @Nullable java.lang.Object>
ListenableFuture<V>withTimeout(ListenableFuture<V> delegate, long time, java.util.concurrent.TimeUnit unit, java.util.concurrent.ScheduledExecutorService scheduledExecutor)
Returns a future that delegates to another but will finish early (via aTimeoutException
wrapped in anExecutionException
) if the specified duration expires.static <V extends @Nullable java.lang.Object>
ListenableFuture<V>withTimeout(ListenableFuture<V> delegate, java.time.Duration time, java.util.concurrent.ScheduledExecutorService scheduledExecutor)
Returns a future that delegates to another but will finish early (via aTimeoutException
wrapped in anExecutionException
) if the specified duration expires.
-
-
-
Method Detail
-
immediateFuture
public static <V extends @Nullable java.lang.Object> ListenableFuture<V> immediateFuture(V value)
Creates aListenableFuture
which has its value set immediately upon construction. The getters just return the value. ThisFuture
can't be canceled or timed out and itsisDone()
method always returnstrue
.
-
immediateVoidFuture
public static ListenableFuture<@Nullable java.lang.Void> immediateVoidFuture()
Returns a successfulListenableFuture<Void>
. This method is equivalent toimmediateFuture(null)
except that it is restricted to produce futures of typeVoid
.- Since:
- 29.0
-
immediateFailedFuture
public static <V extends @Nullable java.lang.Object> ListenableFuture<V> immediateFailedFuture(java.lang.Throwable throwable)
Returns aListenableFuture
which has an exception set immediately upon construction.The returned
Future
can't be cancelled, and itsisDone()
method always returnstrue
. Callingget()
will immediately throw the providedThrowable
wrapped in anExecutionException
.
-
immediateCancelledFuture
public static <V extends @Nullable java.lang.Object> ListenableFuture<V> immediateCancelledFuture()
Creates aListenableFuture
which is cancelled immediately upon construction, so thatisCancelled()
always returnstrue
.- Since:
- 14.0
-
submit
public static <O extends @Nullable java.lang.Object> ListenableFuture<O> submit(java.util.concurrent.Callable<O> callable, java.util.concurrent.Executor executor)
Executescallable
on the specifiedexecutor
, returning aFuture
.- Throws:
java.util.concurrent.RejectedExecutionException
- if the task cannot be scheduled for execution- Since:
- 28.2
-
submit
public static ListenableFuture<@Nullable java.lang.Void> submit(java.lang.Runnable runnable, java.util.concurrent.Executor executor)
Executesrunnable
on the specifiedexecutor
, returning aFuture
that will complete after execution.- Throws:
java.util.concurrent.RejectedExecutionException
- if the task cannot be scheduled for execution- Since:
- 28.2
-
submitAsync
public static <O extends @Nullable java.lang.Object> ListenableFuture<O> submitAsync(AsyncCallable<O> callable, java.util.concurrent.Executor executor)
Executescallable
on the specifiedexecutor
, returning aFuture
.- Throws:
java.util.concurrent.RejectedExecutionException
- if the task cannot be scheduled for execution- Since:
- 23.0
-
scheduleAsync
@GwtIncompatible public static <O extends @Nullable java.lang.Object> ListenableFuture<O> scheduleAsync(AsyncCallable<O> callable, java.time.Duration delay, java.util.concurrent.ScheduledExecutorService executorService)
Schedulescallable
on the specifiedexecutor
, returning aFuture
.- Throws:
java.util.concurrent.RejectedExecutionException
- if the task cannot be scheduled for execution- Since:
- 28.0
-
scheduleAsync
@GwtIncompatible public static <O extends @Nullable java.lang.Object> ListenableFuture<O> scheduleAsync(AsyncCallable<O> callable, long delay, java.util.concurrent.TimeUnit timeUnit, java.util.concurrent.ScheduledExecutorService executorService)
Schedulescallable
on the specifiedexecutor
, returning aFuture
.- Throws:
java.util.concurrent.RejectedExecutionException
- if the task cannot be scheduled for execution- Since:
- 23.0
-
catching
@GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class") public static <V extends @Nullable java.lang.Object,X extends java.lang.Throwable> ListenableFuture<V> catching(ListenableFuture<? extends V> input, java.lang.Class<X> exceptionType, Function<? super X,? extends V> fallback, java.util.concurrent.Executor executor)
Returns aFuture
whose result is taken from the given primaryinput
or, 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, x -> 0, directExecutor());
When selecting an executor, note that
directExecutor
is dangerous in some cases. See the warnings theMoreExecutors.directExecutor()
documentation.- Parameters:
input
- the primary inputFuture
exceptionType
- 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 theExecutionException
thrown 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.class
in particular.fallback
- theFunction
to be called ifinput
fails with the expected exception type. The function's argument is the input's exception. "The input's exception" means the cause of theExecutionException
thrown byinput.get()
or, ifget()
throws a different kind of exception, that exception itself.executor
- the executor that runsfallback
ifinput
fails- Since:
- 19.0
-
catchingAsync
@GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class") public static <V extends @Nullable java.lang.Object,X extends java.lang.Throwable> ListenableFuture<V> catchingAsync(ListenableFuture<? extends V> input, java.lang.Class<X> exceptionType, AsyncFunction<? super X,? extends V> fallback, java.util.concurrent.Executor executor)
Returns aFuture
whose result is taken from the given primaryinput
or, 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, x -> 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, e -> { if (omitDataOnFetchFailure) { return immediateFuture(0); } throw e; }, directExecutor());
When selecting an executor, note that
directExecutor
is dangerous in some cases. See the warnings theMoreExecutors.directExecutor()
documentation.- Parameters:
input
- the primary inputFuture
exceptionType
- 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 theExecutionException
thrown 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.class
in particular.fallback
- theAsyncFunction
to be called ifinput
fails with the expected exception type. The function's argument is the input's exception. "The input's exception" means the cause of theExecutionException
thrown byinput.get()
or, ifget()
throws a different kind of exception, that exception itself.executor
- the executor that runsfallback
ifinput
fails- Since:
- 19.0 (similar functionality in 14.0 as
withFallback
)
-
withTimeout
@GwtIncompatible public static <V extends @Nullable java.lang.Object> ListenableFuture<V> withTimeout(ListenableFuture<V> delegate, java.time.Duration time, java.util.concurrent.ScheduledExecutorService scheduledExecutor)
Returns a future that delegates to another but will finish early (via aTimeoutException
wrapped 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 time out the futurescheduledExecutor
- The executor service to enforce the timeout.- Since:
- 28.0
-
withTimeout
@GwtIncompatible public static <V extends @Nullable java.lang.Object> ListenableFuture<V> withTimeout(ListenableFuture<V> delegate, long time, java.util.concurrent.TimeUnit unit, java.util.concurrent.ScheduledExecutorService scheduledExecutor)
Returns a future that delegates to another but will finish early (via aTimeoutException
wrapped 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 time out the futureunit
- the time unit of the time parameterscheduledExecutor
- The executor service to enforce the timeout.- Since:
- 19.0
-
transformAsync
public static <I extends @Nullable java.lang.Object,O extends @Nullable java.lang.Object> ListenableFuture<O> transformAsync(ListenableFuture<I> input, AsyncFunction<? super I,? extends O> function, java.util.concurrent.Executor executor)
Returns a newFuture
whose result is asynchronously derived from the result of the givenFuture
. If the givenFuture
fails, the returnedFuture
fails with the same exception (and the function is not invoked).More precisely, the returned
Future
takes its result from aFuture
produced by applying the givenAsyncFunction
to the result of the originalFuture
. Example usage:ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query); ListenableFuture<QueryResult> queryFuture = transformAsync(rowKeyFuture, dataService::readFuture, executor);
When selecting an executor, note that
directExecutor
is dangerous in some cases. See the warnings theMoreExecutors.directExecutor()
documentation.The returned
Future
attempts 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 returnedFuture
is cancelled, it will attempt to cancel the other two, and if either of the other two is cancelled, the returnedFuture
will 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 extends @Nullable java.lang.Object,O extends @Nullable java.lang.Object> ListenableFuture<O> transform(ListenableFuture<I> input, Function<? super I,? extends O> function, java.util.concurrent.Executor executor)
Returns a newFuture
whose result is derived from the result of the givenFuture
. Ifinput
fails, the returnedFuture
fails with the same exception (and the function is not invoked). Example usage:ListenableFuture<QueryResult> queryFuture = ...; ListenableFuture<List<Row>> rowsFuture = transform(queryFuture, QueryResult::getRows, executor);
When selecting an executor, note that
directExecutor
is dangerous in some cases. See the warnings theMoreExecutors.directExecutor()
documentation.The returned
Future
attempts to keep its cancellation state in sync with that of the input future. That is, if the returnedFuture
is cancelled, it will attempt to cancel the input, and if the input is cancelled, the returnedFuture
will 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 extends @Nullable java.lang.Object,O extends @Nullable java.lang.Object> java.util.concurrent.Future<O> lazyTransform(java.util.concurrent.Future<I> input, Function<? super I,? extends O> function)
Liketransform(ListenableFuture, Function, Executor)
except that the transformationfunction
is invoked on each call toget()
on the returned future.The returned
Future
reflects 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
transform
who don't have aListenableFuture
available 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
-
allAsList
@SafeVarargs public static <V extends @Nullable java.lang.Object> ListenableFuture<java.util.List<V>> allAsList(ListenableFuture<? extends V>... futures)
Creates a newListenableFuture
whose value is a list containing the values of all its input futures, if all succeed.The list of results is in the same order as the input list.
This differs from
successfulAsList(ListenableFuture[])
in that it will return a failed future if any of the items fails.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
public static <V extends @Nullable java.lang.Object> ListenableFuture<java.util.List<V>> allAsList(java.lang.Iterable<? extends ListenableFuture<? extends V>> futures)
Creates a newListenableFuture
whose value is a list containing the values of all its input futures, if all succeed.The list of results is in the same order as the input list.
This differs from
successfulAsList(Iterable)
in that it will return a failed future if any of the items fails.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 extends @Nullable java.lang.Object> Futures.FutureCombiner<V> whenAllComplete(ListenableFuture<? extends V>... futures)
Creates aFutures.FutureCombiner
that processes the completed futures whether or not they're successful.Any failures from the input futures will not be propagated to the returned future.
- Since:
- 20.0
-
whenAllComplete
public static <V extends @Nullable java.lang.Object> Futures.FutureCombiner<V> whenAllComplete(java.lang.Iterable<? extends ListenableFuture<? extends V>> futures)
Creates aFutures.FutureCombiner
that processes the completed futures whether or not they're successful.Any failures from the input futures will not be propagated to the returned future.
- Since:
- 20.0
-
whenAllSucceed
@SafeVarargs public static <V extends @Nullable java.lang.Object> Futures.FutureCombiner<V> whenAllSucceed(ListenableFuture<? extends V>... futures)
Creates aFutures.FutureCombiner
requiring that all passed in futures are successful.If any input fails, the returned future fails immediately.
- Since:
- 20.0
-
whenAllSucceed
public static <V extends @Nullable java.lang.Object> Futures.FutureCombiner<V> whenAllSucceed(java.lang.Iterable<? extends ListenableFuture<? extends V>> futures)
Creates aFutures.FutureCombiner
requiring that all passed in futures are successful.If any input fails, the returned future fails immediately.
- Since:
- 20.0
-
nonCancellationPropagating
public static <V extends @Nullable java.lang.Object> ListenableFuture<V> nonCancellationPropagating(ListenableFuture<V> future)
Returns aListenableFuture
whose 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
@SafeVarargs public static <V extends @Nullable java.lang.Object> ListenableFuture<java.util.List<@Nullable V>> successfulAsList(ListenableFuture<? extends V>... futures)
Creates a newListenableFuture
whose 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
).The list of results is in the same order as the input list.
This differs from
allAsList(ListenableFuture[])
in that it's tolerant of failed futures for any of the items, representing them asnull
in the result list.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
public static <V extends @Nullable java.lang.Object> ListenableFuture<java.util.List<@Nullable V>> successfulAsList(java.lang.Iterable<? extends ListenableFuture<? extends V>> futures)
Creates a newListenableFuture
whose 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
).The list of results is in the same order as the input list.
This differs from
allAsList(Iterable)
in that it's tolerant of failed futures for any of the items, representing them asnull
in the result list.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
public static <T extends @Nullable java.lang.Object> ImmutableList<ListenableFuture<T>> inCompletionOrder(java.lang.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."In the order that they complete" means, for practical purposes, about what you would expect, but there are some subtleties. First, we do guarantee that, if the output future at index n is done, the output future at index n-1 is also done. (But as usual with futures, some listeners for future n may complete before some for future n-1.) However, it is possible, if one input completes with result X and another later with result Y, for Y to come before X in the output future list. (Such races are impossible to solve without global synchronization of all future completions. And they should have little practical impact.)
Cancelling a delegate future propagates to input futures once all the delegates complete, either from cancellation or because an input future has completed. If N futures are passed in, and M delegates are cancelled, the remaining M input futures will be cancelled once N - M of the input futures complete. If all the delegates are cancelled, all the input futures will be too.
- Since:
- 17.0
-
addCallback
public static <V extends @Nullable java.lang.Object> void addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback, java.util.concurrent.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 on
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.Exceptions thrown by a
callback
will be propagated up to the executor. Any exception thrown duringExecutor.execute
(e.g., aRejectedExecutionException
or an exception thrown by direct execution) will be caught and logged.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
directExecutor
is dangerous in some cases. See the warnings theMoreExecutors.directExecutor()
documentation.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 whenfuture
is completed.executor
- The executor to runcallback
when the future completes.- Since:
- 10.0
-
getDone
@CanIgnoreReturnValue public static <V extends @Nullable java.lang.Object> V getDone(java.util.concurrent.Future<V> future) throws java.util.concurrent.ExecutionException
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
Future
is already done. Second, if buggy code callsgetDone
on aFuture
that 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 thecall
implementation but forget to add it to the arguments ofwhenAllComplete
.If you are looking for a method to determine whether a given
Future
is done, use the instance methodFuture.isDone()
.- Throws:
java.util.concurrent.ExecutionException
- if theFuture
failed with an exceptionjava.util.concurrent.CancellationException
- if theFuture
was cancelledjava.lang.IllegalStateException
- if theFuture
is not done- Since:
- 20.0
-
getChecked
@CanIgnoreReturnValue @GwtIncompatible public static <V extends @Nullable java.lang.Object,X extends java.lang.Exception> V getChecked(java.util.concurrent.Future<V> future, java.lang.Class<X> exceptionClass) throws X extends java.lang.Exception
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 ofFuture
in which it is unnecessary to programmatically distinguish between exception types or to extract other information from the exception instance.Exceptions from
Future.get
are treated as follows:- Any
ExecutionException
has its cause wrapped in anX
if the cause is a checked exception, anUncheckedExecutionException
if the cause is aRuntimeException
, or anExecutionError
if the cause is anError
. - Any
InterruptedException
is wrapped in anX
(after restoring the interrupt). - Any
CancellationException
is propagated untouched, as is any otherRuntimeException
(thoughget
implementations 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
ExecutionException
is wrapped in order to ensure that the new stack trace matches that of the current thread.Instances of
exceptionClass
are created by choosing an arbitrary public constructor that accepts zero or more arguments, all of typeString
orThrowable
(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, anIllegalArgumentException
is thrown.- Throws:
X
- ifget
throws any checked exception except for anExecutionException
whose cause is not itself a checked exceptionUncheckedExecutionException
- ifget
throws anExecutionException
with aRuntimeException
as its causeExecutionError
- ifget
throws anExecutionException
with anError
as its causejava.util.concurrent.CancellationException
- ifget
throws aCancellationException
java.lang.IllegalArgumentException
- ifexceptionClass
extendsRuntimeException
or does not have a suitable constructorX extends java.lang.Exception
- Since:
- 19.0 (in 10.0 as
get
)
- Any
-
getChecked
@CanIgnoreReturnValue @GwtIncompatible public static <V extends @Nullable java.lang.Object,X extends java.lang.Exception> V getChecked(java.util.concurrent.Future<V> future, java.lang.Class<X> exceptionClass, java.time.Duration timeout) throws X extends java.lang.Exception
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 ofFuture
in which it is unnecessary to programmatically distinguish between exception types or to extract other information from the exception instance.Exceptions from
Future.get
are treated as follows:- Any
ExecutionException
has its cause wrapped in anX
if the cause is a checked exception, anUncheckedExecutionException
if the cause is aRuntimeException
, or anExecutionError
if the cause is anError
. - Any
InterruptedException
is wrapped in anX
(after restoring the interrupt). - Any
TimeoutException
is wrapped in anX
. - Any
CancellationException
is propagated untouched, as is any otherRuntimeException
(thoughget
implementations 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
ExecutionException
is wrapped in order to ensure that the new stack trace matches that of the current thread.Instances of
exceptionClass
are created by choosing an arbitrary public constructor that accepts zero or more arguments, all of typeString
orThrowable
(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, anIllegalArgumentException
is thrown.- Throws:
X
- ifget
throws any checked exception except for anExecutionException
whose cause is not itself a checked exceptionUncheckedExecutionException
- ifget
throws anExecutionException
with aRuntimeException
as its causeExecutionError
- ifget
throws anExecutionException
with anError
as its causejava.util.concurrent.CancellationException
- ifget
throws aCancellationException
java.lang.IllegalArgumentException
- ifexceptionClass
extendsRuntimeException
or does not have a suitable constructorX extends java.lang.Exception
- Since:
- 28.0
- Any
-
getChecked
@CanIgnoreReturnValue @GwtIncompatible public static <V extends @Nullable java.lang.Object,X extends java.lang.Exception> V getChecked(java.util.concurrent.Future<V> future, java.lang.Class<X> exceptionClass, long timeout, java.util.concurrent.TimeUnit unit) throws X extends java.lang.Exception
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 ofFuture
in which it is unnecessary to programmatically distinguish between exception types or to extract other information from the exception instance.Exceptions from
Future.get
are treated as follows:- Any
ExecutionException
has its cause wrapped in anX
if the cause is a checked exception, anUncheckedExecutionException
if the cause is aRuntimeException
, or anExecutionError
if the cause is anError
. - Any
InterruptedException
is wrapped in anX
(after restoring the interrupt). - Any
TimeoutException
is wrapped in anX
. - Any
CancellationException
is propagated untouched, as is any otherRuntimeException
(thoughget
implementations 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
ExecutionException
is wrapped in order to ensure that the new stack trace matches that of the current thread.Instances of
exceptionClass
are created by choosing an arbitrary public constructor that accepts zero or more arguments, all of typeString
orThrowable
(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, anIllegalArgumentException
is thrown.- Throws:
X
- ifget
throws any checked exception except for anExecutionException
whose cause is not itself a checked exceptionUncheckedExecutionException
- ifget
throws anExecutionException
with aRuntimeException
as its causeExecutionError
- ifget
throws anExecutionException
with anError
as its causejava.util.concurrent.CancellationException
- ifget
throws aCancellationException
java.lang.IllegalArgumentException
- ifexceptionClass
extendsRuntimeException
or does not have a suitable constructorX extends java.lang.Exception
- Since:
- 19.0 (in 10.0 as
get
and with different parameter order)
- Any
-
getUnchecked
@CanIgnoreReturnValue public static <V extends @Nullable java.lang.Object> V getUnchecked(java.util.concurrent.Future<V> future)
Returns the result of callingFuture.get()
uninterruptibly on a task known not to throw a checked exception. This makesFuture
more 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.get
are treated as follows:- Any
ExecutionException
has its cause wrapped in anUncheckedExecutionException
(if the cause is anException
) orExecutionError
(if the cause is anError
). - Any
InterruptedException
causes a retry of theget
call. The interrupt is restored beforegetUnchecked
returns. - Any
CancellationException
is propagated untouched. So is any otherRuntimeException
(get
implementations 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 anUncheckedExecutionException
orExecutionError
.For an uninterruptible
get
that preserves other exceptions, seeUninterruptibles.getUninterruptibly(Future)
.- Throws:
UncheckedExecutionException
- ifget
throws anExecutionException
with anException
as its causeExecutionError
- ifget
throws anExecutionException
with anError
as its causejava.util.concurrent.CancellationException
- ifget
throws aCancellationException
- Since:
- 10.0
- Any
-
-