Top Description Inners Constructors Methods
com.google.common.util.concurrent

public abstract Class FluentFuture<V extends @Nullable Object>

extends GwtFluentFutureCatchingSpecialization<V extends @Nullable Object>
Class Inheritance
Known Direct Subclasses
com.google.common.util.concurrent.FluentFuture.TrustedFuture, com.google.common.util.concurrent.ForwardingFluentFuture
Annotations
@DoNotMock:Use FluentFuture.from(Futures.immediate*Future) or SettableFuture
@GwtCompatible
emulated:true
@ElementTypesAreNonnullByDefault
Static Imports
com.google.common.base.Preconditions.checkNotNull, com.google.common.util.concurrent.Internal.toNanosSaturated

A ListenableFuture that supports fluent chains of operations. For example:
ListenableFuture<Boolean> adminIsLoggedIn =
    FluentFuture.from(usersDatabase.getAdminUser())
        .transform(User::getId, directExecutor())
        .transform(ActivityService::isLoggedIn, threadPool)
        .catching(RpcException.class, e -> false, directExecutor());

Alternatives

Frameworks

When chaining together a graph of asynchronous operations, you will often find it easier to use a framework. Frameworks automate the process, often adding features like monitoring, debugging, and cancellation. Examples of frameworks include:

java.util.concurrent.CompletableFuture / java.util.concurrent.CompletionStage

Users of CompletableFuture will likely want to continue using CompletableFuture. FluentFuture is targeted at people who use ListenableFuture, who can't use Java 8, or who want an API more focused than CompletableFuture. (If you need to adapt between CompletableFuture and ListenableFuture, consider Future Converter.)

Extension

If you want a class like FluentFuture but with extra methods, we recommend declaring your own subclass of ListenableFuture, complete with a method like from to adapt an existing ListenableFuture, implemented atop a ForwardingListenableFuture that forwards to that future and adds the desired methods.
Since
23.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv abstract static class
FluentFuture.TrustedFuture<V extends @Nullable Object>

A less abstract subclass of AbstractFuture.

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public final void
addCallback(FutureCallback<? super V>
The callback to invoke when this Future is completed.
callback
,
Executor
The executor to run callback when the future completes.
executor
)

Registers separate success and failure callbacks to be run when this Future's computation is complete or, if the computation is already complete, immediately.

public final <X extends Throwable> FluentFuture<V>
catching(Class<X>
the exception type that triggers use of fallback. The exception type is matched against the input's exception. "The input's exception" means the cause of the ExecutionException thrown by input.get() or, if get() throws a different kind of exception, that exception itself. To avoid hiding bugs and other unrecoverable errors, callers should prefer more specific types, avoiding Throwable.class in particular.
exceptionType
,
Function<? super X, ? extends V>
the Function to be called if the input fails with the expected exception type. The function's argument is the input's exception. "The input's exception" means the cause of the ExecutionException thrown by this.get() or, if get() throws a different kind of exception, that exception itself.
fallback
,
Executor
the executor that runs fallback if the input fails
executor
)

Returns a Future whose result is taken from this Future or, if this Future fails with the given exceptionType, from the result provided by the fallback.

public final <X extends Throwable> FluentFuture<V>
catchingAsync(Class<X>
the exception type that triggers use of fallback. The exception type is matched against the input's exception. "The input's exception" means the cause of the ExecutionException thrown by this.get() or, if get() throws a different kind of exception, that exception itself. To avoid hiding bugs and other unrecoverable errors, callers should prefer more specific types, avoiding Throwable.class in particular.
exceptionType
,
AsyncFunction<? super X, ? extends V>
the AsyncFunction to be called if the input fails with the expected exception type. The function's argument is the input's exception. "The input's exception" means the cause of the ExecutionException thrown by input.get() or, if get() throws a different kind of exception, that exception itself.
fallback
,
Executor
the executor that runs fallback if the input fails
executor
)

Returns a Future whose result is taken from this Future or, if this Future fails with the given exceptionType, from the result provided by the fallback.

public static <V extends @Nullable Object> FluentFuture<V>
from(ListenableFuture<V> future)

Converts the given ListenableFuture to an equivalent FluentFuture.

public static <V extends @Nullable Object> FluentFuture<V>
from(FluentFuture<V> future)

Deprecated no need to use this
Simply returns its argument.
public final <T extends @Nullable Object> FluentFuture<T>

Returns:

