com.google.common.util.concurrent
Class Futures

java.lang.Object
  extended by com.google.common.util.concurrent.Futures

@Beta
public final class Futures
extends Object

Static utility methods pertaining to the Future interface.

Many of these methods use the ListenableFuture API; consult the Guava User Guide article on ListenableFuture.

Since:
1.0
Author:
Kevin Bourrillion, Nishant Thakkar, Sven Mawson

Method Summary
static
<V> void
addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback)
          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<V> future, FutureCallback<? super V> callback, Executor executor)
          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<List<V>>
allAsList(Iterable<? extends ListenableFuture<? extends V>> futures)
          Creates a new ListenableFuture whose value is a list containing the values of all its input futures, if all succeed.
static
<V> ListenableFuture<List<V>>
allAsList(ListenableFuture<? extends V>... futures)
          Creates a new ListenableFuture whose 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 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,X extends Exception>
V
get(Future<V> future, Class<X> exceptionClass)
          Returns the result of Future.get(), converting most exceptions to a new instance of the given checked exception type.
static
<V,X extends Exception>
V
get(Future<V> future, long timeout, TimeUnit unit, Class<X> exceptionClass)
          Returns the result of Future.get(long, TimeUnit), converting most exceptions to a new instance of the given checked exception type.
static
<V> V
getUnchecked(Future<V> future)
          Returns the result of calling Future.get() uninterruptibly on a task known not to throw a checked exception.
static
<V,X extends Exception>
CheckedFuture<V,X>
immediateCheckedFuture(V value)
          Returns a CheckedFuture which has its value set immediately upon construction.
static
<V,X extends Exception>
CheckedFuture<V,X>
immediateFailedCheckedFuture(X exception)
          Returns a CheckedFuture which has an exception set immediately upon construction.
static
<V> ListenableFuture<V>
immediateFailedFuture(Throwable throwable)
          Returns a ListenableFuture which has an exception set immediately upon construction.
static
<V> ListenableFuture<V>
immediateFuture(V value)
          Creates a ListenableFuture which has its value set immediately upon construction.
static
<I,O> Future<O>
lazyTransform(Future<I> input, Function<? super I,? extends O> function)
          Like transform(ListenableFuture, Function) except that the transformation function is invoked on each call to get() on the returned future.
static
<V,X extends Exception>
CheckedFuture<V,X>
makeChecked(ListenableFuture<V> future, Function<Exception,X> mapper)
          Creates a CheckedFuture out of a normal ListenableFuture and a Function that maps from Exception instances into the appropriate checked type.
static
<V> ListenableFuture<List<V>>
successfulAsList(Iterable<? extends ListenableFuture<? extends V>> futures)
          Creates a new ListenableFuture whose value is a list containing the values of all its successful input futures.
static
<V> ListenableFuture<List<V>>
successfulAsList(ListenableFuture<? extends V>... futures)
          Creates a new ListenableFuture whose value is a list containing the values of all its successful input futures.
static
<I,O> ListenableFuture<O>
transform(ListenableFuture<I> input, AsyncFunction<? super I,? extends O> function)
          Returns a new ListenableFuture whose result is asynchronously derived from the result of the given Future.
static
<I,O> ListenableFuture<O>
transform(ListenableFuture<I> input, AsyncFunction<? super I,? extends O> function, Executor executor)
          Returns a new ListenableFuture whose result is asynchronously derived from the result of the given Future.
static
<I,O> ListenableFuture<O>
transform(ListenableFuture<I> input, Function<? super I,? extends O> function)
          Returns a new ListenableFuture whose result is the product of applying the given Function to the result of the given Future.
static
<I,O> ListenableFuture<O>
transform(ListenableFuture<I> input, Function<? super I,? extends O> function, Executor executor)
          Returns a new ListenableFuture whose result is the product of applying the given Function to the result of the given Future.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

makeChecked

public static <V,X extends Exception> CheckedFuture<V,X> makeChecked(ListenableFuture<V> future,
                                                                     Function<Exception,X> mapper)
Creates a CheckedFuture out of a normal ListenableFuture and a Function that maps from Exception instances into the appropriate checked type.

The given mapping function will be applied to an InterruptedException, a CancellationException, or an ExecutionException with the actual cause of the exception. See Future.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 a 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.


immediateCheckedFuture

public static <V,X extends Exception> CheckedFuture<V,X> immediateCheckedFuture(@Nullable
                                                                                V value)
Returns a 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.


immediateFailedFuture

public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable)
Returns a 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.

Throws:
Error - if the throwable is an Error.

immediateFailedCheckedFuture

public static <V,X extends Exception> CheckedFuture<V,X> immediateFailedCheckedFuture(X exception)
Returns a 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 Throwable wrapped in an ExecutionException, and calling checkedGet() will throw the provided exception itself.

Throws:
Error - if the throwable is an Error.

