This is an automated email from the ASF dual-hosted git repository.

JackieTien97 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git


The following commit(s) were added to refs/heads/master by this push:
     new fb2f81d03e7 Add coreSize and maxIdleTime conf for SessionPool and 
TableSessionPool
fb2f81d03e7 is described below

commit fb2f81d03e72ea9e1bd991aea18b463396566f53
Author: Weihao Li <[email protected]>
AuthorDate: Fri Nov 27 19:21:43 2026 +0800

    Add coreSize and maxIdleTime conf for SessionPool and TableSessionPool
---
 .../org/apache/iotdb/isession/SessionConfig.java   |   5 +
 .../apache/iotdb/session/i18n/SessionMessages.java |  11 +
 .../apache/iotdb/session/i18n/SessionMessages.java |  11 +
 .../session/pool/AbstractSessionPoolBuilder.java   |   2 +
 .../org/apache/iotdb/session/pool/SessionPool.java | 205 +++++++++++-
 .../session/pool/TableSessionPoolBuilder.java      |  32 ++
 .../iotdb/session/BrokenSessionConnectionTest.java |  18 +-
 .../session/pool/SessionPoolExceptionTest.java     |   7 +-
 .../apache/iotdb/session/pool/SessionPoolTest.java | 366 +++++++++++++++++++--
 9 files changed, 603 insertions(+), 54 deletions(-)

diff --git 
a/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/SessionConfig.java
 