A future that holds result of the transformation.
transform
(Function<? super V, T>
A Function to transform the results of this future to the results of the returned future.
function
,
Executor
Executor to run the function in.
executor
)

Returns a new Future whose result is derived from the result of this Future.

public final <T extends @Nullable Object> FluentFuture<T>

Returns:

A future that holds result of the function (if the input succeeded) or the original input's failure (if not)
transformAsync
(AsyncFunction<? super V, T>
A function to transform the result of this future to the result of the output future
function
,
Executor
Executor to run the function in.
executor
)

Returns a new Future whose result is asynchronously derived from the result of this Future.

public final FluentFuture<V>
withTimeout(Duration
when to time out the future
timeout
,
ScheduledExecutorService
The executor service to enforce the timeout.
scheduledExecutor
)

Returns a future that delegates to this future but will finish early (via a TimeoutException wrapped in an ExecutionException) if the specified timeout expires.

public final FluentFuture<V>
withTimeout(long
when to time out the future
timeout
,
TimeUnit
the time unit of the time parameter
unit
,
ScheduledExecutorService
The executor service to enforce the timeout.
scheduledExecutor
)

Returns a future that delegates to this future but will finish early (via a TimeoutException wrapped in an ExecutionException) if the specified timeout expires.

Constructor Detail

FluentFutureback to summary
pack-priv FluentFuture()

Method Detail

addCallbackback to summary
public final void addCallback(FutureCallback<? super V> callback, Executor executor)

Registers separate success and failure callbacks to be run when this Future's computation is complete or, if the computation is already complete, immediately.

The callback is run on executor. There is no guaranteed ordering of execution of callbacks, but any callback added through this method is guaranteed to be called once the computation is complete.

Example:

future.addCallback(
    new FutureCallback<QueryResult>() {
      public void onSuccess(QueryResult result) {
        storeInCache(result);
      }
      public void onFailure(Throwable t) {
        reportError(t);
      }
    }, executor);

When selecting an executor, note that directExecutor is dangerous in some cases. See the discussion in the addListener documentation. All its warnings about heavyweight listeners are also applicable to heavyweight callbacks passed to this method.

For a more general interface to attach a completion listener, see addListener.

This method is similar to java.util.concurrent.CompletableFuture#whenComplete and java.util.concurrent.CompletableFuture#whenCompleteAsync. It also serves the use case of java.util.concurrent.CompletableFuture#thenAccept and java.util.concurrent.CompletableFuture#thenAcceptAsync.

Parameters
callback:FutureCallback<? super V>

The callback to invoke when this Future is completed.

executor:Executor

The executor to run callback when the future completes.

catchingback to summary
public final <X extends Throwable> FluentFuture<V> catching(Class<X> exceptionType, Function<? super X, ? extends V> fallback, Executor executor)

Returns a Future whose result is taken from this Future or, if this Future fails with the given exceptionType, from the result provided by the fallback. Function#apply 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:

// Falling back to a zero counter in case an exception happens when processing the RPC to fetch
// counters.
ListenableFuture<Integer> faultTolerantFuture =
    fetchCounters().catching(FetchException.class, x -> 0, directExecutor());

When selecting an executor, note that directExecutor is dangerous in some cases. See the discussion in the addListener documentation. All its warnings about heavyweight listeners are also applicable to heavyweight functions passed to this method.

This method is similar to java.util.concurrent.CompletableFuture#exceptionally. It can also serve some of the use cases of java.util.concurrent.CompletableFuture#handle and java.util.concurrent.CompletableFuture#handleAsync when used along with transform.

Parameters
exceptionType:Class<X>

the exception type that triggers use of fallback. The exception type is matched against the input's exception. "The input's exception" means the cause of the ExecutionException thrown by input.get() or, if get() throws a different kind of exception, that exception itself. To avoid hiding bugs and other unrecoverable errors, callers should prefer more specific types, avoiding Throwable.class in particular.

fallback:Function<? super X, ? extends V>

the Function to be called if the input fails with the expected exception type. The function's argument is the input's exception. "The input's exception" means the cause of the ExecutionException thrown by this.get() or, if get() throws a different kind of exception, that exception itself.

executor:Executor

the executor that runs fallback if the input fails

Annotations
@J2ktIncompatible
@GwtIncompatible:AVAILABLE but requires exceptionType to be Throwable.class
catchingAsyncback to summary
public final <X extends Throwable> FluentFuture<V> catchingAsync(Class<X> exceptionType, AsyncFunction<? super X, ? extends V> fallback, Executor executor)

