Class Future<T>
java.lang.Object
cloud.opencode.base.functional.async.Future<T>
- Type Parameters:
T- value type - 值类型Security | 安全性:
- Thread-safe: Yes (immutable) - 线程安全: 是(不可变)
- Null-safe: Yes (validates inputs) - 空值安全: 是(验证输入)
Future - Functional wrapper for CompletableFuture
Future - CompletableFuture 的函数式包装
A functional wrapper around CompletableFuture that provides a cleaner, more composable API with proper error handling. Similar to Vavr's Future.
CompletableFuture 的函数式包装,提供更简洁、更可组合的 API 和正确的错误处理。 类似于 Vavr 的 Future。
Features | 主要功能:
- Functional API (map, flatMap, filter) - 函数式 API
- Error handling (recover, recoverWith) - 错误处理
- Timeout support - 超时支持
- Conversion to Try/Option - 转换为 Try/Option
- Combining futures (zip, sequence, traverse) - 组合 Future
- Virtual Thread support - 虚拟线程支持
Usage Examples | 使用示例:
// Create and transform
Future<String> future = Future.of(() -> fetchData())
.map(String::toUpperCase)
.filter(s -> s.length() > 5);
// Error handling
Future<String> safe = Future.of(() -> riskyOperation())
.recover(ex -> "default value")
.recoverWith(ex -> Future.successful("backup"));
// Timeout
Future<String> withTimeout = future
.timeout(Duration.ofSeconds(5))
.recover(TimeoutException.class, _ -> "timeout fallback");
// Combine futures
Future<String> combined = Future.zip(
future1, future2, (a, b) -> a + b);
// Await result
Try<String> result = future.await();
Option<String> value = future.toOption();
// Using virtual threads
Future<String> vt = Future.ofVirtual(() -> compute());
Comparison with CompletableFuture | 与 CompletableFuture 对比:
- Cleaner API (no thenApply/thenCompose distinction) - 更简洁的 API
- Better error handling - 更好的错误处理
- Returns Try on await - 等待时返回 Try
- Immutable operations - 不可变操作
- Since:
- JDK 25, opencode-base-functional V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Method Summary
Modifier and TypeMethodDescription<R> Future<R> andThenVirtual(Function<? super T, ? extends R> action) Run action after completion on a virtual thread.await()Await the result, returning a Try.Await the result with timeout, returning a Try.static <T> Future<T> Create a failed Future with the given exception.Filter the value.static <T> Future<T> firstCompleted(Future<T>... futures) Return the first completed future.<R> Future<R> FlatMap to another Future.<R> Future<R> flatMapVirtual(Function<? super T, ? extends Future<R>> mapper) FlatMap on virtual thread.static <T> Future<T> fromCallable(Callable<T> callable) Create a Future from a callable.static <T> Future<T> Create a Future from a CompletableFuture.get()Get the value, throwing if failed.Get the value with default on failure.booleanCheck if completed.booleanCheck if failed.booleanCheck if completed successfully.<R> Future<R> Map the value to a new value.static <T> Future<T> never()Create a Future that never completes.static <T> Future<T> Create a Future from a supplier (uses ForkJoinPool).static <T> Future<T> Create a Future from a supplier with custom executor.static <T> Future<T> Create a Future from a supplier using virtual threads.onComplete(BiConsumer<? super T, ? super Throwable> action) Execute side effect on completion.Execute side effect on failure.Execute side effect on success.Provide a fallback Future on failure.Provide a fallback value on failure.Recover from specific exception type.Recover from any failure.recoverWith(Function<? super Throwable, ? extends Future<T>> recovery) Recover with another Future.Combine a list of futures into a future of list.Combine a list of futures into a future of list.static <T> Future<T> successful(T value) Create a successful Future with the given value.Apply a timeout to this Future.Apply a timeout with default value.Get the underlying CompletableFuture.toOption()Convert to Option (None on failure).toTry()Convert to Try.Transform a collection into a future of list using a mapping function.static <A,B, R> Future <R> zip(Future<A> futureA, Future<B> futureB, BiFunction<? super A, ? super B, ? extends R> zipper) Zip two futures into one.<U,R> Future <R> zipWith(Future<U> other, BiFunction<? super T, ? super U, ? extends R> zipper) Zip this future with another.
-
Method Details
-
of
-
of
-
ofVirtual
-
fromCallable
-
successful
Create a successful Future with the given value. 使用给定值创建成功的 Future。- Type Parameters:
T- value type - 值类型- Parameters:
value- the value - 值- Returns:
- successful Future - 成功的 Future
-
failed
-
fromCompletableFuture
Create a Future from a CompletableFuture. 从 CompletableFuture 创建 Future。- Type Parameters:
T- value type - 值类型- Parameters:
cf- the CompletableFuture - CompletableFuture- Returns:
- new Future - 新 Future
-
never
Create a Future that never completes. 创建永不完成的 Future。- Type Parameters:
T- value type - 值类型- Returns:
- never completing Future - 永不完成的 Future
-
map
-
flatMap
-
filter
-
onSuccess
-
onFailure
-
onComplete
Execute side effect on completion. 完成时执行副作用。- Parameters:
action- the action - 操作- Returns:
- this Future - 此 Future
-
recover
-
recover
public <E extends Throwable> Future<T> recover(Class<E> exceptionType, Function<? super E, ? extends T> recovery) Recover from specific exception type. 从特定异常类型恢复。- Type Parameters:
E- exception type - 异常类型- Parameters:
exceptionType- exception class - 异常类recovery- recovery function - 恢复函数- Returns:
- recovered Future - 恢复后的 Future
-
recoverWith
-
orElse
-
orElse
-
timeout
-
timeout
-
await
-
await
-
get
Get the value, throwing if failed. 获取值,如果失败则抛出异常。- Returns:
- the value - 值
- Throws:
CompletionException- if failed - 如果失败
-
getOrElse
-
isCompleted
public boolean isCompleted()Check if completed. 检查是否完成。- Returns:
- true if done - 如果完成返回 true
-
isSuccess
public boolean isSuccess()Check if completed successfully. 检查是否成功完成。- Returns:
- true if successful - 如果成功返回 true
-
isFailure
public boolean isFailure()Check if failed. 检查是否失败。- Returns:
- true if failed - 如果失败返回 true
-
toOption
-
toTry
-
toCompletableFuture
Get the underlying CompletableFuture. 获取底层的 CompletableFuture。- Returns:
- CompletableFuture - CompletableFuture
-
zip
public static <A,B, Future<R> zipR> (Future<A> futureA, Future<B> futureB, BiFunction<? super A, ? super B, ? extends R> zipper) Zip two futures into one. 将两个 Future 合并为一个。- Type Parameters:
A- first type - 第一个类型B- second type - 第二个类型R- result type - 结果类型- Parameters:
futureA- first future - 第一个 FuturefutureB- second future - 第二个 Futurezipper- combining function - 组合函数- Returns:
- combined Future - 组合后的 Future
-
zipWith
public <U,R> Future<R> zipWith(Future<U> other, BiFunction<? super T, ? super U, ? extends R> zipper) Zip this future with another. 将此 Future 与另一个合并。- Type Parameters:
U- other type - 其他类型R- result type - 结果类型- Parameters:
other- other future - 其他 Futurezipper- combining function - 组合函数- Returns:
- combined Future - 组合后的 Future
-
sequence
Combine a list of futures into a future of list. 将 Future 列表组合为列表的 Future。- Type Parameters:
T- element type - 元素类型- Parameters:
futures- the futures - Future 列表- Returns:
- Future of list - 列表的 Future
-
sequence
-
traverse
public static <A,B> Future<List<B>> traverse(Iterable<A> items, Function<? super A, ? extends Future<B>> function) Transform a collection into a future of list using a mapping function. 使用映射函数将集合转换为列表的 Future。- Type Parameters:
A- source type - 源类型B- result type - 结果类型- Parameters:
items- the items - 项目function- mapping function - 映射函数- Returns:
- Future of list - 列表的 Future
-
firstCompleted
Return the first completed future. 返回第一个完成的 Future。- Type Parameters:
T- element type - 元素类型- Parameters:
futures- the futures - Future 列表- Returns:
- first completed - 第一个完成的
-
andThenVirtual
-
flatMapVirtual
-