001/*
002 * Copyright (C) 2006 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.util.concurrent;
016
017import com.google.common.annotations.Beta;
018import com.google.common.annotations.GwtCompatible;
019import com.google.common.annotations.GwtIncompatible;
020import com.google.common.base.Function;
021import java.util.concurrent.ExecutionException;
022import java.util.concurrent.Executor;
023import java.util.concurrent.ScheduledExecutorService;
024import java.util.concurrent.TimeUnit;
025import java.util.concurrent.TimeoutException;
026
027/**
028 * A {@link ListenableFuture} that supports fluent chains of operations. For example:
029 *
030 * <pre>{@code
031 * ListenableFuture<Boolean> adminIsLoggedIn =
032 *     FluentFuture.from(usersDatabase.getAdminUser())
033 *         .transform(User::getId, directExecutor())
034 *         .transform(ActivityService::isLoggedIn, threadPool)
035 *         .catching(RpcException.class, e -> false, directExecutor());
036 * }</pre>
037 *
038 * <h3>Alternatives</h3>
039 *
040 * <h4>Frameworks</h4>
041 *
042 * <p>When chaining together a graph of asynchronous operations, you will often find it easier to
043 * use a framework. Frameworks automate the process, often adding features like monitoring,
044 * debugging, and cancellation. Examples of frameworks include:
045 *
046 * <ul>
047 *   <li><a href="http://google.github.io/dagger/producers.html">Dagger Producers</a>
048 * </ul>
049 *
050 * <h4>{@link java.util.concurrent.CompletableFuture} / {@link java.util.concurrent.CompletionStage}
051 * </h4>
052 *
053 * <p>Users of {@code CompletableFuture} will likely want to continue using {@code
054 * CompletableFuture}. {@code FluentFuture} is targeted at people who use {@code ListenableFuture},
055 * who can't use Java 8, or who want an API more focused than {@code CompletableFuture}. (If you
056 * need to adapt between {@code CompletableFuture} and {@code ListenableFuture}, consider <a
057 * href="https://github.com/lukas-krecan/future-converter">Future Converter</a>.)
058 *
059 * <h3>Extension</h3>
060 *
061 * If you want a class like {@code FluentFuture} but with extra methods, we recommend declaring your
062 * own subclass of {@link ListenableFuture}, complete with a method like {@link #from} to adapt an
063 * existing {@code ListenableFuture}, implemented atop a {@link ForwardingListenableFuture} that
064 * forwards to that future and adds the desired methods.
065 *
066 * @since 23.0
067 */
068@Beta
069@GwtCompatible(emulated = true)
070public abstract class FluentFuture<V> extends GwtFluentFutureCatchingSpecialization<V> {
071  FluentFuture() {}
072
073  /**
074   * Converts the given {@code ListenableFuture} to an equivalent {@code FluentFuture}.
075   *
076   * <p>If the given {@code ListenableFuture} is already a {@code FluentFuture}, it is returned
077   * directly. If not, it is wrapped in a {@code FluentFuture} that delegates all calls to the
078   * original {@code ListenableFuture}.
079   */
080  public static <V> FluentFuture<V> from(ListenableFuture<V> future) {
081    return future instanceof FluentFuture
082        ? (FluentFuture<V>) future
083        : new ForwardingFluentFuture<V>(future);
084  }
085
086  /**
087   * Returns a {@code Future} whose result is taken from this {@code Future} or, if this {@code
088   * Future} fails with the given {@code exceptionType}, from the result provided by the {@code
089   * fallback}. {@link Function#apply} is not invoked until the primary input has failed, so if the
090   * primary input succeeds, it is never invoked. If, during the invocation of {@code fallback}, an
091   * exception is thrown, this exception is used as the result of the output {@code Future}.
092   *
093   * <p>Usage example:
094   *
095   * <pre>{@code
096   * // Falling back to a zero counter in case an exception happens when processing the RPC to fetch
097   * // counters.
098   * ListenableFuture<Integer> faultTolerantFuture =
099   *     fetchCounters().catching(FetchException.class, x -> 0, directExecutor());
100   * }</pre>
101   *
102   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
103   * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight
104   * listeners are also applicable to heavyweight functions passed to this method.
105   *
106   * <p>This method is similar to {@link java.util.concurrent.CompletableFuture#exceptionally}. It
107   * can also serve some of the use cases of {@link java.util.concurrent.CompletableFuture#handle}
108   * and {@link java.util.concurrent.CompletableFuture#handleAsync} when used along with {@link
109   * #transform}.
110   *
111   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
112   *     type is matched against the input's exception. "The input's exception" means the cause of
113   *     the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
114   *     different kind of exception, that exception itself. To avoid hiding bugs and other
115   *     unrecoverable errors, callers should prefer more specific types, avoiding {@code
116   *     Throwable.class} in particular.
117   * @param fallback the {@link Function} to be called if the input fails with the expected
118   *     exception type. The function's argument is the input's exception. "The input's exception"
119   *     means the cause of the {@link ExecutionException} thrown by {@code this.get()} or, if
120   *     {@code get()} throws a different kind of exception, that exception itself.
121   * @param executor the executor that runs {@code fallback} if the input fails
122   */
123  @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
124  public final <X extends Throwable> FluentFuture<V> catching(
125      Class<X> exceptionType, Function<? super X, ? extends V> fallback, Executor executor) {
126    return (FluentFuture<V>) Futures.catching(this, exceptionType, fallback, executor);
127  }
128
129  /**
130   * Returns a {@code Future} whose result is taken from this {@code Future} or, if the this {@code
131   * Future} fails with the given {@code exceptionType}, from the result provided by the {@code
132   * fallback}. {@link AsyncFunction#apply} is not invoked until the primary input has failed, so if
133   * the primary input succeeds, it is never invoked. If, during the invocation of {@code fallback},
134   * an exception is thrown, this exception is used as the result of the output {@code Future}.
135   *
136   * <p>Usage examples:
137   *
138   * <pre>{@code
139   * // Falling back to a zero counter in case an exception happens when processing the RPC to fetch
140   * // counters.
141   * ListenableFuture<Integer> faultTolerantFuture =
142   *     fetchCounters().catchingAsync(
143   *         FetchException.class, x -> immediateFuture(0), directExecutor());
144   * }</pre>
145   *
146   * <p>The fallback can also choose to propagate the original exception when desired:
147   *
148   * <pre>{@code
149   * // Falling back to a zero counter only in case the exception was a
150   * // TimeoutException.
151   * ListenableFuture<Integer> faultTolerantFuture =
152   *     fetchCounters().catchingAsync(
153   *         fetchCounterFuture,
154   *         FetchException.class,
155   *         e -> {
156   *           if (omitDataOnFetchFailure) {
157   *             return immediateFuture(0);
158   *           }
159   *           throw e;
160   *         },
161   *         directExecutor());
162   * }</pre>
163   *
164   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
165   * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight
166   * listeners are also applicable to heavyweight functions passed to this method. (Specifically,
167   * {@code directExecutor} functions should avoid heavyweight operations inside {@code
168   * AsyncFunction.apply}. Any heavyweight operations should occur in other threads responsible for
169   * completing the returned {@code Future}.)
170   *
171   * <p>This method is similar to {@link java.util.concurrent.CompletableFuture#exceptionally}. It
172   * can also serve some of the use cases of {@link java.util.concurrent.CompletableFuture#handle}
173   * and {@link java.util.concurrent.CompletableFuture#handleAsync} when used along with {@link
174   * #transform}.
175   *
176   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
177   *     type is matched against the input's exception. "The input's exception" means the cause of
178   *     the {@link ExecutionException} thrown by {@code this.get()} or, if {@code get()} throws a
179   *     different kind of exception, that exception itself. To avoid hiding bugs and other
180   *     unrecoverable errors, callers should prefer more specific types, avoiding {@code
181   *     Throwable.class} in particular.
182   * @param fallback the {@link AsyncFunction} to be called if the input fails with the expected
183   *     exception type. The function's argument is the input's exception. "The input's exception"
184   *     means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
185   *     {@code get()} throws a different kind of exception, that exception itself.
186   * @param executor the executor that runs {@code fallback} if the input fails
187   */
188  @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
189  public final <X extends Throwable> FluentFuture<V> catchingAsync(
190      Class<X> exceptionType, AsyncFunction<? super X, ? extends V> fallback, Executor executor) {
191    return (FluentFuture<V>) Futures.catchingAsync(this, exceptionType, fallback, executor);
192  }
193
194  /**
195   * Returns a future that delegates to this future but will finish early (via a {@link
196   * TimeoutException} wrapped in an {@link ExecutionException}) if the specified timeout expires.
197   * If the timeout expires, not only will the output future finish, but also the input future
198   * ({@code this}) will be cancelled and interrupted.
199   *
200   * @param timeout when to time out the future
201   * @param unit the time unit of the time parameter
202   * @param scheduledExecutor The executor service to enforce the timeout.
203   */
204  @GwtIncompatible // ScheduledExecutorService
205  public final FluentFuture<V> withTimeout(
206      long timeout, TimeUnit unit, ScheduledExecutorService scheduledExecutor) {
207    return (FluentFuture<V>) Futures.withTimeout(this, timeout, unit, scheduledExecutor);
208  }
209
210  /**
211   * Returns a new {@code Future} whose result is asynchronously derived from the result of this
212   * {@code Future}. If the input {@code Future} fails, the returned {@code Future} fails with the
213   * same exception (and the function is not invoked).
214   *
215   * <p>More precisely, the returned {@code Future} takes its result from a {@code Future} produced
216   * by applying the given {@code AsyncFunction} to the result of the original {@code Future}.
217   * Example usage:
218   *
219   * <pre>{@code
220   * FluentFuture<RowKey> rowKeyFuture = FluentFuture.from(indexService.lookUp(query));
221   * ListenableFuture<QueryResult> queryFuture =
222   *     rowKeyFuture.transformAsync(dataService::readFuture, executor);
223   * }</pre>
224   *
225   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
226   * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight
227   * listeners are also applicable to heavyweight functions passed to this method. (Specifically,
228   * {@code directExecutor} functions should avoid heavyweight operations inside {@code
229   * AsyncFunction.apply}. Any heavyweight operations should occur in other threads responsible for
230   * completing the returned {@code Future}.)
231   *
232   * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
233   * input future and that of the future returned by the chain function. That is, if the returned
234   * {@code Future} is cancelled, it will attempt to cancel the other two, and if either of the
235   * other two is cancelled, the returned {@code Future} will receive a callback in which it will
236   * attempt to cancel itself.
237   *
238   * <p>This method is similar to {@link java.util.concurrent.CompletableFuture#thenCompose} and
239   * {@link java.util.concurrent.CompletableFuture#thenComposeAsync}. It can also serve some of the
240   * use cases of {@link java.util.concurrent.CompletableFuture#handle} and {@link
241   * java.util.concurrent.CompletableFuture#handleAsync} when used along with {@link #catching}.
242   *
243   * @param function A function to transform the result of this future to the result of the output
244   *     future
245   * @param executor Executor to run the function in.
246   * @return A future that holds result of the function (if the input succeeded) or the original
247   *     input's failure (if not)
248   */
249  public final <T> FluentFuture<T> transformAsync(
250      AsyncFunction<? super V, T> function, Executor executor) {
251    return (FluentFuture<T>) Futures.transformAsync(this, function, executor);
252  }
253
254  /**
255   * Returns a new {@code Future} whose result is derived from the result of this {@code Future}. If
256   * this input {@code Future} fails, the returned {@code Future} fails with the same exception (and
257   * the function is not invoked). Example usage:
258   *
259   * <pre>{@code
260   * ListenableFuture<List<Row>> rowsFuture =
261   *     queryFuture.transform(QueryResult::getRows, executor);
262   * }</pre>
263   *
264   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
265   * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight
266   * listeners are also applicable to heavyweight functions passed to this method.
267   *
268   * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
269   * input future. That is, if the returned {@code Future} is cancelled, it will attempt to cancel
270   * the input, and if the input is cancelled, the returned {@code Future} will receive a callback
271   * in which it will attempt to cancel itself.
272   *
273   * <p>An example use of this method is to convert a serializable object returned from an RPC into
274   * a POJO.
275   *
276   * <p>This method is similar to {@link java.util.concurrent.CompletableFuture#thenApply} and
277   * {@link java.util.concurrent.CompletableFuture#thenApplyAsync}. It can also serve some of the
278   * use cases of {@link java.util.concurrent.CompletableFuture#handle} and {@link
279   * java.util.concurrent.CompletableFuture#handleAsync} when used along with {@link #catching}.
280   *
281   * @param function A Function to transform the results of this future to the results of the
282   *     returned future.
283   * @param executor Executor to run the function in.
284   * @return A future that holds result of the transformation.
285   */
286  public final <T> FluentFuture<T> transform(Function<? super V, T> function, Executor executor) {
287    return (FluentFuture<T>) Futures.transform(this, function, executor);
288  }
289
290  /**
291   * Registers separate success and failure callbacks to be run when this {@code Future}'s
292   * computation is {@linkplain java.util.concurrent.Future#isDone() complete} or, if the
293   * computation is already complete, immediately.
294   *
295   * <p>The callback is run on {@code executor}. There is no guaranteed ordering of execution of
296   * callbacks, but any callback added through this method is guaranteed to be called once the
297   * computation is complete.
298   *
299   * <p>Example:
300   *
301   * <pre>{@code
302   * future.addCallback(
303   *     new FutureCallback<QueryResult>() {
304   *       public void onSuccess(QueryResult result) {
305   *         storeInCache(result);
306   *       }
307   *       public void onFailure(Throwable t) {
308   *         reportError(t);
309   *       }
310   *     }, executor);
311   * }</pre>
312   *
313   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
314   * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight
315   * listeners are also applicable to heavyweight callbacks passed to this method.
316   *
317   * <p>For a more general interface to attach a completion listener, see {@link #addListener}.
318   *
319   * <p>This method is similar to {@link java.util.concurrent.CompletableFuture#whenComplete} and
320   * {@link java.util.concurrent.CompletableFuture#whenCompleteAsync}. It also serves the use case
321   * of {@link java.util.concurrent.CompletableFuture#thenAccept} and {@link
322   * java.util.concurrent.CompletableFuture#thenAcceptAsync}.
323   *
324   * @param callback The callback to invoke when this {@code Future} is completed.
325   * @param executor The executor to run {@code callback} when the future completes.
326   */
327  public final void addCallback(FutureCallback<? super V> callback, Executor executor) {
328    Futures.addCallback(this, callback, executor);
329  }
330}