Class SingleFlight<K,V>

java.lang.Object
cloud.opencode.base.cache.protection.SingleFlight<K,V>
Type Parameters:
K - the type of keys | 键类型
V - the type of values | 值类型

public class SingleFlight<K,V> extends Object
SingleFlight - Request coalescing for cache stampede prevention SingleFlight - 请求合并,防止缓存击穿

Ensures only one loading request is in-flight for each key.

确保每个键只有一个加载请求正在进行。

Features | 主要功能:

  • Request deduplication - 请求去重
  • Concurrent request coalescing - 并发请求合并
  • Timeout support - 超时支持
  • Cancellation support - 取消支持

Usage Examples | 使用示例:

SingleFlight<String, User> flight = new SingleFlight<>();

// Multiple concurrent requests for same key will share one load
// 同一键的多个并发请求将共享一次加载
User user = flight.execute("user:1001", key -> loadFromDb(key));

Performance | 性能特性:

  • Time complexity: O(1) for check, O(loader) for load - 时间复杂度: 检查 O(1),加载 O(loader)
  • Space complexity: O(n) where n is in-flight count - 空间复杂度: O(n) n 为进行中请求数

Security | 安全性:

  • Thread-safe: Yes - 线程安全: 是
  • Null-safe: Yes - 空值安全: 是
Since:
JDK 25, opencode-base-cache V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Constructor Details

    • SingleFlight

      public SingleFlight()
      Creates a new SingleFlight instance | 创建新的 SingleFlight 实例
  • Method Details

    • execute

      public V execute(K key, Function<K,V> loader)
      Execute loader, coalescing concurrent requests for the same key 执行加载器,合并相同键的并发请求
      Parameters:
      key - the key | 键
      loader - the loader function | 加载函数
      Returns:
      the loaded value | 加载的值
    • execute

      public V execute(K key, Function<K,V> loader, Duration timeout) throws SingleFlight.TimeoutException
      Execute loader with timeout 带超时执行加载器
      Parameters:
      key - the key | 键
      loader - the loader function | 加载函数
      timeout - max wait time | 最大等待时间
      Returns:
      the loaded value | 加载的值
      Throws:
      SingleFlight.TimeoutException - if timeout exceeded | 超时时抛出异常
    • executeAsync

      public CompletableFuture<V> executeAsync(K key, Function<K, CompletableFuture<V>> loader)
      Execute async loader 异步执行加载器
      Parameters:
      key - the key | 键
      loader - the async loader function | 异步加载函数
      Returns:
      future containing value | 包含值的 Future
    • inflightCount

      public int inflightCount()
      Get count of in-flight requests 获取进行中请求数
      Returns:
      in-flight count | 进行中请求数
    • isLoading

      public boolean isLoading(K key)
      Check if a key is currently loading 检查键是否正在加载
      Parameters:
      key - the key | 键
      Returns:
      true if loading | 正在加载返回 true
    • cancel

      public boolean cancel(K key)
      Cancel waiting for a key 取消等待某个键
      Parameters:
      key - the key | 键
      Returns:
      true if was loading | 正在加载返回 true
    • cancelAll

      public void cancelAll()
      Cancel all in-flight requests 取消所有进行中请求