transform

public static <I,O> ListenableFuture<O> transform(ListenableFuture<I> input,
                                                  AsyncFunction<? super I,? extends O> function)
Returns a new 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);
 
Note: If the derived Future is slow or heavyweight to create (whether the Future itself is slow or heavyweight to complete is irrelevant), consider supplying an executor. If you do not supply an executor, transform will use sameThreadExecutor, which carries some caveats for heavier operations. For example, the call to function.apply may run on an unpredictable or undesirable thread: Also note that, regardless of which thread executes function.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 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.

Parameters:
input - The future to transform
function - 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

transform

public static <I,O> ListenableFuture<O> transform(ListenableFuture<I> input,
                                                  AsyncFunction<? super I,? extends O> function,
                                                  Executor executor)
Returns a new 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);
 

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.

When the execution of function.apply is fast and lightweight (though the Future it returns need not meet these criteria), consider omitting the executor or explicitly specifying sameThreadExecutor. However, be aware of the caveats documented in the link above.

Parameters:
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.
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 new 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);
 
Note: If the transformation is slow or heavyweight, consider supplying an executor. If you do not supply an executor, transform will use sameThreadExecutor, which carries some caveats for heavier operations. For example, the call to function.apply may run on an unpredictable or undesirable thread: Also note that, regardless of which thread executes function.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 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.

Parameters:
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.
Returns:
A future that holds result of the transformation.
Since:
9.0 (in 1.0 as compose)

transform

public static <I,O> ListenableFuture<O> transform(ListenableFuture<I> input,
                                                  Function<? super I,? extends O> function,
                                                  Executor executor)
Returns a new 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);
 

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.

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 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.
Returns:
A future that holds result of the transformation.
Since:
9.0 (in 2.0 as compose)

lazyTransform

@Beta
public static <I,O> Future<O> lazyTransform(Future<I> input,
                                                 Function<? super I,? extends O> function)
Like 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.

Parameters:
input - The future to transform
function - 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

@Beta
public static <V> ListenableFuture<V> dereference(ListenableFuture<? extends ListenableFuture<? extends V>> nested)
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. 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 thread that called dereference.

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<List<V>> allAsList(ListenableFuture<? extends V>... futures)
Creates a new 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.

The list of results is in the same order as the input list.

Canceling this future does not cancel any of the component futures; however, if any of the provided futures fails or is canceled, this one is, too.

Parameters:
futures - futures to combine
Returns:
a future that provides a list of the results of the component futures
Since:
10.0

allAsList

@Beta
public static <V> ListenableFuture<List<V>> allAsList(Iterable<? extends ListenableFuture<? extends V>> futures)
Creates a new 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.

The list of results is in the same order as the input list.

Canceling this future does not cancel any of the component futures; however, 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

successfulAsList

@Beta
public static <V> ListenableFuture<List<V>> successfulAsList(ListenableFuture<? extends V>... futures)
Creates a new 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).

Parameters:
futures - futures to combine
Returns:
a future that provides a list of the results of the component futures
Since:
10.0

successfulAsList

@Beta
public static <V> ListenableFuture<List<V>> successfulAsList(Iterable<? extends ListenableFuture<? extends V>> futures)
Creates a new 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).

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 the 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);
       }
     });
Note: If the callback is slow or heavyweight, consider supplying an executor. If you do not supply an executor, addCallback will use sameThreadExecutor, which carries some caveats for heavier operations. For example, the callback may run on an unpredictable or undesirable thread: Also note that, regardless of which thread executes the callback, 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, see addListener.

Parameters:
future - The future attach the callback to.
callback - The callback to invoke when future is completed.
Since:
10.0

addCallback

public static <V> void addCallback(ListenableFuture<V> future,
                                   FutureCallback<? super V> callback,
                                   Executor executor)
Registers separate success and failure callbacks to be run when the 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, 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, see addListener.

Parameters:
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.
Since:
10.0

get

@Beta
public static <V,X extends Exception> V get(Future<V> future,
                                                 Class<X> exceptionClass)
             throws X extends Exception
Returns the result of 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:

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.initCause(Throwable) on it. If no such constructor exists, an IllegalArgumentException is thrown.

Throws:
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
Since:
10.0

get

@Beta
public static <V,X extends Exception> V get(Future<V> future,
                                                 long timeout,
                                                 TimeUnit unit,
                                                 Class<X> exceptionClass)
             throws X extends Exception
Returns the result of 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:

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.initCause(Throwable) on it. If no such constructor exists, an IllegalArgumentException is thrown.

Throws:
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
Since:
10.0

getUnchecked

@Beta
public static <V> V getUnchecked(Future<V> future)
Returns the result of calling 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:

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.getUninterruptibly(Future).

Throws:
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
Since:
10.0


Copyright © 2010-2012. All Rights Reserved.