@Beta @GwtCompatible(emulated=true) public final class Futures extends Object
Future interface.
Many of these methods use the ListenableFuture API; consult the Guava User Guide article on ListenableFuture.
| Modifier and Type | Method and Description |
|---|---|
static <V> void |
addCallback(ListenableFuture
Registers separate success and failure callbacks to be run when the
Future's computation is
complete or, if the computation is already complete, immediately.
|
static <V> void |
addCallback(ListenableFuture
Registers separate success and failure callbacks to be run when the
Future's computation is
complete or, if the computation is already complete, immediately.
|
static <V> ListenableFuture |
allAsList(Iterable
Creates a new
ListenableFuture whose value is a list containing the values of all its input futures, if all succeed.
|
static <V> ListenableFuture |
allAsList(ListenableFuture
Creates a new
ListenableFuture whose value is a list containing the values of all its input futures, if all succeed.
|
static <V |
catching(ListenableFuture
Returns a
Future whose result is taken from the given primary
input or, if the primary input fails with the given
exceptionType, from the result provided by the
fallback.
|
static <V |
catching(ListenableFuture
Returns a
Future whose result is taken from the given primary
input or, if the primary input fails with the given
exceptionType, from the result provided by the
fallback.
|
static <V |
catchingAsync(ListenableFuture
Returns a
Future whose result is taken from the given primary
input or, if the primary input fails with the given
exceptionType, from the result provided by the
fallback.
|
static <V |
catchingAsync(ListenableFuture
Returns a
Future whose result is taken from the given primary
input or, if the primary input fails with the given
exceptionType, from the result provided by the
fallback.
|
static <V> ListenableFuture |
dereference(ListenableFuture
Returns a new
ListenableFuture whose result is the product of calling
get() on the
Future nested within the given
Future, effectively chaining the futures one after the other.
|
static <V |
get(Future
Deprecated.
Use
getChecked(Future, Class). This method will be removed in Guava release 20.0.
|
static <V |
get(Future
Deprecated.
Use
getChecked(Future, Class, long, TimeUnit), noting the change in parameter order. This method will be removed in Guava release 20.0.
|
static <V |
getChecked(Future
Returns the result of
Future, converting most exceptions to a new instance of the given checked exception type.
|
static <V |
getChecked(Future
Returns the result of
Future, converting most exceptions to a new instance of the given checked exception type.
|
static <V> V |
getUnchecked(Future
Returns the result of calling
Future uninterruptibly on a task known not to throw a checked exception.
|
static <V> ListenableFuture |
immediateCancelledFuture()
Creates a
ListenableFuture which is cancelled immediately upon construction, so that
isCancelled() always returns
true.
|
static <V |
immediateCheckedFuture(V value)
Returns a
CheckedFuture which has its value set immediately upon construction.
|
static <V |
immediateFailedCheckedFuture(X exception)
Returns a
CheckedFuture which has an exception set immediately upon construction.
|
static <V> ListenableFuture |
immediateFailedFuture(Throwable
Returns a
ListenableFuture which has an exception set immediately upon construction.
|
static <V> ListenableFuture |
immediateFuture(V value)
Creates a
ListenableFuture which has its value set immediately upon construction.
|
static <T> ImmutableList |
inCompletionOrder(Iterable
Returns a list of delegate futures that correspond to the futures received in the order that they complete.
|
static <I |
lazyTransform(Future
Like
transform(ListenableFuture, Function) except that the transformation
function is invoked on each call to
get() on the returned future.
|
static <V |
makeChecked(ListenableFuture
Creates a
CheckedFuture out of a normal
ListenableFuture and a
Function that maps from
Exception instances into the appropriate checked type.
|
static <V> ListenableFuture |
nonCancellationPropagating(ListenableFuture
Creates a new
ListenableFuture whose result is set from the supplied future when it completes.
|
static <V> ListenableFuture |
successfulAsList(Iterable
Creates a new
ListenableFuture whose value is a list containing the values of all its successful input futures.
|
static <V> ListenableFuture |
successfulAsList(ListenableFuture
Creates a new
ListenableFuture whose value is a list containing the values of all its successful input futures.
|
static <I |
transform(ListenableFuture
Deprecated.
These
AsyncFunction overloads of transform are being renamed to transformAsync. (The Function overloads are keeping the "transform" name.) This method will be removed in Guava release 20.0.
|
static <I |
transform(ListenableFuture
Deprecated.
These
AsyncFunction overloads of transform are being renamed to transformAsync. (The Function overloads are keeping the "transform" name.) This method will be removed in Guava release 20.0.
|
static <I |
transform(ListenableFuture
Returns a new
ListenableFuture whose result is the product of applying the given
Function to the result of the given
Future.
|
static <I |
transform(ListenableFuture
Returns a new
ListenableFuture whose result is the product of applying the given
Function to the result of the given
Future.
|
static <I |
transformAsync(ListenableFuture
Returns a new
ListenableFuture whose result is asynchronously derived from the result of the given
Future.
|
static <I |
transformAsync(ListenableFuture
Returns a new
ListenableFuture whose result is asynchronously derived from the result of the given
Future.
|
static <V> ListenableFuture |
withFallback(ListenableFuture
Deprecated.
Use
catchingAsync(input, Throwable.class, fallbackImplementedAsAnAsyncFunction), usually replacing Throwable.class with the specific type you want to handle. This method will be removed in Guava release 20.0.
|
static <V> ListenableFuture |
withFallback(ListenableFuture
Deprecated.
Use
catchingAsync(input, Throwable.class, fallbackImplementedAsAnAsyncFunction, executor), usually replacing Throwable.class with the specific type you want to handle. This method will be removed in Guava release 20.0.
|
static <V> ListenableFuture |
withTimeout(ListenableFuture
Returns a future that delegates to another but will finish early (via a
TimeoutException wrapped in an
ExecutionException) if the specified duration expires.
|
@GwtIncompatible(value="TODO") public static <V,X extends Exception > CheckedFuture <V ,X> makeChecked(ListenableFuture <V> future, Function <? super Exception ,X> mapper)
CheckedFuture out of a normal
ListenableFuture and a
Function that maps from
Exception instances into the appropriate checked type.
Warning: We recommend against using CheckedFuture in new projects. CheckedFuture is difficult to build libraries atop. CheckedFuture ports of methods like transformAsync(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 the CheckedFuture API. Additionally, CheckedFuture encourages 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, a CancellationException, or an ExecutionException. See Future for details on the exceptions thrown.
public static <V> ListenableFuture<V> immediateFuture(V value)
ListenableFuture which has its value set immediately upon construction. The getters just return the value. This
Future can't be canceled or timed out and its
isDone() method always returns
true.
@GwtIncompatible(value="TODO") public static <V,X extends Exception > CheckedFuture <V ,X> immediateCheckedFuture(V value)
CheckedFuture which has its value set immediately upon construction.
The returned Future can't be cancelled, and its isDone() method always returns true. Calling get() or checkedGet() will immediately return the provided value.
public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable)
ListenableFuture which has an exception set immediately upon construction.
The returned Future can't be cancelled, and its isDone() method always returns true. Calling get() will immediately throw the provided Throwable wrapped in an ExecutionException.
@GwtIncompatible(value="TODO") public static <V> ListenableFuture<V> immediateCancelledFuture()
ListenableFuture which is cancelled immediately upon construction, so that
isCancelled() always returns
true.
@GwtIncompatible(value="TODO") public static <V,X extends Exception > CheckedFuture <V ,X> immediateFailedCheckedFuture(X exception)
CheckedFuture which has an exception set immediately upon construction.
The returned Future can't be cancelled, and its isDone() method always returns true. Calling get() will immediately throw the provided Exception wrapped in an ExecutionException, and calling checkedGet() will throw the provided exception itself.
@Deprecated public static <V> ListenableFuture<V> withFallback(ListenableFuture <? extends V> input, FutureFallback <? extends V> fallback)
catchingAsync(input, Throwable.class, fallbackImplementedAsAnAsyncFunction), usually replacing Throwable.class with the specific type you want to handle. This method will be removed in Guava release 20.0.
Future whose result is taken from the given primary
input or, if the primary input fails, from the
Future provided by the
fallback.
FutureFallback.create(java.lang.Throwable) is not invoked until the primary input has failed, so if the primary input succeeds, it is never invoked. If, during the invocation of
fallback, an exception is thrown, this exception is used as the result of the output
Future.
Below is an example of a fallback that returns a default value if an exception occurs:
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.withFallback( fetchCounterFuture, new FutureFallback<Integer>() { public ListenableFuture<Integer> create(Throwable t) { // Returning "0" as the default for the counter when the // exception happens. 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.withFallback( fetchCounterFuture, new FutureFallback<Integer>() { public ListenableFuture<Integer> create(Throwable t) { if (t instanceof TimeoutException) { return immediateFuture(0); } return immediateFailedFuture(t); } });
This overload, which does not accept an executor, uses directExecutor, a dangerous choice in some cases. See the discussion in the ListenableFuture.addListener documentation. The documentation's warnings about "lightweight listeners" refer here to the work done during FutureFallback.create, not to any work done to complete the returned Future.
input - the primary input
Future
fallback - the
FutureFallback implementation to be called if
input fails
@Deprecated public static <V> ListenableFuture<V> withFallback(ListenableFuture <? extends V> input, FutureFallback <? extends V> fallback, Executor executor)
catchingAsync(input, Throwable.class, fallbackImplementedAsAnAsyncFunction, executor), usually replacing Throwable.class with the specific type you want to handle. This method will be removed in Guava release 20.0.
Future whose result is taken from the given primary
input or, if the primary input fails, from the
Future provided by the
fallback.
FutureFallback.create(java.lang.Throwable) is not invoked until the primary input has failed, so if the primary input succeeds, it is never invoked. If, during the invocation of
fallback, an exception is thrown, this exception is used as the result of the output
Future.
Below is an example of a fallback that returns a default value if an exception occurs:
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.withFallback( fetchCounterFuture, new FutureFallback<Integer>() { public ListenableFuture<Integer> create(Throwable t) { // Returning "0" as the default for the counter when the // exception happens. 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.withFallback( fetchCounterFuture, new FutureFallback<Integer>() { public ListenableFuture<Integer> create(Throwable t) { if (t instanceof TimeoutException) { return immediateFuture(0); } return immediateFailedFuture(t); } }, directExecutor());
When selecting an executor, note that directExecutor is dangerous in some cases. See the discussion in the ListenableFuture.addListener documentation. The documentation's warnings about "lightweight listeners" refer here to the work done during FutureFallback.create, not to any work done to complete the returned Future.
input - the primary input
Future
fallback - the
FutureFallback implementation to be called if
input fails
executor - the executor that runs
fallback if
input fails
@GwtIncompatible(value="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)
Future whose result is taken from the given primary
input or, if the primary input fails with the given
exceptionType, from the result provided by the
fallback.
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 of
fallback, an exception is thrown, this exception is used as the result of the output
Future.
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 the ListenableFuture.addListener documentation. The documentation's warnings about "lightweight listeners" refer here to the work done during Function.apply.
input - the primary input
Future
exceptionType - the exception type that triggers use of
fallback. To avoid hiding bugs and other unrecoverable errors, callers should prefer more specific types, avoiding
Throwable.class in particular.
fallback - the
Function implementation to be called if
input fails with the expected exception type
@GwtIncompatible(value="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)
Future whose result is taken from the given primary
input or, if the primary input fails with the given
exceptionType, from the result provided by the
fallback.
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 of
fallback, an exception is thrown, this exception is used as the result of the output
Future.
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 directExecutor is dangerous in some cases. See the discussion in the ListenableFuture.addListener documentation. The documentation's warnings about "lightweight listeners" refer here to the work done during Function.apply.
input - the primary input
Future
exceptionType - the exception type that triggers use of
fallback. To avoid hiding bugs and other unrecoverable errors, callers should prefer more specific types, avoiding
Throwable.class in particular.
fallback - the
Function implementation to be called if
input fails with the expected exception type
executor - the executor that runs
fallback if
input fails
@GwtIncompatible(value="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)
Future whose result is taken from the given primary
input or, if the primary input fails with the given
exceptionType, from the result provided by the
fallback.
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 of
fallback, an exception is thrown, this exception is used as the result of the output
Future.
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 the ListenableFuture.addListener documentation. The documentation's warnings about "lightweight listeners" refer here to the work done during AsyncFunction.apply, not to any work done to complete the returned Future.
input - the primary input
Future
exceptionType - the exception type that triggers use of
fallback. To avoid hiding bugs and other unrecoverable errors, callers should prefer more specific types, avoiding
Throwable.class in particular.
fallback - the
AsyncFunction implementation to be called if
input fails with the expected exception type
withFallback)
@GwtIncompatible(value="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)
Future whose result is taken from the given primary
input or, if the primary input fails with the given
exceptionType, from the result provided by the
fallback.
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 of
fallback, an exception is thrown, this exception is used as the result of the output
Future.
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 directExecutor is dangerous in some cases. See the discussion in the ListenableFuture.addListener documentation. The documentation's warnings about "lightweight listeners" refer here to the work done during AsyncFunction.apply, not to any work done to complete the returned Future.
input - the primary input
Future
exceptionType - the exception type that triggers use of
fallback. To avoid hiding bugs and other unrecoverable errors, callers should prefer more specific types, avoiding
Throwable.class in particular.
fallback - the
AsyncFunction implementation to be called if
input fails with the expected exception type
executor - the executor that runs
fallback if
input fails
withFallback)
@GwtIncompatible(value="java.util.concurrent.ScheduledExecutorService") public static <V> ListenableFuture<V> withTimeout(ListenableFuture <V> delegate, long time, TimeUnit unit, ScheduledExecutorService scheduledExecutor)
TimeoutException wrapped in an
ExecutionException) if the specified duration expires.
The delegate future is interrupted and cancelled if it times out.
delegate - The future to delegate to.
time - when to timeout the future
unit - the time unit of the time parameter
scheduledExecutor - The executor service to enforce the timeout.
@Deprecated public static <I,O> ListenableFuture <O> transform(ListenableFuture <I> input, AsyncFunction <? super I ,? extends O> function)
AsyncFunction overloads of transform are being renamed to transformAsync. (The Function overloads are keeping the "transform" name.) This method will be removed in Guava release 20.0.
ListenableFuture whose result is asynchronously derived from the result of the given
Future. More precisely, the returned
Future takes its result from a
Future produced by applying the given
AsyncFunction to the result of the original
Future. Example:
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 = transform(rowKeyFuture, queryFunction);
This overload, which does not accept an executor, uses directExecutor, a dangerous choice in some cases. See the discussion in the ListenableFuture.addListener documentation. The documentation's warnings about "lightweight listeners" refer here to the work done during AsyncFunction.apply, not to any work done to complete the returned Future.
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 function. That is, if the returned Future is cancelled, it will attempt to cancel the other two, and if either of the other two is cancelled, the returned Future will receive a callback in which it will attempt to cancel itself.
input - The future to transform
function - A function to transform the result of the input future to the result of the output future
@Deprecated public static <I,O> ListenableFuture <O> transform(ListenableFuture <I> input, AsyncFunction <? super I ,? extends O> function, Executor executor)
AsyncFunction overloads of transform are being renamed to transformAsync. (The Function overloads are keeping the "transform" name.) This method will be removed in Guava release 20.0.
ListenableFuture whose result is asynchronously derived from the result of the given
Future. More precisely, the returned
Future takes its result from a
Future produced by applying the given
AsyncFunction to the result of the original
Future. Example:
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 = transform(rowKeyFuture, queryFunction, executor);
When selecting an executor, note that directExecutor is dangerous in some cases. See the discussion in the ListenableFuture.addListener documentation. The documentation's warnings about "lightweight listeners" refer here to the work done during AsyncFunction.apply, not to any work done to complete the returned Future.
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 returned Future is cancelled, it will attempt to cancel the other two, and if either of the other two is cancelled, the returned Future will receive a callback in which it will attempt to cancel itself.
input - The future to transform
function - A function to transform the result of the input future to the result of the output future
executor - Executor to run the function in.
public static <I,O> ListenableFuture <O> transformAsync(ListenableFuture <I> input, AsyncFunction <? super I ,? extends O> function)
ListenableFuture whose result is asynchronously derived from the result of the given
Future. More precisely, the returned
Future takes its result from a
Future produced by applying the given
AsyncFunction to the result of the original
Future. Example:
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 the ListenableFuture.addListener documentation. The documentation's warnings about "lightweight listeners" refer here to the work done during AsyncFunction.apply, not to any work done to complete the returned Future.
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 function. That is, if the returned Future is cancelled, it will attempt to cancel the other two, and if either of the other two is cancelled, the returned Future will receive a callback in which it will attempt to cancel itself.
input - The future to transform
function - A function to transform the result of the input future to the result of the output future
transform)
public static <I,O> ListenableFuture <O> transformAsync(ListenableFuture <I> input, AsyncFunction <? super I ,? extends O> function, Executor executor)
ListenableFuture whose result is asynchronously derived from the result of the given
Future. More precisely, the returned
Future takes its result from a
Future produced by applying the given
AsyncFunction to the result of the original
Future. Example:
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 directExecutor is dangerous in some cases. See the discussion in the ListenableFuture.addListener documentation. The documentation's warnings about "lightweight listeners" refer here to the work done during AsyncFunction.apply, not to any work done to complete the returned Future.
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 returned Future is cancelled, it will attempt to cancel the other two, and if either of the other two is cancelled, the returned Future will receive a callback in which it will attempt to cancel itself.
input - The future to transform
function - A function to transform the result of the input future to the result of the output future
executor - Executor to run the function in.
transform)
public static <I,O> ListenableFuture <O> transform(ListenableFuture <I> input, Function <? super I ,? extends O> function)
ListenableFuture whose result is the product of applying the given
Function to the result of the given
Future. Example:
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 the ListenableFuture.addListener documentation. The documentation's warnings about "lightweight listeners" refer here to the work done during Function.apply.
The returned Future attempts to keep its cancellation state in sync with that of the input future. That is, if the returned Future is cancelled, it will attempt to cancel the input, and if the input is cancelled, the returned Future 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.
input - The future to transform
function - 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.
compose)
public static <I,O> ListenableFuture <O> transform(ListenableFuture <I> input, Function <? super I ,? extends O> function, Executor executor)
ListenableFuture whose result is the product of applying the given
Function to the result of the given
Future. Example:
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 directExecutor is dangerous in some cases. See the discussion in the ListenableFuture.addListener documentation. The documentation's warnings about "lightweight listeners" refer here to the work done during Function.apply.
The returned Future attempts to keep its cancellation state in sync with that of the input future. That is, if the returned Future is cancelled, it will attempt to cancel the input, and if the input is cancelled, the returned Future 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.
input - The future to transform
function - A Function to transform the results of the provided future to the results of the returned future.
executor - Executor to run the function in.
compose)
@GwtIncompatible(value="TODO") public static <I,O> Future <O> lazyTransform(Future <I> input, Function <? super I ,? extends O> function)
transform(ListenableFuture, Function) except that the transformation
function is invoked on each call to
get() 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 a ListenableFuture available and do not mind repeated, lazy function evaluation.
input - The future to transform
function - A Function to transform the results of the provided future to the results of the returned future.
public static <V> ListenableFuture<V> dereference(ListenableFuture <? extends ListenableFuture <? extends V>> nested)
ListenableFuture whose result is the product of calling
get() on the
Future nested within the given
Future, effectively chaining the futures one after the other. Example:
SettableFuture<ListenableFuture<String>> nested = SettableFuture.create(); ListenableFuture<String> dereferenced = dereference(nested);
This call has the same cancellation and execution semantics as transform(ListenableFuture, AsyncFunction), in that the returned Future attempts to keep its cancellation state in sync with both the input Future and the nested Future. The transformation is very lightweight and therefore takes place in the same thread (either the thread that called dereference, or the thread in which the dereferenced future completes).
nested - The nested future to transform.
@Beta @SafeVarargs public static <V> ListenableFuture<List <V>> allAsList(ListenableFuture <? extends V>... futures)
ListenableFuture whose 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.
futures - futures to combine
@Beta public static <V> ListenableFuture<List <V>> allAsList(Iterable <? extends ListenableFuture <? extends V>> futures)
ListenableFuture whose 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.
futures - futures to combine
@GwtIncompatible(value="TODO") public static <V> ListenableFuture<V> nonCancellationPropagating(ListenableFuture <V> future)
ListenableFuture 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.
@Beta @SafeVarargs public static <V> ListenableFuture<List <V>> successfulAsList(ListenableFuture <? extends V>... futures)
ListenableFuture 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 contain
null (which is indistinguishable from the future having a successful value of
null).
Canceling this future will attempt to cancel all the component futures.
futures - futures to combine
@Beta public static <V> ListenableFuture<List <V>> successfulAsList(Iterable <? extends ListenableFuture <? extends V>> futures)
ListenableFuture 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 contain
null (which is indistinguishable from the future having a successful value of
null).
Canceling this future will attempt to cancel all the component futures.
futures - futures to combine
@Beta @GwtIncompatible(value="TODO") public static <T> ImmutableList<ListenableFuture <T>> inCompletionOrder(Iterable <? extends ListenableFuture <? extends T>> futures)
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.
public static <V> void addCallback(ListenableFuture<V> future, FutureCallback <? super V> callback)
Future'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 the ListenableFuture.addListener documentation.
For a more general interface to attach a completion listener to a Future, see addListener.
future - The future attach the callback to.
callback - The callback to invoke when
future is completed.
public static <V> void addCallback(ListenableFuture<V> future, FutureCallback <? super V> callback, Executor executor)
Future'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 directExecutor is dangerous in some cases. See the discussion in the ListenableFuture.addListener documentation.
For a more general interface to attach a completion listener to a Future, see addListener.
future - The future attach the callback to.
callback - The callback to invoke when
future is completed.
executor - The executor to run
callback when the future completes.
@Deprecated @GwtIncompatible(value="reflection") public static <V,X extends Exception > V get(Future <V> future, Class <X> exceptionClass) throws X extends Exception
getChecked(Future, Class). This method will be removed in Guava release 20.0.
Future.get() , converting most exceptions to a new instance of the given checked exception type. This reduces boilerplate for a common use of
Future 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:
ExecutionException has its cause wrapped in an X if the cause is a checked exception, an UncheckedExecutionException if the cause is a RuntimeException, or an ExecutionError if the cause is an Error. InterruptedException is wrapped in an X (after restoring the interrupt). CancellationException is propagated untouched, as is any other RuntimeException (though get 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 type String or Throwable (preferring constructors with at least one String) and calling the constructor via reflection. If the exception did not already have a cause, one is set by calling Throwable on it. If no such constructor exists, an IllegalArgumentException is thrown.
X - if
get throws any checked exception except for an
ExecutionException whose cause is not itself a checked exception
UncheckedExecutionException - if
get throws an
ExecutionException with a
RuntimeException as its cause
ExecutionError - if
get throws an
ExecutionException with an
Error as its cause
CancellationException - if
get throws a
CancellationException
IllegalArgumentException - if
exceptionClass extends
RuntimeException or does not have a suitable constructor
X extends Exception
@Deprecated @GwtIncompatible(value="reflection") public static <V,X extends Exception > V get(Future <V> future, long timeout, TimeUnit unit, Class <X> exceptionClass) throws X extends Exception
getChecked(Future, Class, long, TimeUnit), noting the change in parameter order. This method will be removed in Guava release 20.0.
Future.get(long, TimeUnit) , converting most exceptions to a new instance of the given checked exception type. This reduces boilerplate for a common use of
Future 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:
ExecutionException has its cause wrapped in an X if the cause is a checked exception, an UncheckedExecutionException if the cause is a RuntimeException, or an ExecutionError if the cause is an Error. InterruptedException is wrapped in an X (after restoring the interrupt). TimeoutException is wrapped in an X. CancellationException is propagated untouched, as is any other RuntimeException (though get 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 type String or Throwable (preferring constructors with at least one String) and calling the constructor via reflection. If the exception did not already have a cause, one is set by calling Throwable on it. If no such constructor exists, an IllegalArgumentException is thrown.
X - if
get throws any checked exception except for an
ExecutionException whose cause is not itself a checked exception
UncheckedExecutionException - if
get throws an
ExecutionException with a
RuntimeException as its cause
ExecutionError - if
get throws an
ExecutionException with an
Error as its cause
CancellationException - if
get throws a
CancellationException
IllegalArgumentException - if
exceptionClass extends
RuntimeException or does not have a suitable constructor
X extends Exception
@GwtIncompatible(value="reflection") public static <V,X extends Exception > V getChecked(Future <V> future, Class <X> exceptionClass) throws X extends Exception
Future.get() , converting most exceptions to a new instance of the given checked exception type. This reduces boilerplate for a common use of
Future 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:
ExecutionException has its cause wrapped in an X if the cause is a checked exception, an UncheckedExecutionException if the cause is a RuntimeException, or an ExecutionError if the cause is an Error. InterruptedException is wrapped in an X (after restoring the interrupt). CancellationException is propagated untouched, as is any other RuntimeException (though get 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 type String or Throwable (preferring constructors with at least one String) and calling the constructor via reflection. If the exception did not already have a cause, one is set by calling Throwable on it. If no such constructor exists, an IllegalArgumentException is thrown.
X - if
get throws any checked exception except for an
ExecutionException whose cause is not itself a checked exception
UncheckedExecutionException - if
get throws an
ExecutionException with a
RuntimeException as its cause
ExecutionError - if
get throws an
ExecutionException with an
Error as its cause
CancellationException - if
get throws a
CancellationException
IllegalArgumentException - if
exceptionClass extends
RuntimeException or does not have a suitable constructor
X extends Exception
get)
@GwtIncompatible(value="reflection") public static <V,X extends Exception > V getChecked(Future <V> future, Class <X> exceptionClass, long timeout, TimeUnit unit) throws X extends Exception
Future.get(long, TimeUnit) , converting most exceptions to a new instance of the given checked exception type. This reduces boilerplate for a common use of
Future 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:
ExecutionException has its cause wrapped in an X if the cause is a checked exception, an UncheckedExecutionException if the cause is a RuntimeException, or an ExecutionError if the cause is an Error. InterruptedException is wrapped in an X (after restoring the interrupt). TimeoutException is wrapped in an X. CancellationException is propagated untouched, as is any other RuntimeException (though get 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 type String or Throwable (preferring constructors with at least one String) and calling the constructor via reflection. If the exception did not already have a cause, one is set by calling Throwable on it. If no such constructor exists, an IllegalArgumentException is thrown.
X - if
get throws any checked exception except for an
ExecutionException whose cause is not itself a checked exception
UncheckedExecutionException - if
get throws an
ExecutionException with a
RuntimeException as its cause
ExecutionError - if
get throws an
ExecutionException with an
Error as its cause
CancellationException - if
get throws a
CancellationException
IllegalArgumentException - if
exceptionClass extends
RuntimeException or does not have a suitable constructor
X extends Exception
get and with different parameter order)
@GwtIncompatible(value="TODO") public static <V> V getUnchecked(Future<V> future)
Future.get() uninterruptibly on a task known not to throw a checked exception. This makes
Future 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 of
ForkJoinTask.join.
Exceptions from Future.get are treated as follows:
ExecutionException has its cause wrapped in an UncheckedExecutionException (if the cause is an Exception) or ExecutionError (if the cause is an Error). InterruptedException causes a retry of the get call. The interrupt is restored before getUnchecked returns. CancellationException is propagated untouched. So is any other RuntimeException (get implementations are discouraged from throwing such exceptions). The overall principle is to eliminate all checked exceptions: to loop to avoid InterruptedException, to pass through CancellationException, and to wrap any exception from the underlying computation in an UncheckedExecutionException or ExecutionError.
For an uninterruptible get that preserves other exceptions, see Uninterruptibles.
UncheckedExecutionException - if
get throws an
ExecutionException with an
Exception as its cause
ExecutionError - if
get throws an
ExecutionException with an
Error as its cause
CancellationException - if
get throws a
CancellationException