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) - 空值安全: 是(验证输入)

public final class Future<T> extends Object
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 Details

    • of

      public static <T> Future<T> of(Supplier<T> supplier)
      Create a Future from a supplier (uses ForkJoinPool). 从供应商创建 Future(使用 ForkJoinPool)。
      Type Parameters:
      T - value type - 值类型
      Parameters:
      supplier - the computation - 计算
      Returns:
      new Future - 新 Future
    • of

      public static <T> Future<T> of(Supplier<T> supplier, Executor executor)
      Create a Future from a supplier with custom executor. 使用自定义执行器从供应商创建 Future。
      Type Parameters:
      T - value type - 值类型
      Parameters:
      supplier - the computation - 计算
      executor - the executor - 执行器
      Returns:
      new Future - 新 Future
    • ofVirtual

      public static <T> Future<T> ofVirtual(Supplier<T> supplier)
      Create a Future from a supplier using virtual threads. 使用虚拟线程从供应商创建 Future。
      Type Parameters:
      T - value type - 值类型
      Parameters:
      supplier - the computation - 计算
      Returns:
      new Future - 新 Future
    • fromCallable

      public static <T> Future<T> fromCallable(Callable<T> callable)
      Create a Future from a callable. 从 Callable 创建 Future。
      Type Parameters:
      T - value type - 值类型
      Parameters:
      callable - the callable - Callable
      Returns:
      new Future - 新 Future
    • successful

      public static <T> Future<T> successful(T value)
      Create a successful Future with the given value. 使用给定值创建成功的 Future。
      Type Parameters:
      T - value type - 值类型
      Parameters:
      value - the value - 值
      Returns:
      successful Future - 成功的 Future
    • failed

      public static <T> Future<T> failed(Throwable exception)
      Create a failed Future with the given exception. 使用给定异常创建失败的 Future。
      Type Parameters:
      T - value type - 值类型
      Parameters:
      exception - the exception - 异常
      Returns:
      failed Future - 失败的 Future
    • fromCompletableFuture

      public static <T> Future<T> fromCompletableFuture(CompletableFuture<T> cf)
      Create a Future from a CompletableFuture. 从 CompletableFuture 创建 Future。
      Type Parameters:
      T - value type - 值类型
      Parameters:
      cf - the CompletableFuture - CompletableFuture
      Returns:
      new Future - 新 Future
    • never

      public static <T> Future<T> never()
      Create a Future that never completes. 创建永不完成的 Future。
      Type Parameters:
      T - value type - 值类型
      Returns:
      never completing Future - 永不完成的 Future
    • map

      public <R> Future<R> map(Function<? super T, ? extends R> mapper)
      Map the value to a new value. 将值映射为新值。
      Type Parameters:
      R - result type - 结果类型
      Parameters:
      mapper - mapping function - 映射函数
      Returns:
      mapped Future - 映射后的 Future
    • flatMap

      public <R> Future<R> flatMap(Function<? super T, ? extends Future<R>> mapper)
      FlatMap to another Future. 扁平映射到另一个 Future。
      Type Parameters:
      R - result type - 结果类型
      Parameters:
      mapper - mapping function - 映射函数
      Returns:
      flattened Future - 扁平化的 Future
    • filter

      public Future<T> filter(Predicate<? super T> predicate)
      Filter the value. 过滤值。
      Parameters:
      predicate - filter predicate - 过滤谓词
      Returns:
      filtered Future (may be failed with NoSuchElementException) - 过滤后的 Future
    • onSuccess

      public Future<T> onSuccess(Consumer<? super T> action)
      Execute side effect on success. 成功时执行副作用。
      Parameters:
      action - the action - 操作
      Returns:
      this Future - 此 Future
    • onFailure

      public Future<T> onFailure(Consumer<? super Throwable> action)
      Execute side effect on failure. 失败时执行副作用。
      Parameters:
      action - the action - 操作
      Returns:
      this Future - 此 Future
    • onComplete

      public Future<T> onComplete(BiConsumer<? super T, ? super Throwable> action)
      Execute side effect on completion. 完成时执行副作用。
      Parameters:
      action - the action - 操作
      Returns:
      this Future - 此 Future
    • recover

      public Future<T> recover(Function<? super Throwable, ? extends T> recovery)
      Recover from any failure. 从任何失败恢复。
      Parameters:
      recovery - recovery function - 恢复函数
      Returns:
      recovered Future - 恢复后的 Future
    • 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

      public Future<T> recoverWith(Function<? super Throwable, ? extends Future<T>> recovery)
      Recover with another Future. 使用另一个 Future 恢复。
      Parameters:
      recovery - recovery function - 恢复函数
      Returns:
      recovered Future - 恢复后的 Future
    • orElse

      public Future<T> orElse(T fallback)
      Provide a fallback value on failure. 失败时提供备用值。
      Parameters:
      fallback - the fallback value - 备用值
      Returns:
      Future with fallback - 带备用值的 Future
    • orElse

      public Future<T> orElse(Future<T> fallback)
      Provide a fallback Future on failure. 失败时提供备用 Future。
      Parameters:
      fallback - the fallback Future - 备用 Future
      Returns:
      Future with fallback - 带备用的 Future
    • timeout

      public Future<T> timeout(Duration duration)
      Apply a timeout to this Future. 对此 Future 应用超时。
      Parameters:
      duration - timeout duration - 超时时长
      Returns:
      Future with timeout - 带超时的 Future
    • timeout

      public Future<T> timeout(Duration duration, T defaultValue)
      Apply a timeout with default value. 应用超时并使用默认值。
      Parameters:
      duration - timeout duration - 超时时长
      defaultValue - value on timeout - 超时时的值
      Returns:
      Future with timeout - 带超时的 Future
    • await

      public Try<T> await()
      Await the result, returning a Try. 等待结果,返回 Try。
      Returns:
      Try containing result or exception - 包含结果或异常的 Try
    • await

      public Try<T> await(Duration duration)
      Await the result with timeout, returning a Try. 使用超时等待结果,返回 Try。
      Parameters:
      duration - timeout duration - 超时时长
      Returns:
      Try containing result or exception - 包含结果或异常的 Try
    • get

      public T get()
      Get the value, throwing if failed. 获取值,如果失败则抛出异常。
      Returns:
      the value - 值
      Throws:
      CompletionException - if failed - 如果失败
    • getOrElse

      public T getOrElse(T defaultValue)
      Get the value with default on failure. 获取值,失败时使用默认值。
      Parameters:
      defaultValue - default value - 默认值
      Returns:
      the value or default - 值或默认值
    • 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

      public Option<T> toOption()
      Convert to Option (None on failure). 转换为 Option(失败时为 None)。
      Returns:
      Option containing value - 包含值的 Option
    • toTry

      public Try<T> toTry()
      Convert to Try. 转换为 Try。
      Returns:
      Try containing result - 包含结果的 Try
    • toCompletableFuture

      public CompletableFuture<T> toCompletableFuture()
      Get the underlying CompletableFuture. 获取底层的 CompletableFuture。
      Returns:
      CompletableFuture - CompletableFuture
    • zip

      public 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. 将两个 Future 合并为一个。
      Type Parameters:
      A - first type - 第一个类型
      B - second type - 第二个类型
      R - result type - 结果类型
      Parameters:
      futureA - first future - 第一个 Future
      futureB - second future - 第二个 Future
      zipper - 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 - 其他 Future
      zipper - combining function - 组合函数
      Returns:
      combined Future - 组合后的 Future
    • sequence

      @SafeVarargs public static <T> Future<List<T>> sequence(Future<T>... futures)
      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

      public static <T> Future<List<T>> sequence(List<Future<T>> futures)
      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
    • 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

      @SafeVarargs public static <T> Future<T> firstCompleted(Future<T>... futures)
      Return the first completed future. 返回第一个完成的 Future。
      Type Parameters:
      T - element type - 元素类型
      Parameters:
      futures - the futures - Future 列表
      Returns:
      first completed - 第一个完成的
    • andThenVirtual

      public <R> Future<R> andThenVirtual(Function<? super T, ? extends R> action)
      Run action after completion on a virtual thread. 完成后在虚拟线程上运行操作。
      Type Parameters:
      R - result type - 结果类型
      Parameters:
      action - the action - 操作
      Returns:
      new Future - 新 Future
    • flatMapVirtual

      public <R> Future<R> flatMapVirtual(Function<? super T, ? extends Future<R>> mapper)
      FlatMap on virtual thread. 在虚拟线程上扁平映射。
      Type Parameters:
      R - result type - 结果类型
      Parameters:
      mapper - mapping function - 映射函数
      Returns:
      new Future - 新 Future