Class Lazy<T>

java.lang.Object
cloud.opencode.base.core.Lazy<T>
Type Parameters:
T - value type - 值类型
All Implemented Interfaces:
Supplier<T>

public final class Lazy<T> extends Object implements Supplier<T>
Lazy - Virtual-thread-safe lazy evaluation container using VarHandle CAS Lazy - 使用 VarHandle CAS 的虚拟线程安全惰性求值容器

A container that delays computation until the value is actually needed. The computation is performed at most once, and the result is cached. Uses VarHandle-based CAS spinning instead of synchronized/ReentrantLock, making it safe for virtual threads (no pinning).

延迟计算直到实际需要值的容器。计算最多执行一次,结果会被缓存。 使用基于 VarHandle 的 CAS 自旋代替 synchronized/ReentrantLock, 对虚拟线程安全(不会导致线程固定)。

Features | 主要功能:

  • Deferred computation - 延迟计算
  • Single evaluation (memoization) - 单次求值(记忆化)
  • Virtual-thread safe (VarHandle CAS, no locking) - 虚拟线程安全(VarHandle CAS,无锁)
  • Monadic operations (map, flatMap, filter) - Monad 操作
  • Spin wait with backoff (onSpinWait + parkNanos) - 带退避的自旋等待

Usage Examples | 使用示例:

// Deferred computation
Lazy<ExpensiveObject> lazy = Lazy.of(() -> createExpensiveObject());

// Value not computed yet
assertFalse(lazy.isEvaluated());

// Computed on first access
ExpensiveObject obj = lazy.get();
assertTrue(lazy.isEvaluated());

// Cached on subsequent access
ExpensiveObject same = lazy.get();  // No recomputation

// Chained lazy operations
Lazy<String> result = Lazy.of(() -> fetchData())
    .map(this::process)
    .map(this::format);
// Nothing computed until result.get()

// With checked supplier
Lazy<String> fromFile = Lazy.of((CheckedSupplier<String>) () -> Files.readString(path));

Performance | 性能特性:

  • First get(): O(computation time) - 首次 get(): O(计算时间)
  • Subsequent get(): O(1) volatile read - 后续 get(): O(1) volatile 读取
  • Memory: Supplier reference is kept for reset() support; Lazy itself should be discarded post-evaluation if memory reclamation is needed - 内存: supplier 引用保留以支持 reset();如需回收内存请在求值后丢弃 Lazy 实例

Security | 安全性:

  • Thread-safe: Yes (VarHandle CAS) - 线程安全: 是 (VarHandle CAS)
  • Null-safe: Allows null results - 空值安全: 允许 null 结果
