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

Wei-hao-Li pushed a commit to branch poolConf
in repository https://gitbox.apache.org/repos/asf/iotdb.git

commit 3dc3cd89e8135956771c63e1b6518829828c0aac
Author: Weihao Li <[email protected]>
AuthorDate: Fri Nov 27 09:15:47 2026 +0800

    implement
    
    Signed-off-by: Weihao Li <[email protected]>
---
 .../org/apache/iotdb/isession/SessionConfig.java   |   5 +
 .../apache/iotdb/session/i18n/SessionMessages.java |   8 ++
 .../apache/iotdb/session/i18n/SessionMessages.java |   8 ++
 .../session/pool/AbstractSessionPoolBuilder.java   |   2 +
 .../org/apache/iotdb/session/pool/SessionPool.java | 135 ++++++++++++++---
 .../session/pool/TableSessionPoolBuilder.java      |  27 ++++
 .../iotdb/session/BrokenSessionConnectionTest.java |  18 ++-
 .../session/pool/SessionPoolExceptionTest.java     |   8 +-
 .../apache/iotdb/session/pool/SessionPoolTest.java | 160 ++++++++++++++++++++-
 9 files changed, 336 insertions(+), 35 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 7885d50cf5d..3edc70ff1fe 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 280a8414d6e..cc3f1a1dafd 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,14 @@ 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_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: {}";
+
   // 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 cee0512a23a..99a86c051fe 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,14 @@ 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_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:{}";
+
   // 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 86d11063480..0f01600222b 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<>();
   // for session whose resultSet is not released.
   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
@@ -526,8 +529,19 @@ public class SessionPool implements ISessionPool {
     initAvailableNodes(SessionUtils.parseSeedNodeUrls(this.nodeUrls));
   }
 
+  @SuppressWarnings("unsafeThreadSchedule")
   public SessionPool(AbstractSessionPoolBuilder builder) {
     this.maxSize = builder.maxSize;
+    this.coreSize = builder.coreSize;
+    this.maxIdleTimeInMs = builder.maxIdleTimeInMs;
+    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));
+    }
     this.user = builder.username;
     this.password = builder.pw;
     this.fetchSize = builder.fetchSize;
@@ -589,6 +603,15 @@ public class SessionPool implements ISessionPool {
     } else {
       this.availableNodes = new DummyNodesSupplier(endPointList);
     }