b/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/SessionConfig.java
index cbd507e943d..f182a20b31b 100644
--- 
a/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/SessionConfig.java
+++ 
b/iotdb-client/isession/src/main/java/org/apache/iotdb/isession/SessionConfig.java
@@ -46,6 +46,11 @@ public class SessionConfig {
 
   public static final int DEFAULT_SESSION_POOL_MAX_SIZE = 5;
 
+  public static final int DEFAULT_SESSION_POOL_CORE_SIZE = 0;
+
+  /** 0 means idle sessions are never evicted. */
+  public static final long DEFAULT_SESSION_POOL_MAX_IDLE_TIME_IN_MS = 0;
+
   public static final Version DEFAULT_VERSION = Version.V_1_0;
 
   public static final boolean DEFAULT_ENABLE_AUTO_FETCH = true;
diff --git 
a/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java
 
b/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java
index f6c55ca760d..f182740533d 100644
--- 
a/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java
+++ 
b/iotdb-client/session/src/main/i18n/en/org/apache/iotdb/session/i18n/SessionMessages.java
@@ -91,6 +91,17 @@ public final class SessionMessages {
   public static final String INTERRUPTED = "Interrupted!";
   public static final String CLOSING_SESSION_POOL = "closing the session pool, 
cleaning queues...";
 
+  // SessionPool - configuration
+  public static final String SESSION_POOL_MAX_SIZE_ARG_ILLEGAL =
+      "the maxSize %d must be positive";
+  public static final String SESSION_POOL_CORE_SIZE_ARG_ILLEGAL =
+      "the coreSize %d must be in [0, maxSize(%d)]";
+  public static final String SESSION_POOL_MAX_IDLE_TIME_ARG_ILLEGAL =
+      "the maxIdleTimeInMs %d must not be negative";
+  public static final String EVICT_IDLE_SESSIONS =
+      "evicted {} idle sessions, remaining session count: {}, coreSize: {}";
+  public static final String EVICT_IDLE_SESSIONS_FAILED = "failed to evict 
idle sessions";
+
   // SessionPool - operation failed (warn)
   public static final String INSERT_TABLET_FAILED = "insertTablet failed";
   public static final String INSERT_ALIGNED_TABLET_FAILED = 
"insertAlignedTablet failed";
diff --git 
a/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java
 
b/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java
index 4268a4f95dc..e956777c5cd 100644
--- 
a/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java
+++ 
b/iotdb-client/session/src/main/i18n/zh/org/apache/iotdb/session/i18n/SessionMessages.java
@@ -90,6 +90,17 @@ public final class SessionMessages {
   public static final String INTERRUPTED = "被中断!";
   public static final String CLOSING_SESSION_POOL = "正在关闭 Session 连接池,清理队列...";
 
+  // SessionPool - configuration
+  public static final String SESSION_POOL_MAX_SIZE_ARG_ILLEGAL =
+      "maxSize %d 必须为正数";
+  public static final String SESSION_POOL_CORE_SIZE_ARG_ILLEGAL =
+      "coreSize %d 必须位于 [0, maxSize(%d)] 范围内";
+  public static final String SESSION_POOL_MAX_IDLE_TIME_ARG_ILLEGAL =
+      "maxIdleTimeInMs %d 不能为负数";
+  public static final String EVICT_IDLE_SESSIONS =
+      "回收了 {} 个空闲 Session,剩余 Session 数:{},coreSize:{}";
+  public static final String EVICT_IDLE_SESSIONS_FAILED = "回收空闲 Session 失败";
+
   // SessionPool - operation failed (warn)
   public static final String INSERT_TABLET_FAILED = "insertTablet 失败";
   public static final String INSERT_ALIGNED_TABLET_FAILED = 
"insertAlignedTablet 失败";
diff --git 
a/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/AbstractSessionPoolBuilder.java
 
b/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/AbstractSessionPoolBuilder.java
index f8ce0c3d54c..7366e778747 100644
--- 
a/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/AbstractSessionPoolBuilder.java
+++ 
b/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/AbstractSessionPoolBuilder.java
@@ -25,6 +25,8 @@ import org.apache.iotdb.session.AbstractSessionBuilder;
 
 public class AbstractSessionPoolBuilder extends AbstractSessionBuilder {
   int maxSize = SessionConfig.DEFAULT_SESSION_POOL_MAX_SIZE;
+  int coreSize = SessionConfig.DEFAULT_SESSION_POOL_CORE_SIZE;
+  long maxIdleTimeInMs = 
SessionConfig.DEFAULT_SESSION_POOL_MAX_IDLE_TIME_IN_MS;
   long waitToGetSessionTimeoutInMs = 60_000;
   int connectionTimeoutInMs = SessionConfig.DEFAULT_CONNECTION_TIMEOUT_MS;
   protected INodeSupplier nodeSupplier;
diff --git 
a/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/SessionPool.java
 
b/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/SessionPool.java
index fba2e6abdbe..29810157d64 100644
--- 
a/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/SessionPool.java
+++ 
b/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/SessionPool.java
@@ -61,6 +61,7 @@ import java.util.concurrent.ConcurrentLinkedDeque;
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
 
 import static org.apache.iotdb.rpc.RpcUtils.isSetSqlDialect;
 import static org.apache.iotdb.rpc.RpcUtils.isUseDatabase;
@@ -99,11 +100,13 @@ public class SessionPool implements ISessionPool {
   private static final int RETRY = 3;
   private static final int FINAL_RETRY = RETRY - 1;
 
-  private final ConcurrentLinkedDeque<ISession> queue = new 
ConcurrentLinkedDeque<>();
+  private final ConcurrentLinkedDeque<IdleSession> queue = new 
ConcurrentLinkedDeque<>();
   // sessions currently borrowed for a result set or a table-session wrapper.
   private final ConcurrentMap<ISession, ISession> occupied = new 
ConcurrentHashMap<>();
   private int size = 0;
   private int maxSize = 0;
+  private int coreSize = SessionConfig.DEFAULT_SESSION_POOL_CORE_SIZE;
+  private long maxIdleTimeInMs = 
SessionConfig.DEFAULT_SESSION_POOL_MAX_IDLE_TIME_IN_MS;
   private final long waitToGetSessionTimeoutInMs;
 
   // parameters for Session constructor
@@ -172,6 +175,11 @@ public class SessionPool implements ISessionPool {
   @SuppressWarnings("java:S3077")
   private volatile ScheduledExecutorService executorService;
 
+  // dedicated single-thread scheduler for idle session eviction, so that a 
slow session.close()
+  // cannot block the datanode-list updater above (and vice versa)
+  @SuppressWarnings("java:S3077")
+  private volatile ScheduledExecutorService idleEvictor;
+
   private INodeSupplier availableNodes;
 
   // set to true, means that we will start a background thread to fetch all 
available (Status is
@@ -528,6 +536,9 @@ public class SessionPool implements ISessionPool {
 
   public SessionPool(AbstractSessionPoolBuilder builder) {
     this.maxSize = builder.maxSize;
+    this.coreSize = builder.coreSize;
+    this.maxIdleTimeInMs = builder.maxIdleTimeInMs;
+    validatePoolConfig(maxSize, coreSize, maxIdleTimeInMs);
     this.user = builder.username;
     this.password = builder.pw;
     this.fetchSize = builder.fetchSize;
@@ -589,6 +600,43 @@ public class SessionPool implements ISessionPool {
     } else {
       this.availableNodes = new DummyNodesSupplier(endPointList);
     }
+
+    if (maxIdleTimeInMs > 0 && coreSize < maxSize) {
+      // The eviction task only reads fields declared in this class, all of 
which are assigned
+      // above, so scheduling in the constructor cannot observe a partially 
initialized subclass.
+      // The first run is also delayed by at least one check interval.
+      scheduleIdleEviction();
+    }
+  }
+
+  private void scheduleIdleEviction() {
+    long checkIntervalInMs = Math.max(1_000L, Math.min(maxIdleTimeInMs / 2, 
60_000L));
+    ScheduledExecutorService evictor =
+        Executors.newSingleThreadScheduledExecutor(
+            r -> {
+              Thread t =
+                  new Thread(
+                      Thread.currentThread().getThreadGroup(), r, 
"SessionPoolIdleEvictor", 0);
+              t.setDaemon(true);
+              return t;
+            });
+    idleEvictor = evictor;
+    scheduleEvictionTask(evictor, this::runIdleEviction, checkIntervalInMs);
+  }
+
+  @SuppressWarnings("unsafeThreadSchedule")
+  private static void scheduleEvictionTask(
+      ScheduledExecutorService executor, Runnable task, long intervalInMs) {
+    executor.scheduleWithFixedDelay(task, intervalInMs, intervalInMs, 
TimeUnit.MILLISECONDS);
+  }
+
+  private void runIdleEviction() {
+    try {
+      evictIdleSessions();
+    } catch (Throwable t) {
+      // an uncaught Throwable would silently cancel all subsequent runs of a 
periodic task
+      LOGGER.warn(SessionMessages.EVICT_IDLE_SESSIONS_FAILED, t);
+    }
   }
 
   protected Session constructNewSession() {
@@ -712,7 +760,8 @@ public class SessionPool implements ISessionPool {
       if (closed) {
         throw new IoTDBConnectionException(SESSION_POOL_IS_CLOSED);
       }
-      session = queue.poll();
+      IdleSession idleSession = queue.poll();
+      session = idleSession == null ? null : idleSession.session;
     }
     if (session != null) {
       return session;
@@ -763,12 +812,21 @@ public class SessionPool implements ISessionPool {
           // wake up from this.wait(1000) by this.notify()
         }
 
-        session = queue.poll();
+        // closed may have been set while waiting; check before taking a 
session from the queue
+        if (closed) {
+          throw new IoTDBConnectionException(SESSION_POOL_IS_CLOSED);
+        }
+
+        IdleSession idleSession = queue.poll();
+        session = idleSession == null ? null : idleSession.session;
 
         // for putBack or size--
         this.notify();
 
+        // poll may have released the monitor, so re-check: never hand out a 
session from a
+        // closed pool, and never leak the session that has just been taken 
out of the queue
         if (closed) {
+          closeSession(session);
           throw new IoTDBConnectionException(SESSION_POOL_IS_CLOSED);
         }
       }
@@ -835,7 +893,7 @@ public class SessionPool implements ISessionPool {
   protected void putBack(ISession session) {
     synchronized (this) {
       if (!closed) {
-        queue.push(session);
+        queue.push(new IdleSession(session, System.nanoTime()));
         // we do not need to notifyAll as any waited thread can continue to 
work after waked up.
         this.notify();
         // comment the following codes as putBack is too frequently called.
@@ -897,18 +955,24 @@ public class SessionPool implements ISessionPool {
     final List<ISession> idleSessions;
     final List<ISession> borrowedSessions;
     final ScheduledExecutorService executorToShutdown;
+    final ScheduledExecutorService idleEvictorToShutdown;
     final INodeSupplier nodesToClose;
     synchronized (this) {
       if (closed) {
         return;
       }
       closed = true;
-      idleSessions = new ArrayList<>(queue);
+      idleSessions = new ArrayList<>(queue.size());
+      for (IdleSession idleSession : queue) {
+        idleSessions.add(idleSession.session);
+      }
       borrowedSessions = new ArrayList<>(occupied.keySet());
       queue.clear();
       occupied.clear();
       executorToShutdown = this.executorService;
       this.executorService = null;
+      idleEvictorToShutdown = this.idleEvictor;
+      this.idleEvictor = null;
       nodesToClose = availableNodes;
       availableNodes = null;
       this.notifyAll();
@@ -923,6 +987,9 @@ public class SessionPool implements ISessionPool {
     if (executorToShutdown != null) {
       executorToShutdown.shutdown();
     }
+    if (idleEvictorToShutdown != null) {
+      idleEvictorToShutdown.shutdown();
+    }
     if (nodesToClose != null && !nodesToClose.isCallerManaged()) {
       nodesToClose.close();
     }
@@ -974,7 +1041,7 @@ public class SessionPool implements ISessionPool {
           session.close();
           throw new IoTDBConnectionException(SESSION_POOL_IS_CLOSED);
         }
-        queue.push(session);
+        queue.push(new IdleSession(session, System.nanoTime()));
         this.notify();
       }
     } catch (IoTDBConnectionException e) {
@@ -986,6 +1053,59 @@ public class SessionPool implements ISessionPool {
     }
   }
 
+  private static void validatePoolConfig(int maxSize, int coreSize, long 
maxIdleTimeInMs) {
+    if (maxSize <= 0) {
+      throw new IllegalArgumentException(
+          String.format(SessionMessages.SESSION_POOL_MAX_SIZE_ARG_ILLEGAL, 
maxSize));
+    }
+    if (coreSize < 0 || coreSize > maxSize) {
+      throw new IllegalArgumentException(
+          String.format(SessionMessages.SESSION_POOL_CORE_SIZE_ARG_ILLEGAL, 
coreSize, maxSize));
+    }
+    if (maxIdleTimeInMs < 0) {
+      throw new IllegalArgumentException(
+          
String.format(SessionMessages.SESSION_POOL_MAX_IDLE_TIME_ARG_ILLEGAL, 
maxIdleTimeInMs));
+    }
+  }
+
+  /**
+   * Closes idle sessions which have been idle for more than {@link 
#maxIdleTimeInMs}, until the
+   * total number of sessions drops to {@link #coreSize}. Evicted sessions are 
closed outside the
+   * lock to avoid holding it during I/O.
+   */
+  private void evictIdleSessions() {
+    List<ISession> evicted = new ArrayList<>();
+    int sizeAfterEviction;
+    synchronized (this) {
+      if (closed) {
+        return;
+      }
+      long nowNanos = System.nanoTime();
+      long maxIdleNanos = TimeUnit.MILLISECONDS.toNanos(maxIdleTimeInMs);
+      while (size > coreSize) {
+        IdleSession idleSession = queue.peekLast();
+        if (idleSession == null || nowNanos - idleSession.idleSinceNanos <= 
maxIdleNanos) {
+          break;
+        }
+        queue.pollLast();
+        size--;
+        evicted.add(idleSession.session);
+      }
+      sizeAfterEviction = size;
+      if (!evicted.isEmpty()) {
+        // wake up all waiters so that they can create new sessions if size < 
maxSize.
+        this.notifyAll();
+      }
+    }
+    if (!evicted.isEmpty()) {
+      LOGGER.debug(
+          SessionMessages.EVICT_IDLE_SESSIONS, evicted.size(), 
sizeAfterEviction, coreSize);
+    }
+    for (ISession session : evicted) {
+      closeSession(session);
+    }
+  }
+
   private void closeSession(ISession session) {
     if (session != null) {
       try {
@@ -3560,6 +3680,14 @@ public class SessionPool implements ISessionPool {
     return maxSize;
   }
 
+  public int getCoreSize() {
+    return coreSize;
+  }
+
+  public long getMaxIdleTimeInMs() {
+    return maxIdleTimeInMs;
+  }
+
   @Override
   public String getHost() {
     return host;
@@ -3583,8 +3711,8 @@ public class SessionPool implements ISessionPool {
   @Override
   public void setFetchSize(int fetchSize) {
     this.fetchSize = fetchSize;
-    for (ISession session : queue) {
-      session.setFetchSize(fetchSize);
+    for (IdleSession idleSession : queue) {
+      idleSession.session.setFetchSize(fetchSize);
     }
     for (ISession session : occupied.keySet()) {
       session.setFetchSize(fetchSize);
@@ -3614,8 +3742,8 @@ public class SessionPool implements ISessionPool {
       }
     }
     this.zoneId = ZoneId.of(zoneId);
-    for (ISession session : queue) {
-      session.setTimeZoneOfSession(zoneId);
+    for (IdleSession idleSession : queue) {
+      idleSession.session.setTimeZoneOfSession(zoneId);
     }
     for (ISession session : occupied.keySet()) {
       session.setTimeZoneOfSession(zoneId);
@@ -3644,8 +3772,8 @@ public class SessionPool implements ISessionPool {
       deviceIdToEndpoint = new ConcurrentHashMap<>();
       tableModelDeviceIdToEndpoint = new ConcurrentHashMap<>();
     }
-    for (ISession session : queue) {
-      session.setEnableRedirection(enableRedirection);
+    for (IdleSession idleSession : queue) {
+      idleSession.session.setEnableRedirection(enableRedirection);
     }
     for (ISession session : occupied.keySet()) {
       session.setEnableRedirection(enableRedirection);
@@ -3660,8 +3788,8 @@ public class SessionPool implements ISessionPool {
   @Override
   public void setEnableQueryRedirection(boolean enableQueryRedirection) {
     this.enableQueryRedirection = enableQueryRedirection;
-    for (ISession session : queue) {
-      session.setEnableQueryRedirection(enableQueryRedirection);
+    for (IdleSession idleSession : queue) {
+      idleSession.session.setEnableQueryRedirection(enableQueryRedirection);
     }
     for (ISession session : occupied.keySet()) {
       session.setEnableQueryRedirection(enableQueryRedirection);
@@ -3722,8 +3850,8 @@ public class SessionPool implements ISessionPool {
   @Override
   public void setVersion(Version version) {
     this.version = version;
-    for (ISession session : queue) {
-      session.setVersion(version);
+    for (IdleSession idleSession : queue) {
+      idleSession.session.setVersion(version);
     }
     for (ISession session : occupied.keySet()) {
       session.setVersion(version);
@@ -3738,8 +3866,8 @@ public class SessionPool implements ISessionPool {
   @Override
   public void setQueryTimeout(long timeoutInMs) {
     this.queryTimeoutInMs = timeoutInMs;
-    for (ISession session : queue) {
-      session.setQueryTimeout(timeoutInMs);
+    for (IdleSession idleSession : queue) {
+      idleSession.session.setQueryTimeout(timeoutInMs);
     }
     for (ISession session : occupied.keySet()) {
       session.setQueryTimeout(timeoutInMs);
@@ -3751,6 +3879,17 @@ public class SessionPool implements ISessionPool {
     return queryTimeoutInMs;
   }
 
+  private static final class IdleSession {
+    private final ISession session;
+    // monotonic timestamp (System.nanoTime) of the moment this session was 
returned to the pool
+    private final long idleSinceNanos;
+
+    private IdleSession(ISession session, long idleSinceNanos) {
+      this.session = session;
+      this.idleSinceNanos = idleSinceNanos;
+    }
+  }
+
   public static class Builder extends AbstractSessionPoolBuilder {
 
     public Builder useSSL(boolean useSSL) {
@@ -3807,6 +3946,36 @@ public class SessionPool implements ISessionPool {
       return this;
     }
 
+    /**
+     * Sets the minimum number of sessions kept in the pool. Idle sessions 
will not be evicted when
+     * the total number of sessions reaches this value.
+     *
+     * <p>Note that sessions are still created lazily on demand: the pool 
never pre-warms {@code
+     * coreSize} sessions at construction time. This value only takes effect 
when {@link
+     * #maxIdleTimeInMs(long)} is positive, and it bounds the total number of 
sessions (borrowed and
+     * idle), not the number of idle sessions alone.
+     *
+     * @param coreSize the minimum number of sessions, must be in [0, maxSize]
+     * @return this builder
+     */
+    public Builder coreSize(int coreSize) {
+      this.coreSize = coreSize;
+      return this;
+    }
+
+    /**
+     * Sets the maximum time in milliseconds that an idle session can stay in 
the pool. Idle
+     * sessions are evicted until the total number of sessions drops to the 
core size. 0 means idle
+     * sessions are never evicted.
+     *
+     * @param maxIdleTimeInMs the maximum idle time in milliseconds, must not 
be negative
+     * @return this builder
+     */
+    public Builder maxIdleTimeInMs(long maxIdleTimeInMs) {
+      this.maxIdleTimeInMs = maxIdleTimeInMs;
+      return this;
+    }
+
     public Builder user(String user) {
       this.username = user;
       return this;
diff --git 
a/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/TableSessionPoolBuilder.java
 
b/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/TableSessionPoolBuilder.java
index fbd071a092b..99c0e3ce033 100644
--- 
a/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/TableSessionPoolBuilder.java
+++ 
b/iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/TableSessionPoolBuilder.java
@@ -63,6 +63,38 @@ public class TableSessionPoolBuilder extends 
AbstractSessionPoolBuilder {
     return this;
   }
 
+  /**
+   * Sets the minimum number of sessions kept in the pool. Idle sessions will 
not be evicted when
+   * the total number of sessions reaches this value.
+   *
+   * <p>Note that sessions are still created lazily on demand: the pool never 
pre-warms {@code
+   * coreSize} sessions at construction time. This value only takes effect 
when {@link
+   * #maxIdleTimeInMs(long)} is positive, and it bounds the total number of 
sessions (borrowed and
+   * idle), not the number of idle sessions alone.
+   *
+   * @param coreSize the minimum number of sessions, must be in [0, maxSize].
+   * @return the current {@link TableSessionPoolBuilder} instance.
+   * @defaultValue 0
+   */
+  public TableSessionPoolBuilder coreSize(int coreSize) {
+    this.coreSize = coreSize;
+    return this;
+  }
+
+  /**
+   * Sets the maximum time in milliseconds that an idle session can stay in 
the pool. Idle sessions
+   * are evicted until the total number of sessions drops to the core size. 0 
means idle sessions
+   * are never evicted.
+   *
+   * @param maxIdleTimeInMs the maximum idle time in milliseconds, must not be 
negative.
+   * @return the current {@link TableSessionPoolBuilder} instance.
+   * @defaultValue 0
+   */
+  public TableSessionPoolBuilder maxIdleTimeInMs(long maxIdleTimeInMs) {
+    this.maxIdleTimeInMs = maxIdleTimeInMs;
+    return this;
+  }
+
   /**
    * Sets the username for the connection.
    *
diff --git 
a/iotdb-client/session/src/test/java/org/apache/iotdb/session/BrokenSessionConnectionTest.java
 
b/iotdb-client/session/src/test/java/org/apache/iotdb/session/BrokenSessionConnectionTest.java
index 952edb49f64..351be2c9642 100644
--- 
a/iotdb-client/session/src/test/java/org/apache/iotdb/session/BrokenSessionConnectionTest.java
+++ 
b/iotdb-client/session/src/test/java/org/apache/iotdb/session/BrokenSessionConnectionTest.java
@@ -20,7 +20,6 @@
 package org.apache.iotdb.session;
 
 import org.apache.iotdb.common.rpc.thrift.TEndPoint;
-import org.apache.iotdb.isession.ISession;
 import org.apache.iotdb.isession.SessionConfig;
 import org.apache.iotdb.rpc.DeepCopyRpcTransportFactory;
 import org.apache.iotdb.rpc.IoTDBConnectionException;
@@ -162,8 +161,8 @@ public class BrokenSessionConnectionTest {
             .enableAutoFetch(false)
             .build();
     try {
-      ConcurrentLinkedDeque<ISession> queue = Whitebox.getInternalState(pool, 
"queue");
-      queue.add(brokenSession);
+      ConcurrentLinkedDeque<?> queue = Whitebox.getInternalState(pool, 
"queue");
+      Whitebox.invokeMethod(pool, "putBack", brokenSession);
       Whitebox.setInternalState(pool, "size", 1);
 
       // Each call fails, but with a connection error, and the broken session 
must not be reused.
@@ -178,18 +177,27 @@ public class BrokenSessionConnectionTest {
               "call "
                   + call
                   + ": the pool reused the broken session"
-                  + (queue.contains(brokenSession) ? " (still queued)" : ""),
+                  + (containsSession(queue, brokenSession) ? " (still queued)" 
: ""),
               e);
         }
         assertFalse(
             "call " + call + ": broken session was put back into the pool",
-            queue.contains(brokenSession));
+            containsSession(queue, brokenSession));
       }
     } finally {
       pool.close();
     }
   }
 
+  private static boolean containsSession(ConcurrentLinkedDeque<?> queue, 
Object session) {
+    for (Object idleSession : queue) {
+      if (Whitebox.getInternalState(idleSession, "session") == session) {
+        return true;
+      }
+    }
+    return false;
+  }
+
   private Session newSession() {
     return new Session.Builder()
         .nodeUrls(Collections.singletonList(deadEndPoint.getIp() + ":" + 
deadEndPoint.getPort()))
diff --git 
a/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/SessionPoolExceptionTest.java
 
b/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/SessionPoolExceptionTest.java
index 4ec78e6306a..80d2d3c7429 100644
--- 
a/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/SessionPoolExceptionTest.java
+++ 
b/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/SessionPoolExceptionTest.java
@@ -78,9 +78,7 @@ public class SessionPoolExceptionTest {
             .maxSize(10)
             .enableAutoFetch(false)
             .build();
-    ConcurrentLinkedDeque<ISession> queue = new ConcurrentLinkedDeque<>();
-    queue.add(session);
-    Whitebox.setInternalState(sessionPool, "queue", queue);
+    ((SessionPool) sessionPool).putBack(session);
   }
 
   @After
@@ -253,9 +251,6 @@ public class SessionPoolExceptionTest {
 
   @Test
   public void testInsertRecords2() throws Exception {
-    ConcurrentLinkedDeque<ISession> queue = new ConcurrentLinkedDeque<>();
-    queue.add(session);
-    Whitebox.setInternalState(sessionPool, "queue", queue);
     List<String> deviceIds = Arrays.asList("device1", "device2");
     List<Long> timeList = Arrays.asList(1L, 2L);
     List<List<String>> measurementsList =
diff --git 
a/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/SessionPoolTest.java
 
b/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/SessionPoolTest.java
index 086532ff2aa..9dbb98712f1 100644
--- 
a/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/SessionPoolTest.java
+++ 
b/iotdb-client/session/src/test/java/org/apache/iotdb/session/pool/SessionPoolTest.java
@@ -25,6 +25,7 @@ import org.apache.iotdb.isession.ISession;
 import org.apache.iotdb.isession.ITableSession;
 import org.apache.iotdb.isession.SessionDataSet;
 import org.apache.iotdb.isession.pool.ISessionPool;
+import org.apache.iotdb.isession.pool.ITableSessionPool;
 import org.apache.iotdb.isession.pool.SessionDataSetWrapper;
 import org.apache.iotdb.isession.template.Template;
 import org.apache.iotdb.isession.util.Version;
@@ -85,6 +86,9 @@ import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
@@ -108,7 +112,7 @@ public class SessionPoolTest {
   @Mock private TSFetchMetadataResp fetchMetadataResp;
   @Mock private TSFetchResultsResp fetchResultsResp;
 
-  private static class BlockingAfterPollDeque extends 
ConcurrentLinkedDeque<ISession> {
+  private static class BlockingAfterPollDeque extends 
ConcurrentLinkedDeque<Object> {
 
     private final SessionPool pool;
     private final CountDownLatch polled = new CountDownLatch(1);
@@ -119,8 +123,8 @@ public class SessionPoolTest {
     }
 
     @Override
-    public ISession poll() {
-      ISession session = super.poll();
+    public Object poll() {
+      Object session = super.poll();
       if (session != null && shouldBlock.compareAndSet(true, false)) {
         polled.countDown();
         // getSession holds the pool monitor here. Waiting releases it so 
close() can run before
@@ -238,6 +242,325 @@ public class SessionPoolTest {
     assertEquals(Version.V_0_13, pool.getVersion());
   }
 
+  @Test
+  public void testBuilderCoreSizeAndMaxIdleTime() {
+    SessionPool pool =
+        new SessionPool.Builder()
+            .host("localhost")
+            .port(1234)
+            .maxSize(10)
+            .coreSize(3)
+            .maxIdleTimeInMs(5_000L)
+            .enableAutoFetch(false)
+            .build();
+    try {
+      assertEquals(3, pool.getCoreSize());
+      assertEquals(5_000L, pool.getMaxIdleTimeInMs());
+    } finally {
+      pool.close();
+    }
+  }
+
+  @Test
+  public void testBuilderPoolDefaultsDisableEviction() {
+    SessionPool pool =
+        new SessionPool.Builder()
+            .host("localhost")
+            .port(1234)
+            .maxSize(5)
+            .enableAutoFetch(false)
+            .build();
+    try {
+      assertEquals(0, pool.getCoreSize());
+      assertEquals(0L, pool.getMaxIdleTimeInMs());
+      // no eviction task is registered when maxIdleTimeInMs is 0
+      assertNull(Whitebox.getInternalState(pool, "idleEvictor"));
+    } finally {
+      pool.close();
+    }
+  }
+
+  @Test
+  public void testNoEvictorWhenPoolCannotShrink() {
+    SessionPool pool =
+        new SessionPool.Builder()
+            .host("localhost")
+            .port(1234)
+            .maxSize(5)
+            .coreSize(5)
+            .maxIdleTimeInMs(1_000L)
+            .enableAutoFetch(false)
+            .build();
+    try {
+      // coreSize == maxSize means size can never exceed coreSize, so eviction 
would be a no-op
+      assertNull(Whitebox.getInternalState(pool, "idleEvictor"));
+    } finally {
+      pool.close();
+    }
+  }
+
+  @Test
+  public void testTableSessionPoolBuilderCoreSizeAndMaxIdleTime() {
+    ITableSessionPool tableSessionPool =
+        new TableSessionPoolBuilder()
+            .nodeUrls(Collections.singletonList("127.0.0.1:6667"))
+            .maxSize(5)
+            .coreSize(2)
+            .maxIdleTimeInMs(1_000L)
+            .enableAutoFetch(false)
+            .build();
+    try {
+      SessionPool pool = Whitebox.getInternalState(tableSessionPool, 
"sessionPool");
+      assertEquals(2, pool.getCoreSize());
+      assertEquals(1_000L, pool.getMaxIdleTimeInMs());
+    } finally {
+      tableSessionPool.close();
+    }
+  }
+
+  @Test
+  public void testIllegalCoreSize() {
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            new 
SessionPool.Builder().host("localhost").port(1234).maxSize(5).coreSize(6).build());
+    assertThrows(
+        IllegalArgumentException.class,
+        () -> new 
SessionPool.Builder().host("localhost").port(1234).coreSize(-1).build());
+  }
+
+  @Test
+  public void testIllegalMaxIdleTime() {
+    assertThrows(
+        IllegalArgumentException.class,
+        () -> new 
SessionPool.Builder().host("localhost").port(1234).maxIdleTimeInMs(-1).build());
+  }
+
+  @Test
+  public void testIllegalMaxSize() {
+    IllegalArgumentException zeroMaxSize =
+        assertThrows(
+            IllegalArgumentException.class,
+            () -> new 
SessionPool.Builder().host("localhost").port(1234).maxSize(0).build());
+    assertTrue(zeroMaxSize.getMessage().contains("maxSize"));
+    assertThrows(
+        IllegalArgumentException.class,
+        () -> new 
SessionPool.Builder().host("localhost").port(1234).maxSize(-1).build());
+  }
+
+  @Test
+  public void testIllegalArgumentsForTableSessionPoolBuilder() {
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            new TableSessionPoolBuilder()
+                .nodeUrls(Collections.singletonList("127.0.0.1:6667"))
+                .maxSize(5)
+                .coreSize(6)
+                .build());
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            new TableSessionPoolBuilder()
+                .nodeUrls(Collections.singletonList("127.0.0.1:6667"))
+                .maxSize(5)
+                .maxIdleTimeInMs(-1)
+                .build());
+    assertThrows(
+        IllegalArgumentException.class,
+        () ->
+            new TableSessionPoolBuilder()
+                .nodeUrls(Collections.singletonList("127.0.0.1:6667"))
+                .maxSize(0)
+                .build());
+  }
+
+  @Test
+  public void testEvictIdleSessions() throws Exception {
+    SessionPool pool = newEvictionPool(10, 2);
+    try {
+      List<ISession> sessions = new ArrayList<>();
+      for (int i = 0; i < 5; i++) {
+        sessions.add(Mockito.mock(ISession.class));
+      }
+      // push puts a session at the head, so sessions.get(0) ends up at the 
tail (earliest idle)
+      for (ISession s : sessions) {
+        putBackExpired(pool, s, 120_000L);
+      }
+      Whitebox.setInternalState(pool, "size", 5);
+
+      Whitebox.invokeMethod(pool, "evictIdleSessions");
+
+      assertEquals(2, idleQueueOf(pool).size());
+      assertEquals(2, ((Integer) Whitebox.getInternalState(pool, 
"size")).intValue());
+      // the 3 earliest idle sessions are evicted, the 2 most recently 
returned ones are kept
+      Mockito.verify(sessions.get(0)).close();
+      Mockito.verify(sessions.get(1)).close();
+      Mockito.verify(sessions.get(2)).close();
+      Mockito.verify(sessions.get(3), Mockito.never()).close();
+      Mockito.verify(sessions.get(4), Mockito.never()).close();
+    } finally {
+      pool.close();
+    }
+  }
+
+  @Test
+  public void testEvictIdleSessionsStopsAtFirstNonExpired() throws Exception {
+    // a fresh session at the head must stop the tail-to-head scan even when 
size > coreSize
+    SessionPool pool = newEvictionPool(10, 0);
+    try {
+      ISession oldest = Mockito.mock(ISession.class);
+      ISession middle = Mockito.mock(ISession.class);
+      ISession fresh = Mockito.mock(ISession.class);
+      putBackExpired(pool, oldest, 120_000L);
+      putBackExpired(pool, middle, 120_000L);
+      pool.putBack(fresh);
+      Whitebox.setInternalState(pool, "size", 3);
+
+      Whitebox.invokeMethod(pool, "evictIdleSessions");
+
+      assertEquals(1, idleQueueOf(pool).size());
+      assertEquals(1, ((Integer) Whitebox.getInternalState(pool, 
"size")).intValue());
+      Mockito.verify(oldest).close();
+      Mockito.verify(middle).close();
+      Mockito.verify(fresh, Mockito.never()).close();
+    } finally {
+      pool.close();
+    }
+  }
+
+  @Test
+  public void testEvictIdleSessionsWithCoreSizeZeroEvictsAll() throws 
Exception {
+    SessionPool pool = newEvictionPool(10, 0);
+    try {
+      for (int i = 0; i < 3; i++) {
+        putBackExpired(pool, Mockito.mock(ISession.class), 120_000L);
+      }
+      Whitebox.setInternalState(pool, "size", 3);
+
+      Whitebox.invokeMethod(pool, "evictIdleSessions");
+
+      assertEquals(0, idleQueueOf(pool).size());
+      assertEquals(0, ((Integer) Whitebox.getInternalState(pool, 
"size")).intValue());
+    } finally {
+      pool.close();
+    }
+  }
+
+  @Test
+  public void testEvictIdleSessionsCountsBorrowedSessionsTowardsCoreSize() 
throws Exception {
+    // coreSize bounds the total number of sessions (borrowed + idle), not 
just idle ones
+    SessionPool pool = newEvictionPool(10, 2);
+    try {
+      ISession borrowed = Mockito.mock(ISession.class);
+      Whitebox.invokeMethod(pool, "occupy", borrowed);
+      ISession idle1 = Mockito.mock(ISession.class);
+      ISession idle2 = Mockito.mock(ISession.class);
+      putBackExpired(pool, idle1, 120_000L);
+      putBackExpired(pool, idle2, 120_000L);
+      Whitebox.setInternalState(pool, "size", 3);
+
+      Whitebox.invokeMethod(pool, "evictIdleSessions");
+
+      // size 3 -> 2: only one idle session may be evicted although both are 
expired
+      assertEquals(1, idleQueueOf(pool).size());
+      assertEquals(2, ((Integer) Whitebox.getInternalState(pool, 
"size")).intValue());
+      assertEquals(1, pool.currentOccupiedSize());
+      Mockito.verify(borrowed, Mockito.never()).close();
+    } finally {
+      pool.close();
+    }
+  }
+
+  @Test
+  public void testEvictIdleSessionsWithEmptyQueueIsNoOp() throws Exception {
+    // all sessions are borrowed: the queue is empty, eviction must not touch 
occupied sessions
+    SessionPool pool = newEvictionPool(10, 0);
+    try {
+      ISession borrowed = Mockito.mock(ISession.class);
+      Whitebox.invokeMethod(pool, "occupy", borrowed);
+      Whitebox.setInternalState(pool, "size", 1);
+
+      Whitebox.invokeMethod(pool, "evictIdleSessions");
+
+      assertEquals(0, idleQueueOf(pool).size());
+      assertEquals(1, ((Integer) Whitebox.getInternalState(pool, 
"size")).intValue());
+      Mockito.verify(borrowed, Mockito.never()).close();
+    } finally {
+      pool.close();
+    }
+  }
+
+  @Test
+  public void testEvictIdleSessionsIsNoOpAfterClose() throws Exception {
+    SessionPool pool = newEvictionPool(10, 0);
+    pool.close();
+
+    Whitebox.invokeMethod(pool, "evictIdleSessions");
+
+    assertEquals(0, idleQueueOf(pool).size());
+    assertEquals(0, ((Integer) Whitebox.getInternalState(pool, 
"size")).intValue());
+  }
+
+  @Test(timeout = 15_000)
+  public void testScheduledEvictionRunsAndStopsOnClose() throws Exception {
+    SessionPool pool =
+        new SessionPool.Builder()
+            .host("localhost")
+            .port(1234)
+            .maxSize(5)
+            .coreSize(0)
+            .maxIdleTimeInMs(1_000L)
+            .enableAutoFetch(false)
+            .build();
+    try {
+      assertNotNull(Whitebox.getInternalState(pool, "idleEvictor"));
+      ISession session1 = Mockito.mock(ISession.class);
+      ISession session2 = Mockito.mock(ISession.class);
+      putBackExpired(pool, session1, 20_000L);
+      putBackExpired(pool, session2, 20_000L);
+      Whitebox.setInternalState(pool, "size", 2);
+
+      // the check interval is 1s, so eviction should happen well within the 
timeout
+      long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
+      while (pool.currentAvailableSize() > 0 && System.nanoTime() < deadline) {
+        Thread.sleep(50L);
+      }
+
+      assertEquals(0, pool.currentAvailableSize());
+      assertEquals(0, ((Integer) Whitebox.getInternalState(pool, 
"size")).intValue());
+    } finally {
+      pool.close();
+    }
+    assertNull(Whitebox.getInternalState(pool, "idleEvictor"));
+  }
+
+  private static SessionPool newEvictionPool(int maxSize, int coreSize) {
+    return new SessionPool.Builder()
+        .host("localhost")
+        .port(1234)
+        .maxSize(maxSize)
+        .coreSize(coreSize)
+        // a long threshold keeps the background evictor (interval = max(1s, 
threshold / 2))
+        // from racing with the manually triggered eviction in these tests
+        .maxIdleTimeInMs(60_000L)
+        .enableAutoFetch(false)
+        .build();
+  }
+
+  private static void putBackExpired(SessionPool pool, ISession session, long 
idleForMs) {
+    pool.putBack(session);
+    Whitebox.setInternalState(
+        idleQueueOf(pool).peekFirst(),
+        "idleSinceNanos",
+        System.nanoTime() - TimeUnit.MILLISECONDS.toNanos(idleForMs));
+  }
+
+  @SuppressWarnings("unchecked")
+  private static ConcurrentLinkedDeque<Object> idleQueueOf(SessionPool pool) {
+    return Whitebox.getInternalState(pool, "queue");
+  }
+
   @Before
   public void setUp() throws IoTDBConnectionException, 
StatementExecutionException, TException {
     // Initialize the session pool before each test
@@ -267,11 +590,8 @@ public class SessionPoolTest {
             .enableAutoFetch(false)
             .build();
 
-    ConcurrentLinkedDeque<ISession> queue = new ConcurrentLinkedDeque<>();
-    queue.add(session);
-
-    // set SessionPool's internal field state
-    Whitebox.setInternalState(sessionPool, "queue", queue);
+    // set SessionPool's internal field state: one idle session in the queue
+    ((SessionPool) sessionPool).putBack(session);
   }
 
   @After
@@ -1335,9 +1655,7 @@ public class SessionPoolTest {
   public void testRestoreFailureKeepsPoolCapacity() throws Exception {
     Session replacementSession = Mockito.mock(Session.class);
     SessionPool concreteSessionPool = new 
MockReplacementSessionPool(replacementSession);
-    ConcurrentLinkedDeque<ISession> queue = new ConcurrentLinkedDeque<>();
-    queue.add(session);
-    Whitebox.setInternalState(concreteSessionPool, "queue", queue);
+    concreteSessionPool.putBack(session);
     Whitebox.setInternalState(concreteSessionPool, "size", 1);
     
Mockito.when(session.getSqlDialect()).thenReturn(concreteSessionPool.sqlDialect 
+ "_borrowed");
     Mockito.doThrow(new StatementExecutionException("restore failed"))
@@ -1350,11 +1668,11 @@ public class SessionPoolTest {
       assertEquals(0, concreteSessionPool.currentOccupiedSize());
       assertEquals(
           1, ((Integer) Whitebox.getInternalState(concreteSessionPool, 
"size")).intValue());
-      assertEquals(
-          replacementSession,
-          ((ConcurrentLinkedDeque<ISession>)
-                  Whitebox.getInternalState(concreteSessionPool, "queue"))
-              .peek());
+      Object head =
+          ((ConcurrentLinkedDeque<?>) 
Whitebox.getInternalState(concreteSessionPool, "queue"))
+              .peek();
+      assertNotNull(head);
+      assertEquals(replacementSession, Whitebox.getInternalState(head, 
"session"));
       Mockito.verify(session).close();
     } finally {
       concreteSessionPool.close();
@@ -1365,9 +1683,7 @@ public class SessionPoolTest {
   public void testConnectionFailureReleasesCapacityAndClosesWrapper() throws 
Exception {
     Session replacementSession = Mockito.mock(Session.class);
     SessionPool concreteSessionPool = new 
MockReplacementSessionPool(replacementSession);
-    ConcurrentLinkedDeque<ISession> queue = new ConcurrentLinkedDeque<>();
-    queue.add(session);
-    Whitebox.setInternalState(concreteSessionPool, "queue", queue);
+    concreteSessionPool.putBack(session);
     Whitebox.setInternalState(concreteSessionPool, "size", 1);
     Mockito.doThrow(new IoTDBConnectionException("connection failed"))
         .when(session)
@@ -1392,11 +1708,11 @@ public class SessionPoolTest {
       assertEquals(0, concreteSessionPool.currentOccupiedSize());
       assertEquals(
           1, ((Integer) Whitebox.getInternalState(concreteSessionPool, 
"size")).intValue());
-      assertEquals(
-          replacementSession,
-          ((ConcurrentLinkedDeque<ISession>)
-                  Whitebox.getInternalState(concreteSessionPool, "queue"))
-              .peek());
+      Object head =
+          ((ConcurrentLinkedDeque<?>) 
Whitebox.getInternalState(concreteSessionPool, "queue"))
+              .peek();
+      assertNotNull(head);
+      assertEquals(replacementSession, Whitebox.getInternalState(head, 
"session"));
       Mockito.verify(session).close();
     } finally {
       concreteSessionPool.close();
@@ -1445,8 +1761,8 @@ public class SessionPoolTest {
   public void testTableSessionBorrowRacingWithPoolClose() throws Exception {
     SessionPool concreteSessionPool = (SessionPool) sessionPool;
     BlockingAfterPollDeque blockingQueue = new 
BlockingAfterPollDeque(concreteSessionPool);
-    blockingQueue.add(session);
     Whitebox.setInternalState(concreteSessionPool, "queue", blockingQueue);
+    concreteSessionPool.putBack(session);
     ExecutorService executor = Executors.newSingleThreadExecutor();
     try {
       Future<ITableSession> borrowFuture =

Reply via email to