Class Futures
- java.lang.Object
-
- com.google.common.util.concurrent.Futures
-
@Beta public final class Futures extends java.lang.Object
Static utility methods pertaining to theFutureinterface.Many of these methods use the
ListenableFutureAPI; consult the Guava User Guide article onListenableFuture.- Since:
- 1.0
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static <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, 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> ListenableFuture<java.util.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<java.util.List<V>>allAsList(java.lang.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> 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 java.lang.Exception>
Vget(java.util.concurrent.Future<V> future, long timeout, java.util.concurrent.TimeUnit unit, java.lang.Class<X> exceptionClass)Returns the result ofFuture.get(long, TimeUnit), converting most exceptions to a new instance of the given checked exception type.static <V,X extends java.lang.Exception>
Vget(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> 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> ListenableFuture<V>immediateCancelledFuture()Creates aListenableFuturewhich is cancelled immediately upon construction, so thatisCancelled()always returnstrue.static <V,X extends java.lang.Exception>
CheckedFuture<V,X>immediateCheckedFuture(V value)Returns aCheckedFuturewhich has its value set immediately upon construction.static <V,X extends java.lang.Exception>
CheckedFuture<V,X>immediateFailedCheckedFuture(X exception)Returns aCheckedFuturewhich has an exception set immediately upon construction.static <V> ListenableFuture<V>immediateFailedFuture(java.lang.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 <I,O>
java.util.concurrent.Future<O>lazyTransform(java.util.concurrent.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 java.lang.Exception>
CheckedFuture<V,X>makeChecked(ListenableFuture<V> future, Function<java.lang.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<java.util.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<java.util.List<V>>successfulAsList(java.lang.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 newListenableFuturewhose result is the product of applying the givenFunctionto the result of the givenFuture.static <I,O>
ListenableFuture<O>transform(ListenableFuture<I> input, Function<? super I,? extends O> function, java.util.concurrent.Executor executor)Returns a newListenableFuturewhose result is the product of applying the givenFunctionto the result of the givenFuture.static <I,O>
ListenableFuture<O>transform(ListenableFuture<I> input, AsyncFunction<? super I,? extends O> function)Returns a newListenableFuturewhose result is asynchronously derived from the result of the givenFuture.static <I,O>
ListenableFuture<O>transform(ListenableFuture<I> input, AsyncFunction<? super I,? extends O> function, java.util.concurrent.Executor executor)Returns a newListenableFuturewhose result is asynchronously derived from the result of the givenFuture.static <V> ListenableFuture<V>withFallback(ListenableFuture<? extends V> input, FutureFallback<? extends V> fallback)Returns aFuturewhose result is taken from the given primaryinputor, if the primary input fails, from theFutureprovided by thefallback.static <V> ListenableFuture<V>withFallback(ListenableFuture<? extends V> input, FutureFallback<? extends V> fallback, java.util.concurrent.Executor executor)Returns aFuturewhose result is taken from the given primaryinputor, if the primary input fails, from theFutureprovided by thefallback.
-
-
-
Method Detail
-
makeChecked
public static <V,X extends java.lang.Exception> CheckedFuture<V,X> makeChecked(ListenableFuture<V> future, Function<java.lang.Exception,X> mapper)
Creates aCheckedFutureout of a normalListenableFutureand aFunctionthat maps fromExceptioninstances into the appropriate checked type.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
public static <V> ListenableFuture<V> immediateFuture(@Nullable V value)
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
public static <V,X extends java.lang.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
public static <V> ListenableFuture<V> immediateFailedFuture(java.lang.Throwable throwable)
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
public static <V> ListenableFuture<V> immediateCancelledFuture()
Creates aListenableFuturewhich is cancelled immediately upon construction, so thatisCancelled()always returnstrue.- Since:
- 14.0
-
immediateFailedCheckedFuture
public static <V,X extends java.lang.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.
-
withFallback
public static <V> ListenableFuture<V> withFallback(ListenableFuture<? extends V> input, FutureFallback<? extends V> fallback)
Returns aFuturewhose result is taken from the given primaryinputor, if the primary input fails, from theFutureprovided by thefallback.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 offallback, an exception is thrown, this exception is used as the result of the outputFuture.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); } });Note: If the derived
Futureis slow or heavyweight to create (whether theFutureitself is slow or heavyweight to complete is irrelevant), consider supplying an executor. If you do not supply an executor,withFallbackwill usesameThreadExecutor, which carries some caveats for heavier operations. For example, the call tofallback.createmay run on an unpredictable or undesirable thread:- If the input
Futureis done at the timewithFallbackis called,withFallbackwill callfallback.createinline. - If the input
Futureis not yet done,withFallbackwill schedulefallback.createto be run by the thread that completes the inputFuture, which may be an internal system thread such as an RPC network thread.
Also note that, regardless of which thread executes the
sameThreadExecutorfallback.create, all other registered but unexecuted listeners are prevented from running during its execution, even if those listeners are to run in other executors.- Parameters:
input- the primary inputFuturefallback- theFutureFallbackimplementation to be called ifinputfails- Since:
- 14.0
- If the input
-
withFallback
public static <V> ListenableFuture<V> withFallback(ListenableFuture<? extends V> input, FutureFallback<? extends V> fallback, java.util.concurrent.Executor executor)
Returns aFuturewhose result is taken from the given primaryinputor, if the primary input fails, from theFutureprovided by thefallback.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 offallback, an exception is thrown, this exception is used as the result of the outputFuture.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); } }, sameThreadExecutor());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); } }, sameThreadExecutor());When the execution of
fallback.createis fast and lightweight (though theFutureit returns need not meet these criteria), consider omitting the executor or explicitly specifyingsameThreadExecutor. However, be aware of the caveats documented in the link above.- Parameters:
input- the primary inputFuturefallback- theFutureFallbackimplementation to be called ifinputfailsexecutor- the executor that runsfallbackifinputfails- Since:
- 14.0
-
transform
public static <I,O> ListenableFuture<O> transform(ListenableFuture<I> input, AsyncFunction<? super I,? extends O> function)
Returns a newListenableFuturewhose result is asynchronously derived from the result of the givenFuture. More precisely, the returnedFuturetakes its result from aFutureproduced by applying the givenAsyncFunctionto the result of the originalFuture. 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);Note: If the derived
Futureis slow or heavyweight to create (whether theFutureitself is slow or heavyweight to complete is irrelevant), consider supplying an executor. If you do not supply an executor,transformwill usesameThreadExecutor, which carries some caveats for heavier operations. For example, the call tofunction.applymay run on an unpredictable or undesirable thread:- If the input
Futureis done at the timetransformis called,transformwill callfunction.applyinline. - If the input
Futureis not yet done,transformwill schedulefunction.applyto be run by the thread that completes the inputFuture, which may be an internal system thread such as an RPC network thread.
Also note that, regardless of which thread executes the
sameThreadExecutorfunction.apply, all other registered but unexecuted listeners are prevented from running during its execution, even if those listeners are to run in other executors.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:
- 11.0
- If the input
-
transform
public static <I,O> ListenableFuture<O> transform(ListenableFuture<I> input, AsyncFunction<? super I,? extends O> function, java.util.concurrent.Executor executor)
Returns a newListenableFuturewhose result is asynchronously derived from the result of the givenFuture. More precisely, the returnedFuturetakes its result from aFutureproduced by applying the givenAsyncFunctionto the result of the originalFuture. 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);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.When the execution of
function.applyis fast and lightweight (though theFutureit returns need not meet these criteria), consider omitting the executor or explicitly specifyingsameThreadExecutor. However, be aware of the caveats documented in the link above.- 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:
- 11.0
-
transform
public static <I,O> ListenableFuture<O> transform(ListenableFuture<I> input, Function<? super I,? extends O> function)
Returns a newListenableFuturewhose result is the product of applying the givenFunctionto the result of the givenFuture. 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);Note: If the transformation is slow or heavyweight, consider supplying an executor. If you do not supply an executor,
transformwill usesameThreadExecutor, which carries some caveats for heavier operations. For example, the call tofunction.applymay run on an unpredictable or undesirable thread:- If the input
Futureis done at the timetransformis called,transformwill callfunction.applyinline. - If the input
Futureis not yet done,transformwill schedulefunction.applyto be run by the thread that completes the inputFuture, which may be an internal system thread such as an RPC network thread.
Also note that, regardless of which thread executes the
sameThreadExecutorfunction.apply, all other registered but unexecuted listeners are prevented from running during its execution, even if those listeners are to run in other executors.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)
- If the input
-
transform
public static <I,O> ListenableFuture<O> transform(ListenableFuture<I> input, Function<? super I,? extends O> function, java.util.concurrent.Executor executor)
Returns a newListenableFuturewhose result is the product of applying the givenFunctionto the result of the givenFuture. 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);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.
When the transformation is fast and lightweight, consider omitting the executor or explicitly specifying
sameThreadExecutor. However, be aware of the caveats documented in the link above.- 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
public static <I,O> java.util.concurrent.Future<O> lazyTransform(java.util.concurrent.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);This call has the same cancellation and execution semantics as
transform(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 thread that calleddereference.- Parameters:
nested- The nested future to transform.- Returns:
- A future that holds result of the inner future.
- Since:
- 13.0
-
allAsList
@Beta public static <V> ListenableFuture<java.util.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.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<java.util.List<V>> allAsList(java.lang.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.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
-
nonCancellationPropagating
public static <V> ListenableFuture<V> nonCancellationPropagating(ListenableFuture<V> future)
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 public static <V> ListenableFuture<java.util.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<java.util.List<V>> successfulAsList(java.lang.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
-
addCallback
public static <V> void addCallback(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.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); } });Note: If the callback is slow or heavyweight, consider supplying an executor. If you do not supply an executor,
addCallbackwill usesameThreadExecutor, which carries some caveats for heavier operations. For example, the callback may run on an unpredictable or undesirable thread:- If the input
Futureis done at the timeaddCallbackis called,addCallbackwill execute the callback inline. - If the input
Futureis not yet done,addCallbackwill schedule the callback to be run by the thread that completes the inputFuture, which may be an internal system thread such as an RPC network thread.
Also note that, regardless of which thread executes the
sameThreadExecutorcallback, all other registered but unexecuted listeners are prevented from running during its execution, even if those listeners are to run in other executors.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
- If the input
-
addCallback
public static <V> 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 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, e, new FutureCallback<QueryResult> { public void onSuccess(QueryResult result) { storeInCache(result); } public void onFailure(Throwable t) { reportError(t); } });When the callback is fast and lightweight, consider omitting the executor or explicitly specifying
sameThreadExecutor. However, be aware of the caveats documented in the link above.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
-
get
public static <V,X extends java.lang.Exception> V get(java.util.concurrent.Future<V> future, java.lang.Class<X> exceptionClass) throws X extends java.lang.ExceptionReturns 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 causejava.util.concurrent.CancellationException- ifgetthrows aCancellationExceptionjava.lang.IllegalArgumentException- ifexceptionClassextendsRuntimeExceptionor does not have a suitable constructorX extends java.lang.Exception- Since:
- 10.0
- Any
-
get
public static <V,X extends java.lang.Exception> V get(java.util.concurrent.Future<V> future, long timeout, java.util.concurrent.TimeUnit unit, java.lang.Class<X> exceptionClass) throws X extends java.lang.ExceptionReturns 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 causejava.util.concurrent.CancellationException- ifgetthrows aCancellationExceptionjava.lang.IllegalArgumentException- ifexceptionClassextendsRuntimeExceptionor does not have a suitable constructorX extends java.lang.Exception- Since:
- 10.0
- Any
-
getUnchecked
public static <V> 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 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 causejava.util.concurrent.CancellationException- ifgetthrows aCancellationException- Since:
- 10.0
- Any
-
-