Returns a Future whose result is taken from this Future or, if this Future fails with the given exceptionType, from the result provided by the fallback. AsyncFunction#apply 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:

// Falling back to a zero counter in case an exception happens when processing the RPC to fetch
// counters.
ListenableFuture<Integer> faultTolerantFuture =
    fetchCounters().catchingAsync(
        FetchException.class, x -> immediateFuture(0), directExecutor());

The fallback can also choose to propagate the original exception when desired:

// Falling back to a zero counter only in case the exception was a
// TimeoutException.
ListenableFuture<Integer> faultTolerantFuture =
    fetchCounters().catchingAsync(
        FetchException.class,
        e -> {
          if (omitDataOnFetchFailure) {
            return immediateFuture(0);
          }
          throw e;
        },
        directExecutor());

When selecting an executor, note that directExecutor is dangerous in some cases. See the discussion in the addListener documentation. All its warnings about heavyweight listeners are also applicable to heavyweight functions passed to this method. (Specifically, directExecutor functions should avoid heavyweight operations inside AsyncFunction.apply. Any heavyweight operations should occur in other threads responsible for completing the returned Future.)

This method is similar to java.util.concurrent.CompletableFuture#exceptionally. It can also serve some of the use cases of java.util.concurrent.CompletableFuture#handle and java.util.concurrent.CompletableFuture#handleAsync when used along with transform.

Parameters
exceptionType:Class<X>

the exception type that triggers use of fallback. The exception type is matched against the input's exception. "The input's exception" means the cause of the ExecutionException thrown by this.get() or, if get() throws a different kind of exception, that exception itself. To avoid hiding bugs and other unrecoverable errors, callers should prefer more specific types, avoiding Throwable.class in particular.

fallback:AsyncFunction<? super X, ? extends V>

the AsyncFunction to be called if the input fails with the expected exception type. The function's argument is the input's exception. "The input's exception" means the cause of the ExecutionException thrown by input.get() or, if get() throws a different kind of exception, that exception itself.

executor:Executor

the executor that runs fallback if the input fails

Annotations
@J2ktIncompatible
@GwtIncompatible:AVAILABLE but requires exceptionType to be Throwable.class
fromback to summary
public static <V extends @Nullable Object> FluentFuture<V> from(ListenableFuture<V> future)

Converts the given ListenableFuture to an equivalent FluentFuture.

If the given ListenableFuture is already a FluentFuture, it is returned directly. If not, it is wrapped in a FluentFuture that delegates all calls to the original ListenableFuture.

fromback to summary
public static <V extends @Nullable Object> FluentFuture<V> from(FluentFuture<V> future)

Deprecated

no need to use this

Simply returns its argument.

Annotations
@Deprecated
Since
28.0
transformback to summary
public final <T extends @Nullable Object> FluentFuture<T> transform(Function<? super V, T> function, Executor executor)

Returns a new Future whose result is derived from the result of this Future. If this input Future fails, the returned Future fails with the same exception (and the function is not invoked). Example usage:

ListenableFuture<List<Row>> rowsFuture =
    queryFuture.transform(QueryResult::getRows, executor);

When selecting an executor, note that directExecutor is dangerous in some cases. See the discussion in the addListener documentation. All its warnings about heavyweight listeners are also applicable to heavyweight functions passed to this method.

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.

This method is similar to java.util.concurrent.CompletableFuture#thenApply and java.util.concurrent.CompletableFuture#thenApplyAsync. It can also serve some of the use cases of java.util.concurrent.CompletableFuture#handle and java.util.concurrent.CompletableFuture#handleAsync when used along with catching.

Parameters
function:Function<? super V, T>

A Function to transform the results of this future to the results of the returned future.

executor:Executor

Executor to run the function in.

Returns:FluentFuture<T>

A future that holds result of the transformation.

transformAsyncback to summary
public final <T extends @Nullable Object> FluentFuture<T> transformAsync(AsyncFunction<? super V, T> function, Executor executor)

Returns a new Future whose result is asynchronously derived from the result of this Future. If the input Future fails, the returned Future fails with the same exception (and the function is not invoked).

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 usage:

FluentFuture<RowKey> rowKeyFuture = FluentFuture.from(indexService.lookUp(query));
ListenableFuture<QueryResult> queryFuture =
    rowKeyFuture.transformAsync(dataService::readFuture, executor);