Since:
JDK 25, opencode-base-core V1.0.3
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Summary

    Modifier and Type
    Method
    Description
    filter(Predicate<? super T> predicate)
    Filter the value lazily.
    <U> Lazy<U>
    flatMap(Function<? super T, Lazy<U>> mapper)
    Transform to another Lazy lazily 惰性转换为另一个 Lazy
    get()
    Get the value, computing if necessary.
    getOrElse(Supplier<? extends T> supplier)
    Get value or compute default if evaluation throws 获取值或计算默认值(如果求值抛出异常)
    getOrElse(T defaultValue)
    Get value or default if evaluation throws 获取值或默认值(如果求值抛出异常)
    boolean
    Check if the value has been evaluated 检查值是否已被求值
    <U> Lazy<U>
    map(Function<? super T, ? extends U> mapper)
    Transform the value lazily.
    static <T> Lazy<T>
    of(CheckedSupplier<T> supplier)
    Create a Lazy from a CheckedSupplier.
    static <T> Lazy<T>
    of(Supplier<T> supplier)
    Create a Lazy from a Supplier 从 Supplier 创建 Lazy
    void
    Reset this Lazy to unevaluated state, allowing re-computation on next get() call.
    Convert to Optional.
     
    static <T> Lazy<T>
    value(T value)
    Create an already-evaluated Lazy with a pre-computed value 创建已求值的 Lazy,包含预计算的值

    Methods inherited from class Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
  • Method Details

    • of

      public static <T> Lazy<T> of(Supplier<T> supplier)
      Create a Lazy from a Supplier 从 Supplier 创建 Lazy
      Type Parameters:
      T - value type - 值类型
      Parameters:
      supplier - value supplier (evaluated lazily) - 值供应商(惰性求值)
      Returns:
      Lazy container
      Throws:
      NullPointerException - if supplier is null
    • of

      public static <T> Lazy<T> of(CheckedSupplier<T> supplier)
      Create a Lazy from a CheckedSupplier. Checked exceptions are wrapped in OpenException. 从 CheckedSupplier 创建 Lazy。受检异常包装为 OpenException。
      Type Parameters:
      T - value type - 值类型
      Parameters:
      supplier - checked value supplier (evaluated lazily) - 受检值供应商(惰性求值)
      Returns:
      Lazy container
      Throws:
      NullPointerException - if supplier is null
    • value

      public static <T> Lazy<T> value(T value)
      Create an already-evaluated Lazy with a pre-computed value 创建已求值的 Lazy,包含预计算的值
      Type Parameters:
      T - value type - 值类型
      Parameters:
      value - the pre-computed value - 预计算的值
      Returns:
      already-evaluated Lazy
    • get

      public T get()
      Get the value, computing if necessary. Thread-safe via VarHandle CAS with spin-wait backoff. If the supplier throws, the exception is memoized and re-thrown on subsequent calls. 获取值,必要时进行计算。通过 VarHandle CAS 和自旋等待退避保证线程安全。 如果供应商抛出异常,异常会被缓存并在后续调用时重新抛出。
      Specified by:
      get in interface Supplier<T>
      Returns:
      the computed value - 计算后的值
      Throws:
      RuntimeException - if the supplier threw (memoized) - 如果供应商抛出异常(已缓存)
    • isEvaluated

      public boolean isEvaluated()
      Check if the value has been evaluated 检查值是否已被求值
      Returns:
      true if evaluated - 如果已求值返回 true
    • map

      public <U> Lazy<U> map(Function<? super T, ? extends U> mapper)
      Transform the value lazily. The mapper is not applied until get() is called on the result. 惰性转换值。映射函数在结果的 get() 被调用前不会执行。
      Type Parameters:
      U - result type - 结果类型
      Parameters:
      mapper - transformation function - 转换函数
      Returns:
      lazy transformed value
    • flatMap

      public <U> Lazy<U> flatMap(Function<? super T, Lazy<U>> mapper)
      Transform to another Lazy lazily 惰性转换为另一个 Lazy
      Type Parameters:
      U - result type - 结果类型
      Parameters:
      mapper - transformation function returning Lazy - 返回 Lazy 的转换函数
      Returns:
      lazy result
    • filter

      public Lazy<T> filter(Predicate<? super T> predicate)
      Filter the value lazily. If the predicate is not satisfied, get() throws NoSuchElementException. 惰性过滤值。如果谓词不满足,get() 抛出 NoSuchElementException。
      Parameters:
      predicate - filter condition - 过滤条件
      Returns:
      filtered Lazy
    • getOrElse

      public T getOrElse(T defaultValue)
      Get value or default if evaluation throws 获取值或默认值(如果求值抛出异常)
      Parameters:
      defaultValue - default value on error - 错误时的默认值
      Returns:
      value or default
    • getOrElse

      public T getOrElse(Supplier<? extends T> supplier)
      Get value or compute default if evaluation throws 获取值或计算默认值(如果求值抛出异常)
      Parameters:
      supplier - default value supplier - 默认值供应商
      Returns:
      value or computed default
    • toOptional

      public Optional<T> toOptional()
      Convert to Optional. Returns Optional.of(value) if evaluated and non-null, Optional.empty() if evaluation throws or returns null. 转换为 Optional。如果已求值且非 null 返回 Optional.of(value), 如果求值抛出异常或返回 null 则返回 Optional.empty()。
      Returns:
      Optional containing the value
    • reset

      @Experimental(since="1.0.3", reason="Reset semantics under concurrency need further validation") public void reset()
      Reset this Lazy to unevaluated state, allowing re-computation on next get() call. 将此 Lazy 重置为未求值状态,允许在下次 get() 调用时重新计算。

      Warning: This method is experimental. Using reset() while concurrent get() calls are in flight may cause the supplier to be invoked more than once. The supplier reference must still be available (not a pre-evaluated Lazy created via value()).

      警告:此方法为实验性。在并发 get() 调用进行中使用 reset() 可能导致 supplier 被调用多次。supplier 引用必须仍然可用(不是通过 value() 创建的预求值 Lazy)。

      Throws:
      IllegalStateException - if this Lazy was created via value() (supplier is null)
    • toString

      public String toString()
      Overrides:
      toString in class Object