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.

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

Method Summary
static
<I,O> ListenableFuture<O>
chain(ListenableFuture<I> input, Function<? super I,? extends ListenableFuture<? extends O>> function)
          Returns a new ListenableFuture whose result is asynchronously derived from the result of the given Future.
static
<I,O> ListenableFuture<O>
chain(ListenableFuture<I> input, Function<? super I,? extends ListenableFuture<? extends O>> function, Executor exec)
          Returns a new ListenableFuture whose result is asynchronously derived from the result of the given Future.
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
<V,X extends Exception>
CheckedFuture<V,X>
makeChecked(Future<V> future, Function<Exception,X> mapper)
          Creates a CheckedFuture out of a normal Future and a Function that maps from Exception instances into the appropriate checked type.
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<V>
makeListenable(Future<V> future)
          Creates a ListenableFuture out of a normal Future.
static
<V> UninterruptibleFuture<V>
makeUninterruptible(Future<V> future)
          Returns an uninterruptible view of a Future.
static
<I,O> Future<O>
transform(Future<I> future, Function<? super I,? extends O> function)
          Returns a new Future 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> future, 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> future, Function<? super I,? extends O> function, Executor exec)
          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

makeUninterruptible

public static <V> UninterruptibleFuture<V> makeUninterruptible(Future<V> future)
Returns an uninterruptible view of a Future. If a thread is interrupted during an attempt to get() from the returned future, it continues to wait on the result until it is available or the timeout elapses, and only then re-interrupts the thread.


makeListenable

public static <V> ListenableFuture<V> makeListenable(Future<V> future)

Creates a ListenableFuture out of a normal Future. The returned future will create a thread to wait for the source future to complete before executing the listeners.

Warning: If the input future does not already implement ListenableFuture, the returned future will emulate ListenableFuture.addListener(java.lang.Runnable, java.util.concurrent.Executor) by taking a thread from an internal, unbounded pool at the first call to addListener and holding it until the future is done.

Callers who have a future that subclasses FutureTask may want to instead subclass ListenableFutureTask, which adds the ListenableFuture functionality to the standard FutureTask implementation.


makeChecked

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

Warning: If the input future does not implement ListenableFuture, the returned future will emulate ListenableFuture.addListener(java.lang.Runnable, java.util.concurrent.Executor) by taking a thread from an internal, unbounded pool at the first call to addListener and holding it until the future is done.

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.


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 (source-compatible since release 1)

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.

chain

public static <I,O> ListenableFuture<O> chain(ListenableFuture<I> input,
                                              Function<? super I,? extends ListenableFuture<? 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 Function to the result of the original Future. Example:
   ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
   Function<RowKey, ListenableFuture<QueryResult>> queryFunction =
       new Function<RowKey, ListenableFuture<QueryResult>>() {
         public ListenableFuture<QueryResult> apply(RowKey rowKey) {
           return dataService.read(rowKey);
         }
       };
   ListenableFuture<QueryResult> queryFuture =
       chain(queryFuture, queryFunction);
 

Successful cancellation of either the input future or the result of function application will cause the returned future to be cancelled. Cancelling the returned future will succeed if it is currently running. In this case, attempts will be made to cancel the input future and the result of the function, however there is no guarantee of success.

TODO: Add a version that accepts a normal Future

The typical use for this method would be when a RPC call is dependent on the results of another RPC. One would call the first RPC (input), create a function that calls another RPC based on input's result, and then call chain on input and that function to get a ListenableFuture of the result.

Parameters:
input - The future to chain
function - A function to chain 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 chain.

chain

public static <I,O> ListenableFuture<O> chain(ListenableFuture<I> input,
                                              Function<? super I,? extends ListenableFuture<? extends O>> function,
                                              Executor exec)
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 Function to the result of the original Future. Example:
   ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
   Function<RowKey, ListenableFuture<QueryResult>> queryFunction =
       new Function<RowKey, ListenableFuture<QueryResult>>() {
         public ListenableFuture<QueryResult> apply(RowKey rowKey) {
           return dataService.read(rowKey);
         }
       };
   ListenableFuture<QueryResult> queryFuture =
       chain(queryFuture, queryFunction, executor);
 

Successful cancellation of either the input future or the result of function application will cause the returned future to be cancelled. Cancelling the returned future will succeed if it is currently running. In this case, attempts will be made to cancel the input future and the result of the function, however there is no guarantee of success.

This version allows an arbitrary executor to be passed in for running the chained Function. When using MoreExecutors.sameThreadExecutor(), the thread chained Function executes in will be whichever thread set the result of the input Future, which may be the network thread in the case of RPC-based Futures.

Parameters:
input - The future to chain
function - A function to chain the results of the provided future to the results of the returned future.
exec - Executor to run the function in.
Returns:
A future that holds result of the chain.

transform

public static <I,O> ListenableFuture<O> transform(ListenableFuture<I> future,
                                                  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);
 

Successful cancellation of the input future will cause the returned future to be cancelled. Cancelling the returned future will succeed if it is currently running. In this case, an attempt will be made to cancel the input future, however there is no guarantee of success.

An example use of this method is to convert a serializable object returned from an RPC into a POJO.

Parameters:
future - The future to compose
function - A Function to compose 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 composition.
Since:
9 (in version 1 as compose)

transform

public static <I,O> ListenableFuture<O> transform(ListenableFuture<I> future,
                                                  Function<? super I,? extends O> function,
                                                  Executor exec)
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);
 

Successful cancellation of the input future will cause the returned future to be cancelled. Cancelling the returned future will succeed if it is currently running. In this case, an attempt will be made to cancel the input future, however there is no guarantee of success.

An example use of this method is to convert a serializable object returned from an RPC into a POJO.

This version allows an arbitrary executor to be passed in for running the chained Function. When using MoreExecutors.sameThreadExecutor(), the thread chained Function executes in will be whichever thread set the result of the input Future, which may be the network thread in the case of RPC-based Futures.

Parameters:
future - The future to compose
function - A Function to compose the results of the provided future to the results of the returned future.
exec - Executor to run the function in.
Returns:
A future that holds result of the composition.
Since:
9 (in version 2 as compose)

transform

public static <I,O> Future<O> transform(Future<I> future,
                                        Function<? super I,? extends O> function)
Returns a new Future whose result is the product of applying the given Function to the result of the given Future. Example:
   Future<QueryResult> queryFuture = ...;
   Function<QueryResult, List<Row>> rowsFunction =
       new Function<QueryResult, List<Row>>() {
         public List<Row> apply(QueryResult queryResult) {
           return queryResult.getRows();
         }
       };
   Future<List<Row>> rowsFuture = transform(queryFuture, rowsFunction);
 

Each call to Future<O>.get(*) results in a call to Future<I>.get(*), but function is only applied once, so it is assumed that Future<I>.get(*) is idempotent.

When calling Future.get(long, TimeUnit) on the returned future, the timeout only applies to the future passed in to this method. Any additional time taken by applying function is not considered. (Exception: If the input future is a ListenableFuture, timeouts will be strictly enforced.)

Parameters:
future - The future to compose
function - A Function to compose the results of the provided future to the results of the returned future. This will be run in the thread that calls one of the varieties of get().
Returns:
A future that computes result of the composition.
Since:
9 (in version 1 as compose)