Class LazyAsync<T>

java.lang.Object
cloud.opencode.base.functional.async.LazyAsync<T>
Type Parameters:
T - result type - 结果类型

public final class LazyAsync<T> extends Object
LazyAsync - Lazy asynchronous computation LazyAsync - 惰性异步计算

Combines lazy evaluation with asynchronous execution. The computation is not started until explicitly triggered, then runs on a Virtual Thread. Results are cached for subsequent access.

将惰性求值与异步执行结合。计算在显式触发之前不会开始,然后在虚拟线程上运行。 结果会被缓存以供后续访问。

Features | 主要功能:

  • Deferred async execution - 延迟异步执行
  • Virtual Thread based - 基于虚拟线程
  • Result caching - 结果缓存
  • Timeout support - 超时支持
  • Monadic operations - Monad 操作

Usage Examples | 使用示例:

// Create lazy async computation
LazyAsync<Data> lazy = LazyAsync.of(() -> fetchDataFromNetwork());

// Computation not started yet
assertFalse(lazy.isStarted());

// Start and get result
CompletableFuture<Data> future = lazy.start();
Data data = future.join();

// Or get blocking with timeout
Try<Data> result = lazy.get(Duration.ofSeconds(5));

// Chain transformations (also lazy)
LazyAsync<String> processed = lazy
    .map(Data::getName)
    .map(String::toUpperCase);

// Force evaluation
String name = processed.force();

// Multiple lazy operations
LazyAsync<Combined> combined = LazyAsync.combine(
    LazyAsync.of(() -> fetchA()),
    LazyAsync.of(() -> fetchB()),
    Combined::new
);

States | 状态:

  • NOT_STARTED - Computation not yet triggered - 未启动 - 计算尚未触发
  • RUNNING - Computation in progress - 运行中 - 计算进行中
  • COMPLETED - Result available - 已完成 - 结果可用
  • FAILED - Computation failed - 失败 - 计算失败

Performance | 性能特性:

  • Start: O(1) (just triggers async) - 启动: O(1) (仅触发异步)
  • Subsequent get: O(1) (cached) - 后续获取: O(1) (已缓存)
  • Memory: Holds supplier until started - 内存: 保持 supplier 直到启动

Security | 安全性:

  • Thread-safe: Yes - 线程安全: 是
  • Exception handling: Wrapped in Try/Future - 异常处理: 包装在 Try/Future 中
Since:
JDK 25, opencode-base-functional V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • of

      public static <T> LazyAsync<T> of(Supplier<T> supplier)
      Create a lazy async computation 创建惰性异步计算
      Type Parameters:
      T - result type - 结果类型
      Parameters:
      supplier - the computation - 计算
      Returns:
      lazy async container
    • completed

      public static <T> LazyAsync<T> completed(T value)
      Create an already completed lazy async 创建已完成的惰性异步
      Type Parameters:
      T - result type - 结果类型
      Parameters:
      value - the value - 值
      Returns:
      completed lazy async
    • failed

      public static <T> LazyAsync<T> failed(Throwable throwable)
      Create a failed lazy async 创建失败的惰性异步
      Type Parameters:
      T - result type - 结果类型
      Parameters:
      throwable - the exception - 异常
      Returns:
      failed lazy async
    • start

      public CompletableFuture<T> start()
      Start the computation if not already started 如果尚未启动则启动计算
      Returns:
      CompletableFuture with result
    • force

      public T force()
      Get the result, starting computation if needed 获取结果,必要时启动计算
      Returns:
      the result (blocking)
      Throws:
      RuntimeException - if computation fails
    • get

      public Try<T> get(Duration timeout)
      Get the result with timeout 带超时获取结果
      Parameters:
      timeout - maximum wait time - 最大等待时间
      Returns:
      Try containing result or exception
    • toTry

      public Try<T> toTry()
      Get the result as Try (blocking) 获取结果为 Try(阻塞)
      Returns:
      Try containing result
    • isStarted

      public boolean isStarted()
      Check if computation has been started 检查计算是否已启动
      Returns:
      true if started
    • isRunning

      public boolean isRunning()
      Check if computation is running 检查计算是否正在运行
      Returns:
      true if running
    • isCompleted

      public boolean isCompleted()
      Check if computation is complete 检查计算是否完成
      Returns:
      true if completed successfully
    • isFailed

      public boolean isFailed()
      Check if computation failed 检查计算是否失败
      Returns:
      true if failed
    • state

      public LazyAsync.State state()
      Get the current state 获取当前状态
      Returns:
      the state
    • map

      public <U> LazyAsync<U> map(Function<? super T, ? extends U> mapper)
      Transform the result lazily 惰性转换结果
      Type Parameters:
      U - result type - 结果类型
      Parameters:
      mapper - transformation function - 转换函数
      Returns:
      new lazy async with transformation
    • flatMap

      public <U> LazyAsync<U> flatMap(Function<? super T, LazyAsync<U>> mapper)
      Flat-map to another lazy async 扁平映射到另一个惰性异步
      Type Parameters:
      U - result type - 结果类型
      Parameters:
      mapper - function returning LazyAsync - 返回 LazyAsync 的函数
      Returns:
      flattened lazy async
    • recover

      public LazyAsync<T> recover(Function<Throwable, T> recovery)
      Recover from failure 从失败恢复
      Parameters:
      recovery - recovery function - 恢复函数
      Returns:
      lazy async with recovery
    • orElse

      public LazyAsync<T> orElse(LazyAsync<T> fallback)
      Provide fallback on failure 失败时提供回退
      Parameters:
      fallback - fallback lazy async - 回退惰性异步
      Returns:
      lazy async with fallback
    • combine

      public static <T1,T2,R> LazyAsync<R> combine(LazyAsync<T1> la1, LazyAsync<T2> la2, BiFunction<T1,T2,R> combiner)
      Combine two lazy async computations 组合两个惰性异步计算
      Type Parameters:
      T1 - first type - 第一个类型
      T2 - second type - 第二个类型
      R - result type - 结果类型
      Parameters:
      la1 - first lazy async - 第一个惰性异步
      la2 - second lazy async - 第二个惰性异步
      combiner - combiner function - 组合函数
      Returns:
      combined lazy async
    • race

      public static <T> LazyAsync<T> race(LazyAsync<T> la1, LazyAsync<T> la2)
      Race two lazy async computations 竞争两个惰性异步计算

      Returns the result of whichever completes first.

      返回先完成的那个的结果。

      Type Parameters:
      T - result type - 结果类型
      Parameters:
      la1 - first lazy async - 第一个惰性异步
      la2 - second lazy async - 第二个惰性异步
      Returns:
      lazy async completing with first result
    • getFuture

      public CompletableFuture<T> getFuture()
      Get the underlying future if started 获取底层 Future(如果已启动)
      Returns:
      CompletableFuture or null if not started
    • toString

      public String toString()
      Overrides:
      toString in class Object