Class AsyncFunctionUtil

java.lang.Object
cloud.opencode.base.functional.async.AsyncFunctionUtil

public final class AsyncFunctionUtil extends Object
AsyncFunctionUtil - Virtual Thread based async utilities AsyncFunctionUtil - 基于虚拟线程的异步工具

Provides utilities for asynchronous function execution using JDK 25's Virtual Threads. Enables functional-style async operations with proper error handling.

提供使用 JDK 25 虚拟线程的异步函数执行工具。支持带有正确错误处理的 函数式异步操作。

Features | 主要功能:

  • Virtual Thread execution - 虚拟线程执行
  • Parallel function application - 并行函数应用
  • Timeout support - 超时支持
  • Error accumulation - 错误累积
  • Structured concurrency - 结构化并发

Usage Examples | 使用示例:

// Run async with Virtual Thread
CompletableFuture<String> future = AsyncFunctionUtil.async(() -> fetchData());
String result = future.join();

// Run async with timeout
Try<String> result = AsyncFunctionUtil.asyncWithTimeout(
    () -> slowOperation(),
    Duration.ofSeconds(5)
);

// Parallel map
List<User> users = List.of(id1, id2, id3);
List<Profile> profiles = AsyncFunctionUtil.parallelMap(
    users,
    this::fetchProfile
);

// Run multiple async operations
List<CompletableFuture<Result>> futures = AsyncFunctionUtil.runAll(
    () -> task1(),
    () -> task2(),
    () -> task3()
);

// Wait for all with error handling
Try<List<Result>> allResults = AsyncFunctionUtil.awaitAll(futures);

Virtual Thread Benefits | 虚拟线程优势:

  • Lightweight (millions possible) - 轻量级(可创建数百万个)
  • Efficient I/O blocking - 高效 I/O 阻塞
  • Simplified async code - 简化异步代码
  • No thread pool tuning - 无需线程池调优

Performance | 性能特性:

  • Virtual Thread creation: ~1μs - 虚拟线程创建: ~1μs
  • Context switch: Very low overhead - 上下文切换: 极低开销
  • Memory: ~1KB per Virtual Thread - 内存: ~1KB 每个虚拟线程

Security | 安全性:

  • Thread-safe: Yes - 线程安全: 是
  • Exception handling: Comprehensive - 异常处理: 全面