+
+    if (maxIdleTimeInMs > 0) {
+      if (executorService == null) {
+        initThreadPool();
+      }
+      long checkIntervalInMs = Math.max(1_000L, Math.min(maxIdleTimeInMs, 
60_000L));
+      executorService.scheduleWithFixedDelay(
+          this::evictIdleSessions, checkIntervalInMs, checkIntervalInMs, 
TimeUnit.MILLISECONDS);
+    }
   }
 
   private Session constructNewSession() {
@@ -707,7 +730,8 @@ public class SessionPool implements ISessionPool {
   // is incorrect.
   @SuppressWarnings({"squid:S3776", "squid:S2446"}) // Suppress high Cognitive 
Complexity warning
   private ISession getSession() throws IoTDBConnectionException {
-    ISession session = queue.poll();
+    IdleSession idleSession = queue.poll();
+    ISession session = idleSession == null ? null : idleSession.session;
     if (closed) {
       throw new IoTDBConnectionException(SESSION_POOL_IS_CLOSED);
     }
@@ -757,7 +781,8 @@ public class SessionPool implements ISessionPool {
           // wake up from this.wait(1000) by this.notify()
         }
 
-        session = queue.poll();
+        idleSession = queue.poll();
+        session = idleSession == null ? null : idleSession.session;
 
         // for putBack or size--
         this.notify();
@@ -821,7 +846,7 @@ public class SessionPool implements ISessionPool {
   protected void putBack(ISession session) {
     synchronized (this) {
       if (!closed) {
-        queue.push(session);
+        queue.push(new IdleSession(session, System.currentTimeMillis()));
         // 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.
@@ -842,9 +867,9 @@ public class SessionPool implements ISessionPool {
   /** close all connections in the pool */
   @Override
   public synchronized void close() {
-    for (ISession session : queue) {
+    for (IdleSession idleSession : queue) {
       try {
-        session.close();
+        idleSession.session.close();
       } catch (IoTDBConnectionException e) {
         // do nothing
         LOGGER.warn(CLOSE_THE_SESSION_FAILED, e);
@@ -926,7 +951,7 @@ public class SessionPool implements ISessionPool {
           session.close();
           throw new IoTDBConnectionException(SESSION_POOL_IS_CLOSED);
         }
-        queue.push(session);
+        queue.push(new IdleSession(session, System.currentTimeMillis()));
         this.notify();
       }
     } catch (IoTDBConnectionException e) {
@@ -938,6 +963,43 @@ public class SessionPool implements ISessionPool {
     }
   }
 
+  /**
+   * 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 now = System.currentTimeMillis();
+      while (size > coreSize) {
+        IdleSession idleSession = queue.peekLast();
+        if (idleSession == null || now - idleSession.idleSince <= 
maxIdleTimeInMs) {
+          break;
+        }
+        queue.pollLast();
+        size--;
+        evicted.add(idleSession.session);
+      }
+      sizeAfterEviction = size;
+      if (!evicted.isEmpty()) {
+        // wake up waiters so that they can create new sessions if size < 
maxSize.
+        this.notify();
+      }
+    }
+    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 {
@@ -3523,8 +3585,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);
@@ -3554,8 +3616,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);
@@ -3584,8 +3646,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);
@@ -3600,8 +3662,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);
@@ -3662,8 +3724,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);
@@ -3678,8 +3740,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);
@@ -3691,6 +3753,16 @@ public class SessionPool implements ISessionPool {
     return queryTimeoutInMs;
   }
 
+  private static final class IdleSession {
+    private final ISession session;
+    private final long idleSince;
+
+    private IdleSession(ISession session, long idleSince) {
+      this.session = session;
+      this.idleSince = idleSince;
+    }
+  }
+
   public static class Builder extends AbstractSessionPoolBuilder {
 
     public Builder useSSL(boolean useSSL) {
@@ -3747,6 +3819,31 @@ 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.
+     *
+     * @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..a34867ae806 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,33 @@ 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.
+   *
+   * @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..5fe667ca459 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,7 @@ public class SessionPoolExceptionTest {
 
   @Test
   public void testInsertRecords2() throws Exception {
-    ConcurrentLinkedDeque<ISession> queue = new ConcurrentLinkedDeque<>();
-    queue.add(session);
-    Whitebox.setInternalState(sessionPool, "queue", queue);
+    ((SessionPool) sessionPool).putBack(session);
     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 d08625cb978..41ef512a319 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
@@ -24,6 +24,7 @@ import org.apache.iotdb.common.rpc.thrift.TSStatus;
 import org.apache.iotdb.isession.ISession;
 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;
@@ -76,6 +77,8 @@ import java.util.Map;
 import java.util.concurrent.ConcurrentLinkedDeque;
 
 import static org.junit.Assert.assertEquals;
+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.eq;
@@ -167,6 +170,156 @@ 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();
+    int coreSize = Whitebox.getInternalState(pool, "coreSize");
+    long maxIdleTimeInMs = Whitebox.getInternalState(pool, "maxIdleTimeInMs");
+    assertEquals(3, coreSize);
+    assertEquals(5_000L, maxIdleTimeInMs);
+    pool.close();
+  }
+
+  @Test
+  public void testBuilderPoolDefaultsDisableEviction() {
+    SessionPool pool =
+        new SessionPool.Builder()
+            .host("localhost")
+            .port(1234)
+            .maxSize(5)
+            .enableAutoFetch(false)
+            .build();
+    int coreSize = Whitebox.getInternalState(pool, "coreSize");
+    long maxIdleTimeInMs = Whitebox.getInternalState(pool, "maxIdleTimeInMs");
+    assertEquals(0, coreSize);
+    assertEquals(0L, maxIdleTimeInMs);
+    // no eviction task is registered when maxIdleTimeInMs is 0
+    assertNull(Whitebox.getInternalState(pool, "executorService"));
+    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();
+    SessionPool pool = Whitebox.getInternalState(tableSessionPool, 
"sessionPool");
+    int coreSize = Whitebox.getInternalState(pool, "coreSize");
+    long maxIdleTimeInMs = Whitebox.getInternalState(pool, "maxIdleTimeInMs");
+    assertEquals(2, coreSize);
+    assertEquals(1_000L, maxIdleTimeInMs);
+    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 testEvictIdleSessions() throws Exception {
+    SessionPool pool =
+        new SessionPool.Builder()
+            .host("localhost")
+            .port(1234)
+            .maxSize(10)
+            .coreSize(2)
+            .maxIdleTimeInMs(5_000L)
+            .enableAutoFetch(false)
+            .build();
+    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)
+      long idleSince = System.currentTimeMillis() - 20_000L;
+      for (ISession s : sessions) {
+        pool.putBack(s);
+        Whitebox.setInternalState(idleQueueOf(pool).peekFirst(), "idleSince", 
idleSince);
+      }
+      Whitebox.setInternalState(pool, "size", 5);
+
+      Whitebox.invokeMethod(pool, "evictIdleSessions");
+
+      assertEquals(2, idleQueueOf(pool).size());
+      int size = Whitebox.getInternalState(pool, "size");
+      assertEquals(2, size);
+      // 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 testEvictIdleSessionsDoesNotGoBelowCoreSize() throws Exception {
+    SessionPool pool =
+        new SessionPool.Builder()
+            .host("localhost")
+            .port(1234)
+            .maxSize(10)
+            .coreSize(3)
+            .maxIdleTimeInMs(5_000L)
+            .enableAutoFetch(false)
+            .build();
+    try {
+      long idleSince = System.currentTimeMillis() - 20_000L;
+      ISession session1 = Mockito.mock(ISession.class);
+      ISession session2 = Mockito.mock(ISession.class);
+      pool.putBack(session1);
+      Whitebox.setInternalState(idleQueueOf(pool).peekFirst(), "idleSince", 
idleSince);
+      pool.putBack(session2);
+      Whitebox.setInternalState(idleQueueOf(pool).peekFirst(), "idleSince", 
idleSince);
+      Whitebox.setInternalState(pool, "size", 2);
+
+      Whitebox.invokeMethod(pool, "evictIdleSessions");
+
+      assertEquals(2, idleQueueOf(pool).size());
+      int size = Whitebox.getInternalState(pool, "size");
+      assertEquals(2, size);
+      Mockito.verify(session1, Mockito.never()).close();
+      Mockito.verify(session2, Mockito.never()).close();
+    } finally {
+      pool.close();
+    }
+  }
+
+  @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
@@ -196,11 +349,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

Reply via email to