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 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 * FetchException.class, 154 * e -> { 155 * if (omitDataOnFetchFailure) { 156 * return immediateFuture(0); 157 * } 158 * throw e; 159 * }, 160 * directExecutor()); 161 * }</pre> 162 * 163 * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See 164 * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight 165 * listeners are also applicable to heavyweight functions passed to this method. (Specifically, 166 * {@code directExecutor} functions should avoid heavyweight operations inside {@code 167 * AsyncFunction.apply}. Any heavyweight operations should occur in other threads responsible for 168 * completing the returned {@code Future}.) 169 * 170 * <p>This method is similar to {@link java.util.concurrent.CompletableFuture#exceptionally}. It 171 * can also serve some of the use cases of {@link java.util.concurrent.CompletableFuture#handle} 172 * and {@link java.util.concurrent.CompletableFuture#handleAsync} when used along with {@link 173 * #transform}. 174 * 175 * @param exceptionType the exception type that triggers use of {@code fallback}. The exception 176 * type is matched against the input's exception. "The input's exception" means the cause of 177 * the {@link ExecutionException} thrown by {@code this.get()} or, if {@code get()} throws a 178 * different kind of exception, that exception itself. To avoid hiding bugs and other 179 * unrecoverable errors, callers should prefer more specific types, avoiding {@code 180 * Throwable.class} in particular. 181 * @param fallback the {@link AsyncFunction} to be called if the input fails with the expected 182 * exception type. The function's argument is the input's exception. "The input's exception" 183 * means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if 184 * {@code get()} throws a different kind of exception, that exception itself. 185 * @param executor the executor that runs {@code fallback} if the input fails 186 */ 187 @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class") 188 public final <X extends Throwable> FluentFuture<V> catchingAsync( 189 Class<X> exceptionType, AsyncFunction<? super X, ? extends V> fallback, Executor executor) { 190 return (FluentFuture<V>) Futures.catchingAsync(this, exceptionType, fallback, executor); 191 } 192 193 /** 194 * Returns a future that delegates to this future but will finish early (via a {@link 195 * TimeoutException} wrapped in an {@link ExecutionException}) if the specified timeout expires. 196 * If the timeout expires, not only will the output future finish, but also the input future 197 * ({@code this}) will be cancelled and interrupted. 198 * 199 * @param timeout when to time out the future 200 * @param unit the time unit of the time parameter 201 * @param scheduledExecutor The executor service to enforce the timeout. 202 */ 203 @GwtIncompatible // ScheduledExecutorService 204 public final FluentFuture<V> withTimeout( 205 long timeout, TimeUnit unit, ScheduledExecutorService scheduledExecutor) { 206 return (FluentFuture<V>) Futures.withTimeout(this, timeout, unit, scheduledExecutor); 207 } 208 209 /** 210 * Returns a new {@code Future} whose result is asynchronously derived from the result of this 211 * {@code Future}. If the input {@code Future} fails, the returned {@code Future} fails with the 212 * same exception (and the function is not invoked). 213 * 214 * <p>More precisely, the returned {@code Future} takes its result from a {@code Future} produced 215 * by applying the given {@code AsyncFunction} to the result of the original {@code Future}. 216 * Example usage: 217 * 218 * <pre>{@code 219 * FluentFuture<RowKey> rowKeyFuture = FluentFuture.from(indexService.lookUp(query)); 220 * ListenableFuture<QueryResult> queryFuture = 221 * rowKeyFuture.transformAsync(dataService::readFuture, executor); 222 * }</pre> 223 * 224 * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See 225 * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight 226 * listeners are also applicable to heavyweight functions passed to this method. (Specifically, 227 * {@code directExecutor} functions should avoid heavyweight operations inside {@code 228 * AsyncFunction.apply}. Any heavyweight operations should occur in other threads responsible for 229 * completing the returned {@code Future}.) 230 * 231 * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the 232 * input future and that of the future returned by the chain function. That is, if the returned 233 * {@code Future} is cancelled, it will attempt to cancel the other two, and if either of the 234 * other two is cancelled, the returned {@code Future} will receive a callback in which it will 235 * attempt to cancel itself. 236 * 237 * <p>This method is similar to {@link java.util.concurrent.CompletableFuture#thenCompose} and 238 * {@link java.util.concurrent.CompletableFuture#thenComposeAsync}. It can also serve some of the 239 * use cases of {@link java.util.concurrent.CompletableFuture#handle} and {@link 240 * java.util.concurrent.CompletableFuture#handleAsync} when used along with {@link #catching}. 241 * 242 * @param function A function to transform the result of this future to the result of the output 243 * future 244 * @param executor Executor to run the function in. 245 * @return A future that holds result of the function (if the input succeeded) or the original 246 * input's failure (if not) 247 */ 248 public final <T> FluentFuture<T> transformAsync( 249 AsyncFunction<? super V, T> function, Executor executor) { 250 return (FluentFuture<T>) Futures.transformAsync(this, function, executor); 251 } 252 253 /** 254 * Returns a new {@code Future} whose result is derived from the result of this {@code Future}. If 255 * this input {@code Future} fails, the returned {@code Future} fails with the same exception (and 256 * the function is not invoked). Example usage: 257 * 258 * <pre>{@code 259 * ListenableFuture<List<Row>> rowsFuture = 260 * queryFuture.transform(QueryResult::getRows, executor); 261 * }</pre> 262 * 263 * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See 264 * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight 265 * listeners are also applicable to heavyweight functions passed to this method. 266 * 267 * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the 268 * input future. That is, if the returned {@code Future} is cancelled, it will attempt to cancel 269 * the input, and if the input is cancelled, the returned {@code Future} will receive a callback 270 * in which it will attempt to cancel itself. 271 * 272 * <p>An example use of this method is to convert a serializable object returned from an RPC into 273 * a POJO. 274 * 275 * <p>This method is similar to {@link java.util.concurrent.CompletableFuture#thenApply} and 276 * {@link java.util.concurrent.CompletableFuture#thenApplyAsync}. It can also serve some of the 277 * use cases of {@link java.util.concurrent.CompletableFuture#handle} and {@link 278 * java.util.concurrent.CompletableFuture#handleAsync} when used along with {@link #catching}. 279 * 280 * @param function A Function to transform the results of this future to the results of the 281 * returned future. 282 * @param executor Executor to run the function in. 283 * @return A future that holds result of the transformation. 284 */ 285 public final <T> FluentFuture<T> transform(Function<? super V, T> function, Executor executor) { 286 return (FluentFuture<T>) Futures.transform(this, function, executor); 287 } 288 289 /** 290 * Registers separate success and failure callbacks to be run when this {@code Future}'s 291 * computation is {@linkplain java.util.concurrent.Future#isDone() complete} or, if the 292 * computation is already complete, immediately. 293 * 294 * <p>The callback is run on {@code executor}. There is no guaranteed ordering of execution of 295 * callbacks, but any callback added through this method is guaranteed to be called once the 296 * computation is complete. 297 * 298 * <p>Example: 299 * 300 * <pre>{@code 301 * future.addCallback( 302 * new FutureCallback<QueryResult>() { 303 * public void onSuccess(QueryResult result) { 304 * storeInCache(result); 305 * } 306 * public void onFailure(Throwable t) { 307 * reportError(t); 308 * } 309 * }, executor); 310 * }</pre> 311 * 312 * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See 313 * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight 314 * listeners are also applicable to heavyweight callbacks passed to this method. 315 * 316 * <p>For a more general interface to attach a completion listener, see {@link #addListener}. 317 * 318 * <p>This method is similar to {@link java.util.concurrent.CompletableFuture#whenComplete} and 319 * {@link java.util.concurrent.CompletableFuture#whenCompleteAsync}. It also serves the use case 320 * of {@link java.util.concurrent.CompletableFuture#thenAccept} and {@link 321 * java.util.concurrent.CompletableFuture#thenAcceptAsync}. 322 * 323 * @param callback The callback to invoke when this {@code Future} is completed. 324 * @param executor The executor to run {@code callback} when the future completes. 325 */ 326 public final void addCallback(FutureCallback<? super V> callback, Executor executor) { 327 Futures.addCallback(this, callback, executor); 328 } 329}