Since:
JDK 25, opencode-base-functional V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • async

      public static <T> CompletableFuture<T> async(Supplier<T> supplier)
      Run a supplier asynchronously on a Virtual Thread 在虚拟线程上异步运行供应商
      Type Parameters:
      T - result type - 结果类型
      Parameters:
      supplier - the computation - 计算
      Returns:
      CompletableFuture with result
    • asyncRun

      public static CompletableFuture<Void> asyncRun(Runnable runnable)
      Run a runnable asynchronously on a Virtual Thread 在虚拟线程上异步运行可运行对象
      Parameters:
      runnable - the task - 任务
      Returns:
      CompletableFuture for completion tracking
    • asyncWithTimeout

      public static <T> Try<T> asyncWithTimeout(Supplier<T> supplier, Duration timeout)
      Run a supplier asynchronously with timeout 带超时异步运行供应商
      Type Parameters:
      T - result type - 结果类型
      Parameters:
      supplier - the computation - 计算
      timeout - maximum wait time - 最大等待时间
      Returns:
      Try containing result or timeout exception
    • parallelMap

      public static <T,R> List<R> parallelMap(List<T> items, Function<T,R> mapper)
      Map a function over a list in parallel 并行地将函数映射到列表
      Type Parameters:
      T - input type - 输入类型
      R - result type - 结果类型
      Parameters:
      items - items to process - 要处理的项目
      mapper - function to apply - 要应用的函数
      Returns:
      list of results (in original order)
    • parallelMapTry

      public static <T,R> Try<List<R>> parallelMapTry(List<T> items, Function<T,R> mapper)
      Map a function over a list in parallel with error handling 并行地将函数映射到列表,带错误处理
      Type Parameters:
      T - input type - 输入类型
      R - result type - 结果类型
      Parameters:
      items - items to process - 要处理的项目
      mapper - function to apply - 要应用的函数
      Returns:
      Try containing list of results or first exception
    • runAll

      @SafeVarargs public static <T> List<CompletableFuture<T>> runAll(Supplier<T>... suppliers)
      Run multiple suppliers in parallel 并行运行多个供应商
      Type Parameters:
      T - result type - 结果类型
      Parameters:
      suppliers - suppliers to run - 要运行的供应商
      Returns:
      list of futures
    • runAllAsync

      public static List<CompletableFuture<Void>> runAllAsync(Runnable... runnables)
      Run multiple runnables in parallel 并行运行多个可运行对象
      Parameters:
      runnables - runnables to run - 要运行的可运行对象
      Returns:
      list of futures
    • awaitAll

      public static <T> Try<List<T>> awaitAll(List<CompletableFuture<T>> futures)
      Wait for all futures to complete 等待所有 Future 完成
      Type Parameters:
      T - result type - 结果类型
      Parameters:
      futures - futures to wait for - 要等待的 Future
      Returns:
      Try containing list of results
    • awaitAll

      public static <T> Try<List<T>> awaitAll(List<CompletableFuture<T>> futures, Duration timeout)
      Wait for all futures with timeout 带超时等待所有 Future
      Type Parameters:
      T - result type - 结果类型
      Parameters:
      futures - futures to wait for - 要等待的 Future
      timeout - maximum wait time - 最大等待时间
      Returns:
      Try containing list of results
    • awaitFirst

      public static <T> CompletableFuture<T> awaitFirst(List<CompletableFuture<T>> futures)
      Wait for first successful result 等待第一个成功结果
      Type Parameters:
      T - result type - 结果类型
      Parameters:
      futures - futures to wait for - 要等待的 Future
      Returns:
      CompletableFuture with first result
    • thenAsync

      public static <T,R> CompletableFuture<R> thenAsync(CompletableFuture<T> future, Function<T,R> mapper)
      Chain async operations 链接异步操作
      Type Parameters:
      T - input type - 输入类型
      R - result type - 结果类型
      Parameters:
      future - first operation - 第一个操作
      mapper - transformation - 转换
      Returns:
      chained future
    • thenFlatAsync

      public static <T,R> CompletableFuture<R> thenFlatAsync(CompletableFuture<T> future, Function<T, CompletableFuture<R>> mapper)
      Chain async operations with async mapper 使用异步映射器链接异步操作
      Type Parameters:
      T - input type - 输入类型
      R - result type - 结果类型
      Parameters:
      future - first operation - 第一个操作
      mapper - async transformation - 异步转换
      Returns:
      chained future
    • recover

      public static <T> CompletableFuture<T> recover(CompletableFuture<T> future, Function<Throwable, T> recovery)
      Recover from failure asynchronously 异步从失败恢复
      Type Parameters:
      T - result type - 结果类型
      Parameters:
      future - the future - Future
      recovery - recovery function - 恢复函数
      Returns:
      future with recovery
    • recoverAsync

      public static <T> CompletableFuture<T> recoverAsync(CompletableFuture<T> future, Function<Throwable, CompletableFuture<T>> recovery)
      Recover from failure with async operation 使用异步操作从失败恢复
      Type Parameters:
      T - result type - 结果类型
      Parameters:
      future - the future - Future
      recovery - async recovery function - 异步恢复函数
      Returns:
      future with async recovery
    • delay

      public static CompletableFuture<Void> delay(Duration duration)
      Delay execution 延迟执行
      Parameters:
      duration - delay duration - 延迟时长
      Returns:
      future completing after delay
    • completed

      public static <T> CompletableFuture<T> completed(T value)
      Create a completed future with value 创建带值的已完成 Future
      Type Parameters:
      T - result type - 结果类型
      Parameters:
      value - the value - 值
      Returns:
      completed future
    • failed

      public static <T> CompletableFuture<T> failed(Throwable throwable)
      Create a failed future 创建失败的 Future
      Type Parameters:
      T - result type - 结果类型
      Parameters:
      throwable - the exception - 异常
      Returns:
      failed future
    • executor

      public static ExecutorService executor()
      Get the Virtual Thread executor 获取虚拟线程执行器
      Returns:
      the executor