When selecting an executor, note that directExecutor is dangerous in some cases. See the discussion in the addListener documentation. All its warnings about heavyweight listeners are also applicable to heavyweight functions passed to this method. (Specifically, directExecutor functions should avoid heavyweight operations inside AsyncFunction.apply. Any heavyweight operations should occur in other threads responsible for completing 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.

This method is similar to java.util.concurrent.CompletableFuture#thenCompose and java.util.concurrent.CompletableFuture#thenComposeAsync. It can also serve some of the use cases of java.util.concurrent.CompletableFuture#handle and java.util.concurrent.CompletableFuture#handleAsync when used along with catching.

Parameters
function:AsyncFunction<? super V, T>

A function to transform the result of this future to the result of the output future

executor:Executor

Executor to run the function in.

Returns:FluentFuture<T>

A future that holds result of the function (if the input succeeded) or the original input's failure (if not)

withTimeoutback to summary
public final FluentFuture<V> withTimeout(Duration timeout, ScheduledExecutorService scheduledExecutor)

Returns a future that delegates to this future but will finish early (via a TimeoutException wrapped in an ExecutionException) if the specified timeout expires. If the timeout expires, not only will the output future finish, but also the input future (this) will be cancelled and interrupted.

Parameters
timeout:Duration

when to time out the future

scheduledExecutor:ScheduledExecutorService

The executor service to enforce the timeout.

Annotations
@J2ktIncompatible
@GwtIncompatible
Since
28.0
withTimeoutback to summary
public final FluentFuture<V> withTimeout(long timeout, TimeUnit unit, ScheduledExecutorService scheduledExecutor)

Returns a future that delegates to this future but will finish early (via a TimeoutException wrapped in an ExecutionException) if the specified timeout expires. If the timeout expires, not only will the output future finish, but also the input future (this) will be cancelled and interrupted.

Parameters
timeout:long

when to time out the future

unit:TimeUnit

the time unit of the time parameter

scheduledExecutor:ScheduledExecutorService

The executor service to enforce the timeout.

Annotations
@J2ktIncompatible
@GwtIncompatible
@SuppressWarnings:GoodTime
com.google.common.util.concurrent back to summary

pack-priv abstract Class FluentFuture.TrustedFuture<V extends @Nullable Object>

extends FluentFuture<V extends @Nullable Object>
implements AbstractFuture.Trusted<V extends @Nullable Object>
Class Inheritance
All Implemented Interfaces
com.google.common.util.concurrent.AbstractFuture.Trusted, com.google.common.util.concurrent.ListenableFuture, java.util.concurrent.Future
Known Direct Subclasses
com.google.common.util.concurrent.TimeoutFuture, com.google.common.util.concurrent.TrustedListenableFutureTask, com.google.common.util.concurrent.AbstractCatchingFuture, com.google.common.util.concurrent.AbstractTransformFuture

A less abstract subclass of AbstractFuture. This can be used to optimize setFuture by ensuring that get calls exactly the implementation of AbstractFuture#get.

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public final void
addListener(Runnable
the listener to run when the computation is complete
listener
,
Executor
the executor to run the listener in
executor
)

Overrides com.google.common.util.concurrent.AbstractFuture.addListener.

Implements com.google.common.util.concurrent.ListenableFuture.addListener.

Registers a listener to be run on the given executor.
public final boolean
cancel(boolean
true if the thread executing this task should be interrupted (if the thread is known to the implementation); otherwise, in-progress tasks are allowed to complete
mayInterruptIfRunning
)

Overrides com.google.common.util.concurrent.AbstractFuture.cancel.

Implements java.util.concurrent.Future.cancel.

Attempts to cancel execution of this task.
public final V
get()

Overrides com.google.common.util.concurrent.AbstractFuture.get.

Implements java.util.concurrent.Future.get.

Waits if necessary for the computation to complete, and then retrieves its result.
public final V
get(long
the maximum time to wait
timeout
,
TimeUnit
the time unit of the timeout argument
unit
)

Overrides com.google.common.util.concurrent.AbstractFuture.get.

Implements java.util.concurrent.Future.get.

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.
public final boolean
isCancelled()

Overrides com.google.common.util.concurrent.AbstractFuture.isCancelled.

Implements java.util.concurrent.Future.isCancelled.

Returns true if this task was cancelled before it completed normally.
public final boolean
isDone()

Overrides com.google.common.util.concurrent.AbstractFuture.isDone.

Implements java.util.concurrent.Future.isDone.

Returns true if this task completed.
Inherited from com.google.common.util.concurrent.FluentFuture:
addCallbackcatchingcatchingAsyncfromfromtransformtransformAsyncwithTimeoutwithTimeout

Constructor Detail

TrustedFutureback to summary
pack-priv TrustedFuture()

Method Detail

addListenerback to summary
public final void addListener(Runnable listener, Executor executor)

Overrides com.google.common.util.concurrent.AbstractFuture.addListener.

Implements com.google.common.util.concurrent.ListenableFuture.addListener.

Doc from com.google.common.util.concurrent.ListenableFuture.addListener.

Registers a listener to be run on the given executor. The listener will run when the Future's computation is complete or, if the computation is already complete, immediately.

There is no guaranteed ordering of execution of listeners, but any listener added through this method is guaranteed to be called once the computation is complete.

Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown during Executor.execute (e.g., a RejectedExecutionException or an exception thrown by direct execution) will be caught and logged.

Note

If your listener is lightweight -- and will not cause stack overflow by completing more futures or adding more directExecutor() listeners inline -- consider MoreExecutors#directExecutor. Otherwise, avoid it: See the warnings on the docs for directExecutor.

This is the most general listener interface. For common operations performed using listeners, see Futures. For a simplified but general listener interface, see addCallback().

Memory consistency effects: Actions in a thread prior to adding a listener happen-before its execution begins, perhaps in another thread.

Guava implementations of ListenableFuture promptly release references to listeners after executing them.

Parameters
listener:Runnable

the listener to run when the computation is complete

executor:Executor

the executor to run the listener in

Annotations
@Override
cancelback to summary
public final boolean cancel(boolean mayInterruptIfRunning)

Overrides com.google.common.util.concurrent.AbstractFuture.cancel.

Implements java.util.concurrent.Future.cancel.

Doc from java.util.concurrent.Future.cancel.

Attempts to cancel execution of this task. This method has no effect if the task is already completed or cancelled, or could not be cancelled for some other reason. Otherwise, if this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task (when known by the implementation) is interrupted in an attempt to stop the task.

The return value from this method does not necessarily indicate whether the task is now cancelled; use isCancelled.

Parameters
mayInterruptIfRunning:boolean

true if the thread executing this task should be interrupted (if the thread is known to the implementation); otherwise, in-progress tasks are allowed to complete

Returns:boolean

false if the task could not be cancelled, typically because it has already completed; true otherwise. If two or more threads cause a task to be cancelled, then at least one of them returns true. Implementations may provide stronger guarantees.

Annotations
@CanIgnoreReturnValue
@Override
getback to summary
public final V get() throws InterruptedException, ExecutionException

Overrides com.google.common.util.concurrent.AbstractFuture.get.

Implements java.util.concurrent.Future.get.

Doc from java.util.concurrent.Future.get.

Waits if necessary for the computation to complete, and then retrieves its result.

Returns:V

the computed result

Annotations
@CanIgnoreReturnValue
@Override
@ParametricNullness
Exceptions
InterruptedException:
if the current thread was interrupted while waiting
ExecutionException:
if the computation threw an exception
getback to summary
public final V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException

Overrides com.google.common.util.concurrent.AbstractFuture.get.

Implements java.util.concurrent.Future.get.

Doc from java.util.concurrent.Future.get.

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

Parameters
timeout:long

the maximum time to wait

unit:TimeUnit

the time unit of the timeout argument

Returns:V

the computed result

Annotations
@CanIgnoreReturnValue
@Override
@ParametricNullness
Exceptions
InterruptedException:
if the current thread was interrupted while waiting
ExecutionException:
if the computation threw an exception
TimeoutException:
if the wait timed out
isCancelledback to summary
public final boolean isCancelled()

Overrides com.google.common.util.concurrent.AbstractFuture.isCancelled.

Implements java.util.concurrent.Future.isCancelled.

Doc from java.util.concurrent.Future.isCancelled.

Returns true if this task was cancelled before it completed normally.

Returns:boolean

true if this task was cancelled before it completed

Annotations
@Override
isDoneback to summary
public final boolean isDone()

Overrides com.google.common.util.concurrent.AbstractFuture.isDone.

Implements java.util.concurrent.Future.isDone.

Doc from java.util.concurrent.Future.isDone.

Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.

Returns:boolean

true if this task completed

Annotations
@Override