Class ThreadLocalPool<T>

java.lang.Object
cloud.opencode.base.pool.impl.ThreadLocalPool<T>
Type Parameters:
T - the type of object being pooled - 池化对象类型
All Implemented Interfaces:
ObjectPool<T>, AutoCloseable

public class ThreadLocalPool<T> extends Object implements ObjectPool<T>
ThreadLocalPool - Thread Local Object Pool ThreadLocalPool - 线程本地对象池

Object pool that maintains one object per thread using ThreadLocal. Provides zero-contention access for single-object-per-thread scenarios.

使用ThreadLocal为每个线程维护一个对象的对象池。为单线程单对象场景提供零竞争访问。

Features | 主要功能:

  • One object per thread - 每线程一个对象
  • Zero contention access - 零竞争访问
  • Automatic lazy initialization - 自动延迟初始化
  • Thread-safe without locks - 无锁的线程安全

Usage Examples | 使用示例:

ThreadLocalPool<StringBuilder> pool = new ThreadLocalPool<>(
    new BasePooledObjectFactory<>() {
        @Override
        protected StringBuilder create() {
            return new StringBuilder(1024);
        }

        @Override
        public void passivateObject(PooledObject<StringBuilder> obj) {
            obj.getObject().setLength(0);
        }
    });

StringBuilder sb = pool.borrowObject();
try {
    sb.append("Hello");
} finally {
    pool.returnObject(sb);  // Resets the StringBuilder
}

Performance | 性能特性:

  • Borrow/return: O(1) with no contention - 借用/归还: O(1) 无竞争
  • Best for thread-affine workloads - 最适合线程亲和的工作负载

Caution | 注意:

  • Not suitable for Virtual Threads with many instances - 不适合大量虚拟线程实例
  • Memory proportional to thread count - 内存与线程数成正比
  • Thread cleanup limitation: Due to JDK ThreadLocal design, close() and clear() can only destroy the pooled object belonging to the calling thread. Objects held by other threads cannot be removed from their ThreadLocal slots and will only be garbage collected when those threads terminate. The pool tracks all threads that have borrowed objects (via a ConcurrentHashMap-backed set) and marks the pool as closed so that subsequent borrow attempts from any thread will fail fast with an exception.
  • 线程清理限制: 由于JDK ThreadLocal的设计,close()clear() 只能销毁 调用线程拥有的池化对象。其他线程持有的对象无法从其ThreadLocal槽中移除,只有在这些线程终止时才会被垃圾回收。 池会跟踪所有借用过对象的线程(通过ConcurrentHashMap支持的集合),并将池标记为已关闭, 使得任何线程后续的借用尝试都会立即抛出异常。
Since:
JDK 25, opencode-base-pool V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Constructor Details

    • ThreadLocalPool

      public ThreadLocalPool(PooledObjectFactory<T> factory)
      Creates a thread-local pool. 创建线程本地池。
      Parameters:
      factory - the object factory - 对象工厂
  • Method Details

    • borrowObject

      public T borrowObject() throws OpenPoolException
      Description copied from interface: ObjectPool
      Borrows an object from the pool. 从池中借用对象。

      Uses default timeout from pool configuration.

      使用池配置的默认超时。

      Specified by:
      borrowObject in interface ObjectPool<T>
      Returns:
      the borrowed object - 借用的对象
      Throws:
      OpenPoolException - if borrowing fails - 如果借用失败
    • borrowObject

      public T borrowObject(Duration timeout) throws OpenPoolException
      Description copied from interface: ObjectPool
      Borrows an object from the pool with timeout. 带超时从池中借用对象。
      Specified by:
      borrowObject in interface ObjectPool<T>
      Parameters:
      timeout - the maximum wait time - 最大等待时间
      Returns:
      the borrowed object - 借用的对象
      Throws:
      OpenPoolException - if borrowing fails or times out - 如果借用失败或超时
    • returnObject

      public void returnObject(T obj)
      Description copied from interface: ObjectPool
      Returns an object to the pool. 将对象归还到池中。
      Specified by:
      returnObject in interface ObjectPool<T>
      Parameters:
      obj - the object to return - 要归还的对象
    • invalidateObject

      public void invalidateObject(T obj)
      Description copied from interface: ObjectPool
      Invalidates an object (will not be returned to pool). 使对象失效(不会返回池中)。
      Specified by:
      invalidateObject in interface ObjectPool<T>
      Parameters:
      obj - the object to invalidate - 要失效的对象
    • addObject

      public void addObject() throws OpenPoolException
      Description copied from interface: ObjectPool
      Adds a new object to the pool. 向池中添加新对象。
      Specified by:
      addObject in interface ObjectPool<T>
      Throws:
      OpenPoolException - if adding fails - 如果添加失败
    • getNumIdle

      public int getNumIdle()
      Description copied from interface: ObjectPool
      Gets the number of idle objects. 获取空闲对象数。
      Specified by:
      getNumIdle in interface ObjectPool<T>
      Returns:
      the idle count - 空闲数
    • getNumActive

      public int getNumActive()
      Description copied from interface: ObjectPool
      Gets the number of active (borrowed) objects. 获取活跃(借出)对象数。
      Specified by:
      getNumActive in interface ObjectPool<T>
      Returns:
      the active count - 活跃数
    • clear

      public void clear()
      Description copied from interface: ObjectPool
      Clears all idle objects from the pool. 清除池中所有空闲对象。
      Specified by:
      clear in interface ObjectPool<T>
    • getMetrics

      public PoolMetrics getMetrics()
      Description copied from interface: ObjectPool
      Gets the pool metrics. 获取池指标。
      Specified by:
      getMetrics in interface ObjectPool<T>
      Returns:
      the metrics - 指标
    • close

      public void close()
      Specified by:
      close in interface AutoCloseable