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

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-dbcp.git

commit 0a8a1cdfe5d3fc3519480abff43240e21bfa7a1d
Author: Gary Gregory <[email protected]>
AuthorDate: Sun Nov 22 18:53:22 2026 -0500

    Fix JDBC timeout handling and pooled state restoration
    
    Centralize Duration conversion to JDBC seconds, preserving positive
    sub-second timeouts, capping oversized values, and retaining negative
    values for driver validation. Close statements when timeout setup fails.
    
    Restore original query timeouts when returning pooled prepared and
    callable statements. Discard statements if restoration fails and clear
    saved timeout state when replacing delegates.
    
    Apply configured login timeouts to physical connection attempts with
    provider-scoped coordination, bounded waits, and failure cleanup.
    Restore
    provider settings afterwards and preserve live configuration across
    deserialization.
    
    Preserve DriverAdapterCPDS eviction durations through JNDI References,
    preferring Duration properties and accepting legacy long millisecond
    values.
    
    Undeprecate DelegatingConnection.isValid(int) while preserving existing
    overload dispatch.
    
    Update Javadoc and release notes. Add regression coverage for timeout
    boundaries, statement reuse, failure paths, JNDI, serialization, and
    concurrent provider access.
---
 src/changes/changes.xml                            |   5 +
 .../org/apache/commons/dbcp2/BasicDataSource.java  |   5 +
 .../apache/commons/dbcp2/DelegatingConnection.java |  38 +-
 .../commons/dbcp2/DelegatingPreparedStatement.java |  33 +-
 .../commons/dbcp2/PoolableCallableStatement.java   |   5 +
 .../apache/commons/dbcp2/PoolableConnection.java   |   3 +-
 .../commons/dbcp2/PoolablePreparedStatement.java   |   6 +
 src/main/java/org/apache/commons/dbcp2/Utils.java  |  19 +
 .../dbcp2/cpdsadapter/DriverAdapterCPDS.java       |  45 +-
 .../datasources/AbstractConnectionFactory.java     |  10 +
 .../dbcp2/datasources/CPDSConnectionFactory.java   |   7 +-
 .../datasources/ConnectionPoolDataSourceUtils.java | 154 ++++++
 .../dbcp2/datasources/InstanceKeyDataSource.java   |  69 ++-
 .../datasources/KeyedCPDSConnectionFactory.java    |   9 +-
 .../dbcp2/datasources/PerUserPoolDataSource.java   |   5 +-
 .../dbcp2/datasources/SharedPoolDataSource.java    |   9 +-
 .../org/apache/commons/dbcp2/TestJdbcTimeouts.java | 436 +++++++++++++++
 .../TestDriverAdapterCPDSReference.java            |  59 ++
 .../dbcp2/datasources/TestLoginTimeout.java        | 591 +++++++++++++++++++++
 19 files changed, 1449 insertions(+), 59 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index b6542149..7a12cc55 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -78,6 +78,11 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="Bill Mitchell, Tiefang Hu, 
Gary Gregory" issue="DBCP-522">Prevent stale cached auto-commit state after 
unchecked failures in DelegatingConnection.setAutoCommit(), preserving rollback 
and auto-commit restoration when pooled connections are returned #549.</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">Invalidate 
cached read-only, catalog, and schema state before driver calls in 
DelegatingConnection so unchecked failures do not leave stale values or prevent 
pooled connection state restoration.</action>
       <action type="fix" dev="ggregory" due-to="Aryan Ganjoo, Gary Gregory" 
issue="DBCP-600">Honor positive sub-second validation timeouts as one JDBC 
second in both validation paths, and cap oversized durations to prevent integer 
overflow #548.</action>
+      <action type="fix" dev="ggregory" due-to="Gary Gregory">Undeprecate 
org.apache.commons.dbcp2.DelegatingConnection.isValid(int) since it implements 
java.sql.Connection.isValid(int).</action>
+      <action type="fix" dev="ggregory" due-to="Gary Gregory">Honor positive 
sub-second default query timeouts and direct connection validation timeouts, 
and cap oversized durations without losing JDBC rejection of negative 
values.</action>
+      <action type="fix" dev="ggregory" due-to="Gary Gregory">Restore the 
original query timeout when returning pooled prepared and callable statements, 
preventing timeout settings from leaking between borrowers.</action>
+      <action type="fix" dev="ggregory" due-to="Gary Gregory">Preserve 
DriverAdapterCPDS eviction durations through JNDI References, preferring 
Duration properties and accepting long legacy millisecond values.</action>
+      <action type="fix" dev="ggregory" due-to="Gary Gregory">Apply 
SharedPoolDataSource and PerUserPoolDataSource login timeouts to every physical 
connection attempt, restoring the underlying provider's timeout afterwards. 
Bound waits to configure the provider, and preserve live timeout settings 
across deserialization.</action>
       <!-- ADD -->
       <action type="add" dev="ggregory" due-to="Gary Gregory">Add 
DriverAdapterCPDS.exportPasswordAsRefAddr to optionally omit the password 
address from JNDI References. Password export remains enabled by default for 
compatibility; the setting survives JNDI lookup and Java serialization.</action>
       <action type="add" dev="ggregory" due-to="Gary Gregory">Add 
PoolingDriver.Builder and PoolingDriver.builder() to configure delegate access 
when creating drivers, preserving the existing permissive default.</action>
diff --git a/src/main/java/org/apache/commons/dbcp2/BasicDataSource.java 
b/src/main/java/org/apache/commons/dbcp2/BasicDataSource.java
index db1ec9c9..7ea9d033 100644
--- a/src/main/java/org/apache/commons/dbcp2/BasicDataSource.java
+++ b/src/main/java/org/apache/commons/dbcp2/BasicDataSource.java
@@ -2097,6 +2097,11 @@ public class BasicDataSource implements DataSource, 
BasicDataSourceMXBean, Dynam
      * Sets the default query timeout that will be used for {@link 
java.sql.Statement Statement}s created from this
      * connection. {@code null} means that the driver default will be used.
      *
+     * <p>
+     * Positive durations use whole seconds, with a minimum of one second and 
a maximum of {@link Integer#MAX_VALUE}.
+     * Zero means no timeout. Negative values are passed to the driver as 
negative seconds for JDBC validation when a statement is created.
+     * </p>
+     *
      * @param defaultQueryTimeoutDuration The default query timeout Duration.
      * @since 2.10.0
      */
diff --git a/src/main/java/org/apache/commons/dbcp2/DelegatingConnection.java 
b/src/main/java/org/apache/commons/dbcp2/DelegatingConnection.java
index e8e53ef0..7a5a7b05 100644
--- a/src/main/java/org/apache/commons/dbcp2/DelegatingConnection.java
+++ b/src/main/java/org/apache/commons/dbcp2/DelegatingConnection.java
@@ -565,8 +565,22 @@ public class DelegatingConnection<C extends Connection> 
extends AbandonedTrace i
      * @throws SQLException Thrown if a database access error occurs, this 
method is called on a closed Statement.
      */
     private <T extends DelegatingStatement> T init(final T 
delegatingStatement) throws SQLException {
-        if (defaultQueryTimeoutDuration != null && 
defaultQueryTimeoutDuration.getSeconds() != 
delegatingStatement.getQueryTimeout()) {
-            delegatingStatement.setQueryTimeout((int) 
defaultQueryTimeoutDuration.getSeconds());
+        if (defaultQueryTimeoutDuration != null) {
+            final int timeoutSeconds = 
Utils.toJdbcSeconds(defaultQueryTimeoutDuration);
+            try {
+                if (timeoutSeconds != delegatingStatement.getQueryTimeout()) {
+                    delegatingStatement.setQueryTimeout(timeoutSeconds);
+                }
+            } catch (final SQLException | RuntimeException e) {
+                try {
+                    delegatingStatement.close();
+                } catch (final SQLException | RuntimeException closeException) 
{
+                    if (e != closeException) {
+                        e.addSuppressed(closeException);
+                    }
+                }
+                throw e;
+            }
         }
         return delegatingStatement;
     }
@@ -618,6 +632,11 @@ public class DelegatingConnection<C extends Connection> 
extends AbandonedTrace i
     /**
      * Tests if the connection has not been closed and is still valid.
      *
+     * <p>
+     * Positive timeouts use whole seconds, with a minimum of one second and a 
maximum of {@link Integer#MAX_VALUE}.
+     * Zero means no timeout; negative values are passed to the driver as 
negative seconds for JDBC validation.
+     * </p>
+     *
      * @param timeout The duration to wait for the database operation used to 
validate the connection to complete.
      * @return See {@link Connection#isValid(int)}.
      * @throws SQLException See {@link Connection#isValid(int)}.
@@ -629,7 +648,7 @@ public class DelegatingConnection<C extends Connection> 
extends AbandonedTrace i
             return false;
         }
         try {
-            return connection.isValid((int) timeout.getSeconds());
+            return connection.isValid(Utils.toJdbcSeconds(timeout));
         } catch (final SQLException e) {
             handleException(e);
             return false;
@@ -637,10 +656,14 @@ public class DelegatingConnection<C extends Connection> 
extends AbandonedTrace i
     }
 
     /**
-     * @deprecated Use {@link #isValid(Duration)}.
+     * Tests if the connection has not been closed and is still valid.
+     *
+     * @param timeoutSeconds The duration to wait for the database operation 
used to validate the connection to complete, in seconds.
+     * @return See {@link Connection#isValid(int)}.
+     * @throws SQLException See {@link Connection#isValid(int)}.
+     * @see Connection#isValid(int)
      */
     @Override
-    @Deprecated
     public boolean isValid(final int timeoutSeconds) throws SQLException {
         return isValid(Duration.ofSeconds(timeoutSeconds));
     }
@@ -935,6 +958,11 @@ public class DelegatingConnection<C extends Connection> 
extends AbandonedTrace i
      * Sets the default query timeout that will be used for {@link Statement}s 
created from this connection.
      * {@code null} means that the driver default will be used.
      *
+     * <p>
+     * Positive durations use whole seconds, with a minimum of one second and 
a maximum of {@link Integer#MAX_VALUE}.
+     * Negative values are passed to the driver as negative seconds for JDBC 
validation when a statement is created.
+     * </p>
+     *
      * @param defaultQueryTimeoutDuration
      *            the new query timeout limit Duration; zero means there is no 
limit.
      * @since 2.10.0
diff --git 
a/src/main/java/org/apache/commons/dbcp2/DelegatingPreparedStatement.java 
b/src/main/java/org/apache/commons/dbcp2/DelegatingPreparedStatement.java
index 89273e92..547093aa 100644
--- a/src/main/java/org/apache/commons/dbcp2/DelegatingPreparedStatement.java
+++ b/src/main/java/org/apache/commons/dbcp2/DelegatingPreparedStatement.java
@@ -32,6 +32,7 @@ import java.sql.RowId;
 import java.sql.SQLException;
 import java.sql.SQLType;
 import java.sql.SQLXML;
+import java.sql.Statement;
 import java.sql.Time;
 import java.sql.Timestamp;
 import java.util.ArrayList;
@@ -52,6 +53,9 @@ import java.util.Objects;
  */
 public class DelegatingPreparedStatement extends DelegatingStatement 
implements PreparedStatement {
 
+    /** Driver timeout before the first change, restored when this statement 
is returned to a pool. */
+    private Integer originalQueryTimeout;
+
     /**
      * Create a wrapper for the Statement which traces this Statement to the 
Connection which created it and the code
      * which created it.
@@ -168,7 +172,8 @@ public class DelegatingPreparedStatement extends 
DelegatingStatement implements
     }
 
     /**
-     * Prepares internal states before calling {@link #passivate()}.
+     * Prepares internal states before calling {@link #passivate()}, restoring 
any saved query timeout.
+     * A failure to restore the timeout prevents this statement from being 
reused by the pool.
      *
      * @throws SQLException Thrown closing a traced resource or calling {@link 
#passivate()}.
      */
@@ -188,6 +193,10 @@ public class DelegatingPreparedStatement extends 
DelegatingStatement implements
                 throw new SQLExceptionList(thrownList);
             }
         }
+        if (originalQueryTimeout != null) {
+            
getDelegatePreparedStatement().setQueryTimeout(originalQueryTimeout);
+            originalQueryTimeout = null;
+        }
         super.passivate();
     }
 
@@ -416,6 +425,19 @@ public class DelegatingPreparedStatement extends 
DelegatingStatement implements
         }
     }
 
+    /**
+     * Sets the delegate, discarding any saved query timeout when the delegate 
changes.
+     *
+     * @param statement the new delegate.
+     */
+    @Override
+    public void setDelegate(final Statement statement) {
+        if (getDelegateInternal() != statement) {
+            originalQueryTimeout = null;
+        }
+        super.setDelegate(statement);
+    }
+
     @Override
     public void setDouble(final int parameterIndex, final double x) throws 
SQLException {
         checkOpen();
@@ -594,6 +616,15 @@ public class DelegatingPreparedStatement extends 
DelegatingStatement implements
         }
     }
 
+    /** Remembers the original timeout before changing a statement that will 
be returned to a pool. */
+    void setQueryTimeoutAndRememberOriginal(final int seconds) throws 
SQLException {
+        checkOpen();
+        if (originalQueryTimeout == null) {
+            originalQueryTimeout = getQueryTimeout();
+        }
+        super.setQueryTimeout(seconds);
+    }
+
     @Override
     public void setRef(final int i, final Ref x) throws SQLException {
         checkOpen();
diff --git 
a/src/main/java/org/apache/commons/dbcp2/PoolableCallableStatement.java 
b/src/main/java/org/apache/commons/dbcp2/PoolableCallableStatement.java
index 56bc7951..74d7d0c4 100644
--- a/src/main/java/org/apache/commons/dbcp2/PoolableCallableStatement.java
+++ b/src/main/java/org/apache/commons/dbcp2/PoolableCallableStatement.java
@@ -108,4 +108,9 @@ public class PoolableCallableStatement extends 
DelegatingCallableStatement {
         prepareToReturn();
     }
 
+    @Override
+    public void setQueryTimeout(final int seconds) throws SQLException {
+        setQueryTimeoutAndRememberOriginal(seconds);
+    }
+
 }
diff --git a/src/main/java/org/apache/commons/dbcp2/PoolableConnection.java 
b/src/main/java/org/apache/commons/dbcp2/PoolableConnection.java
index 469e6a59..2f462165 100644
--- a/src/main/java/org/apache/commons/dbcp2/PoolableConnection.java
+++ b/src/main/java/org/apache/commons/dbcp2/PoolableConnection.java
@@ -415,8 +415,7 @@ public class PoolableConnection extends 
DelegatingConnection<Connection> impleme
         }
 
         // JDBC timeouts are whole seconds where 0 means no timeout, so a 
positive sub-second timeout becomes 1 second.
-        final int timeoutSeconds = timeoutDuration.isNegative() || 
timeoutDuration.isZero() ? 0
-                : (int) Math.max(1, Math.min(Integer.MAX_VALUE, 
timeoutDuration.getSeconds()));
+        final int timeoutSeconds = timeoutDuration.isNegative() ? 0 : 
Utils.toJdbcSeconds(timeoutDuration);
         if (sql == null || sql.isEmpty()) {
             if (!isValid(Duration.ofSeconds(timeoutSeconds))) {
                 throw new SQLException("isValid() returned false");
diff --git 
a/src/main/java/org/apache/commons/dbcp2/PoolablePreparedStatement.java 
b/src/main/java/org/apache/commons/dbcp2/PoolablePreparedStatement.java
index 0ea315ce..b913d675 100644
--- a/src/main/java/org/apache/commons/dbcp2/PoolablePreparedStatement.java
+++ b/src/main/java/org/apache/commons/dbcp2/PoolablePreparedStatement.java
@@ -131,4 +131,10 @@ public class PoolablePreparedStatement<K> extends 
DelegatingPreparedStatement {
         }
         prepareToReturn();
     }
+
+    @Override
+    public void setQueryTimeout(final int seconds) throws SQLException {
+        setQueryTimeoutAndRememberOriginal(seconds);
+    }
+
 }
diff --git a/src/main/java/org/apache/commons/dbcp2/Utils.java 
b/src/main/java/org/apache/commons/dbcp2/Utils.java
index f8b93cfc..48c095b8 100644
--- a/src/main/java/org/apache/commons/dbcp2/Utils.java
+++ b/src/main/java/org/apache/commons/dbcp2/Utils.java
@@ -362,6 +362,25 @@ public final class Utils {
         return value != null ? value.toCharArray() : null;
     }
 
+    /**
+     * Converts a duration to the integer seconds accepted by JDBC timeout 
methods.
+     * Positive durations are truncated to whole seconds, with a minimum of 
one second and a maximum of
+     * {@link Integer#MAX_VALUE}. Zero remains zero. Negative durations remain 
negative, capped at
+     * {@link Integer#MIN_VALUE}, so callers can preserve JDBC's rejection of 
negative timeouts.
+     *
+     * @param duration the duration to convert, not null.
+     * @return the bounded number of seconds.
+     * @throws NullPointerException if duration is null.
+     * @since 2.15.0
+     */
+    public static int toJdbcSeconds(final Duration duration) {
+        final long seconds = duration.getSeconds();
+        if (duration.isNegative()) {
+            return (int) Math.max(Integer.MIN_VALUE, seconds);
+        }
+        return duration.isZero() ? 0 : (int) Math.max(1, 
Math.min(Integer.MAX_VALUE, seconds));
+    }
+
     /**
      * Converts the given char[] to a String.
      *
diff --git 
a/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java 
b/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java
index 3b64a630..ae99533b 100644
--- a/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java
+++ b/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java
@@ -180,6 +180,15 @@ public class DriverAdapterCPDS implements 
ConnectionPoolDataSource, Referenceabl
     public DriverAdapterCPDS() {
     }
 
+    private void addDurationReference(final Reference reference, final String 
durationKey, final String millisKey, final Duration duration) {
+        reference.add(new StringRefAddr(durationKey, duration.toString()));
+        try {
+            reference.add(new StringRefAddr(millisKey, 
Long.toString(duration.toMillis())));
+        } catch (final ArithmeticException ignored) {
+            // Only the Duration representation can preserve values outside 
the range of long milliseconds.
+        }
+    }
+
     /**
      * Throws an IllegalStateException, if a PooledConnection has already been 
requested.
      */
@@ -238,6 +247,15 @@ public class DriverAdapterCPDS implements 
ConnectionPoolDataSource, Referenceabl
         return durationBetweenEvictionRuns;
     }
 
+    private Duration getDuration(final Reference reference, final String 
durationKey, final String millisKey) {
+        final RefAddr duration = reference.get(durationKey);
+        if (isNotEmpty(duration)) {
+            return Duration.parse(getStringContent(duration));
+        }
+        final RefAddr millis = reference.get(millisKey);
+        return isNotEmpty(millis) ? 
Duration.ofMillis(Long.parseLong(getStringContent(millis))) : null;
+    }
+
     private int getIntegerStringContent(final RefAddr ra) {
         return Integer.parseInt(getStringContent(ra));
     }
@@ -363,9 +381,9 @@ public class DriverAdapterCPDS implements 
ConnectionPoolDataSource, Referenceabl
                     setMaxIdle(getIntegerStringContent(ra));
                 }
 
-                ra = ref.get(KEY_TIME_BETWEEN_EVICTION_RUNS_MILLIS);
-                if (isNotEmpty(ra)) {
-                    
setTimeBetweenEvictionRunsMillis(getIntegerStringContent(ra));
+                final Duration evictionInterval = getDuration(ref, 
KEY_DURATION_BETWEEN_EVICTION_RUNS, KEY_TIME_BETWEEN_EVICTION_RUNS_MILLIS);
+                if (evictionInterval != null) {
+                    setDurationBetweenEvictionRuns(evictionInterval);
                 }
 
                 ra = ref.get(KEY_NUM_TESTS_PER_EVICTION_RUN);
@@ -373,9 +391,9 @@ public class DriverAdapterCPDS implements 
ConnectionPoolDataSource, Referenceabl
                     setNumTestsPerEvictionRun(getIntegerStringContent(ra));
                 }
 
-                ra = ref.get(KEY_MIN_EVICTABLE_IDLE_TIME_MILLIS);
-                if (isNotEmpty(ra)) {
-                    setMinEvictableIdleTimeMillis(getIntegerStringContent(ra));
+                final Duration idleDuration = getDuration(ref, 
KEY_MIN_EVICTABLE_IDLE_DURATION, KEY_MIN_EVICTABLE_IDLE_TIME_MILLIS);
+                if (idleDuration != null) {
+                    setMinEvictableIdleDuration(idleDuration);
                 }
 
                 ra = ref.get(KEY_MAX_PREPARED_STATEMENTS);
@@ -504,6 +522,11 @@ public class DriverAdapterCPDS implements 
ConnectionPoolDataSource, Referenceabl
      * are exported unchanged. It does not omit the configured password from 
Java serialization or remove passwords from previously created References.
      * </p>
      *
+     * <p>
+     * Duration properties include their ISO-8601 representations and, when 
representable as a long, legacy millisecond
+     * representations. The ISO-8601 properties take precedence when this 
factory reconstructs the data source.
+     * </p>
+     *
      * @return a Reference describing this data source.
      * @throws NamingException if the Reference cannot be created.
      * @see #setExportPasswordAsRefAddr(boolean)
@@ -530,14 +553,8 @@ public class DriverAdapterCPDS implements 
ConnectionPoolDataSource, Referenceabl
         ref.add(new StringRefAddr(KEY_MAX_IDLE, String.valueOf(getMaxIdle())));
         ref.add(new StringRefAddr(KEY_NUM_TESTS_PER_EVICTION_RUN, 
String.valueOf(getNumTestsPerEvictionRun())));
         ref.add(new StringRefAddr(KEY_MAX_PREPARED_STATEMENTS, 
String.valueOf(getMaxPreparedStatements())));
-        //
-        // Pair of current and deprecated.
-        ref.add(new StringRefAddr(KEY_DURATION_BETWEEN_EVICTION_RUNS, 
String.valueOf(getDurationBetweenEvictionRuns())));
-        ref.add(new StringRefAddr(KEY_TIME_BETWEEN_EVICTION_RUNS_MILLIS, 
String.valueOf(getTimeBetweenEvictionRunsMillis())));
-        //
-        // Pair of current and deprecated.
-        ref.add(new StringRefAddr(KEY_MIN_EVICTABLE_IDLE_DURATION, 
String.valueOf(getMinEvictableIdleDuration())));
-        ref.add(new StringRefAddr(KEY_MIN_EVICTABLE_IDLE_TIME_MILLIS, 
String.valueOf(getMinEvictableIdleTimeMillis())));
+        addDurationReference(ref, KEY_DURATION_BETWEEN_EVICTION_RUNS, 
KEY_TIME_BETWEEN_EVICTION_RUNS_MILLIS, getDurationBetweenEvictionRuns());
+        addDurationReference(ref, KEY_MIN_EVICTABLE_IDLE_DURATION, 
KEY_MIN_EVICTABLE_IDLE_TIME_MILLIS, getMinEvictableIdleDuration());
 
         return ref;
     }
diff --git 
a/src/main/java/org/apache/commons/dbcp2/datasources/AbstractConnectionFactory.java
 
b/src/main/java/org/apache/commons/dbcp2/datasources/AbstractConnectionFactory.java
index 37891022..4cb06088 100644
--- 
a/src/main/java/org/apache/commons/dbcp2/datasources/AbstractConnectionFactory.java
+++ 
b/src/main/java/org/apache/commons/dbcp2/datasources/AbstractConnectionFactory.java
@@ -26,6 +26,7 @@ import java.util.Collections;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Supplier;
 
 import javax.sql.ConnectionPoolDataSource;
 import javax.sql.PooledConnection;
@@ -39,6 +40,7 @@ import org.apache.commons.pool2.PooledObject;
 class AbstractConnectionFactory {
 
     protected final ConnectionPoolDataSource cpds;
+    private Supplier<Duration> loginTimeoutSupplier = () -> null;
     protected Duration maxConnDuration = Duration.ofMillis(-1);
     protected final boolean rollbackAfterValidation;
 
@@ -62,6 +64,14 @@ class AbstractConnectionFactory {
         this.rollbackAfterValidation = rollbackAfterValidation;
     }
 
+    protected PooledConnection getPooledConnection(final UserPassKey 
userPassKey) throws SQLException {
+        return ConnectionPoolDataSourceUtils.getPooledConnection(cpds, 
userPassKey.getUserName(), userPassKey.getPassword(), 
loginTimeoutSupplier.get());
+    }
+
+    void setLoginTimeoutSupplier(final Supplier<Duration> 
loginTimeoutSupplier) {
+        this.loginTimeoutSupplier = loginTimeoutSupplier;
+    }
+
     /**
      * Sets the maximum lifetime of a connection after which the connection 
will always fail activation,
      * passivation and validation.
diff --git 
a/src/main/java/org/apache/commons/dbcp2/datasources/CPDSConnectionFactory.java 
b/src/main/java/org/apache/commons/dbcp2/datasources/CPDSConnectionFactory.java
index 7cbfc513..615c0bca 100644
--- 
a/src/main/java/org/apache/commons/dbcp2/datasources/CPDSConnectionFactory.java
+++ 
b/src/main/java/org/apache/commons/dbcp2/datasources/CPDSConnectionFactory.java
@@ -202,12 +202,7 @@ final class CPDSConnectionFactory extends 
AbstractConnectionFactory
 
     @Override
     public synchronized PooledObject<PooledConnectionAndInfo> makeObject() 
throws SQLException {
-        PooledConnection pc = null;
-        if (userPassKey.getUserName() == null) {
-            pc = cpds.getPooledConnection();
-        } else {
-            pc = cpds.getPooledConnection(userPassKey.getUserName(), 
userPassKey.getPassword());
-        }
+        final PooledConnection pc = getPooledConnection(userPassKey);
         if (pc == null) {
             throw new IllegalStateException("Connection pool data source 
returned null from getPooledConnection");
         }
diff --git 
a/src/main/java/org/apache/commons/dbcp2/datasources/ConnectionPoolDataSourceUtils.java
 
b/src/main/java/org/apache/commons/dbcp2/datasources/ConnectionPoolDataSourceUtils.java
new file mode 100644
index 00000000..86169426
--- /dev/null
+++ 
b/src/main/java/org/apache/commons/dbcp2/datasources/ConnectionPoolDataSourceUtils.java
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.dbcp2.datasources;
+
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
+import java.sql.SQLException;
+import java.sql.SQLTimeoutException;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import javax.sql.ConnectionPoolDataSource;
+import javax.sql.PooledConnection;
+
+import org.apache.commons.dbcp2.Utils;
+
+/** Shared physical connection creation with scoped provider configuration. */
+final class ConnectionPoolDataSourceUtils {
+
+    /** Weak identity keys avoid invoking mutable provider equals/hashCode 
implementations. */
+    private static final class ProviderReference extends 
WeakReference<ConnectionPoolDataSource> {
+        private final int hashCode;
+
+        ProviderReference(final ConnectionPoolDataSource provider) {
+            super(provider, STALE_PROVIDERS);
+            hashCode = System.identityHashCode(provider);
+        }
+
+        @Override
+        public boolean equals(final Object obj) {
+            if (this == obj) {
+                return true;
+            }
+            final ConnectionPoolDataSource provider = get();
+            return provider != null && obj instanceof ProviderReference && 
provider == ((ProviderReference) obj).get();
+        }
+
+        @Override
+        public int hashCode() {
+            return hashCode;
+        }
+    }
+
+    private static final ReferenceQueue<ConnectionPoolDataSource> 
STALE_PROVIDERS = new ReferenceQueue<>();
+
+    /** Neither the weak keys nor the lock values retain providers after their 
pools are closed. */
+    private static final Map<ProviderReference, ReentrantReadWriteLock> LOCKS 
= new HashMap<>();
+
+    private static PooledConnection connect(final ConnectionPoolDataSource 
cpds, final String userName, final String password) throws SQLException {
+        return userName == null ? cpds.getPooledConnection() : 
cpds.getPooledConnection(userName, password);
+    }
+
+    /**
+     * Opens a physical connection with an optional login timeout, restoring 
the provider's setting afterwards.
+     * Timeout overrides exclude other connection attempts through these 
pools. Attempts without an override remain concurrent.
+     */
+    static PooledConnection getPooledConnection(final ConnectionPoolDataSource 
cpds, final String userName, final String password,
+            final Duration loginTimeout) throws SQLException {
+        Objects.requireNonNull(cpds, "cpds");
+        final ReentrantReadWriteLock providerLock;
+        synchronized (LOCKS) {
+            Reference<? extends ConnectionPoolDataSource> stale;
+            while ((stale = STALE_PROVIDERS.poll()) != null) {
+                LOCKS.remove(stale);
+            }
+            providerLock = LOCKS.computeIfAbsent(new ProviderReference(cpds), 
key -> new ReentrantReadWriteLock());
+        }
+        final Lock lock = loginTimeout == null ? providerLock.readLock() : 
providerLock.writeLock();
+        lock(lock, loginTimeout);
+        try {
+            if (loginTimeout == null) {
+                return connect(cpds, userName, password);
+            }
+            final int previousTimeout = cpds.getLoginTimeout();
+            final int timeoutSeconds = Utils.toJdbcSeconds(loginTimeout);
+            if (previousTimeout == timeoutSeconds) {
+                return connect(cpds, userName, password);
+            }
+            PooledConnection connection = null;
+            Throwable failure = null;
+            try {
+                cpds.setLoginTimeout(timeoutSeconds);
+                connection = connect(cpds, userName, password);
+                return connection;
+            } catch (final SQLException | RuntimeException | Error e) {
+                failure = e;
+                throw e;
+            } finally {
+                try {
+                    cpds.setLoginTimeout(previousTimeout);
+                } catch (final SQLException | RuntimeException | Error 
restoreException) {
+                    if (failure != null) {
+                        if (failure != restoreException) {
+                            failure.addSuppressed(restoreException);
+                        }
+                    } else {
+                        if (connection != null) {
+                            try {
+                                connection.close();
+                            } catch (final SQLException | RuntimeException | 
Error closeException) {
+                                if (closeException != restoreException) {
+                                    
restoreException.addSuppressed(closeException);
+                                }
+                            }
+                        }
+                        throw restoreException;
+                    }
+                }
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    private static void lock(final Lock lock, final Duration timeout) throws 
SQLException {
+        try {
+            if (timeout != null && !timeout.isNegative() && !timeout.isZero()) 
{
+                if (!lock.tryLock(Utils.toJdbcSeconds(timeout), 
TimeUnit.SECONDS)) {
+                    throw new SQLTimeoutException("Timed out waiting to 
configure the provider's login timeout");
+                }
+            } else {
+                lock.lockInterruptibly();
+            }
+        } catch (final InterruptedException e) {
+            Thread.currentThread().interrupt();
+            throw new SQLException("Interrupted while waiting to configure the 
provider's login timeout", e);
+        }
+    }
+
+    private ConnectionPoolDataSourceUtils() {
+        // Not instantiable.
+    }
+}
diff --git 
a/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java 
b/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java
index 8549ecbd..802fe30f 100644
--- 
a/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java
+++ 
b/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java
@@ -24,6 +24,7 @@ import java.sql.Connection;
 import java.sql.SQLException;
 import java.sql.SQLFeatureNotSupportedException;
 import java.time.Duration;
+import java.util.Objects;
 import java.util.Properties;
 import java.util.logging.Logger;
 
@@ -102,8 +103,11 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
     /** Environment that may be used to set up a JNDI initial context. */
     private Properties jndiEnvironment;
 
-    /** Login Timeout */
-    private Duration loginTimeoutDuration = Duration.ZERO;
+    /** Login timeout, or null to retain the provider's configuration. */
+    private volatile Duration loginTimeoutDuration;
+
+    /** Original datasource whose pool and live login timeout are shared after 
deserialization. */
+    private transient InstanceKeyDataSource loginTimeoutSource;
 
     /** Log stream */
     private PrintWriter logWriter;
@@ -315,6 +319,11 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
      */
     protected abstract PooledConnectionManager 
getConnectionManager(UserPassKey upkey);
 
+    /** Gets the optional timeout used for physical connection attempts. */
+    Duration getConfiguredLoginTimeout() {
+        return loginTimeoutSource == null ? loginTimeoutDuration : 
loginTimeoutSource.getConfiguredLoginTimeout();
+    }
+
     /**
      * Gets the value of connectionPoolDataSource. This method will return 
null, if the backing data source is being
      * accessed via JNDI.
@@ -586,15 +595,16 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
     }
 
     /**
-     * Gets the value of loginTimeout.
+     * Gets the configured login timeout converted to JDBC seconds, or zero if 
none was configured.
+     * Positive durations are truncated to whole seconds, with a minimum of 
one and a maximum of {@link Integer#MAX_VALUE}.
      *
-     * @return value of loginTimeout.
+     * @return the configured timeout in JDBC seconds.
      * @deprecated Use {@link #getLoginTimeoutDuration()}.
      */
     @Deprecated
     @Override
     public int getLoginTimeout() {
-        return (int) loginTimeoutDuration.getSeconds();
+        return Utils.toJdbcSeconds(getLoginTimeoutDuration());
     }
 
     /**
@@ -604,7 +614,8 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
      * @since 2.10.0
      */
     public Duration getLoginTimeoutDuration() {
-        return loginTimeoutDuration;
+        final Duration timeout = getConfiguredLoginTimeout();
+        return timeout == null ? Duration.ZERO : timeout;
     }
 
     /**
@@ -1117,27 +1128,51 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
     }
 
     /**
-     * Sets the value of loginTimeout.
+     * Sets the timeout applied to the underlying ConnectionPoolDataSource for 
each physical connection attempt,
+     * including connections created after pool initialization. The provider's 
previous timeout is restored afterwards.
+     * Until this method is called, the provider's configured timeout is used 
unchanged. Deserialized wrappers sharing
+     * the same pool also share this live configuration.
+     * <p>
+     * Positive durations use whole seconds, with a minimum of one second and 
a maximum of {@link Integer#MAX_VALUE}.
+     * Zero uses the provider's default login timeout behavior. Enforcement 
depends on the provider; this setting does
+     * not limit JNDI lookup or waiting for an available pooled connection. A 
timeout override excludes other connection
+     * attempts through these pools while the provider's setting is 
temporarily changed. A positive timeout also bounds
+     * waiting to access that setting, using the same whole-second conversion. 
Attempts without an override remain concurrent.
+     * </p>
      *
-     * @param loginTimeout
-     *            Value to assign to loginTimeout.
+     * @param loginTimeout a nonnegative timeout, not null.
+     * @throws NullPointerException if loginTimeout is null.
+     * @throws IllegalArgumentException if loginTimeout is negative.
      * @since 2.10.0
      */
     public void setLoginTimeout(final Duration loginTimeout) {
-        this.loginTimeoutDuration = loginTimeout;
+        Objects.requireNonNull(loginTimeout, "loginTimeout");
+        if (loginTimeout.isNegative()) {
+            throw new IllegalArgumentException("loginTimeout must not be 
negative");
+        }
+        if (loginTimeoutSource == null) {
+            this.loginTimeoutDuration = loginTimeout;
+        } else {
+            loginTimeoutSource.setLoginTimeout(loginTimeout);
+        }
     }
 
     /**
      * Sets the value of loginTimeout.
      *
-     * @param loginTimeout
-     *            Value to assign to loginTimeout.
+     * @param loginTimeout a nonnegative timeout in seconds.
+     * @throws IllegalArgumentException if loginTimeout is negative.
      * @deprecated Use {@link #setLoginTimeout(Duration)}.
      */
     @Deprecated
     @Override
     public void setLoginTimeout(final int loginTimeout) {
-        this.loginTimeoutDuration = Duration.ofSeconds(loginTimeout);
+        setLoginTimeout(Duration.ofSeconds(loginTimeout));
+    }
+
+    /** Shares the live login timeout configuration along with the pool during 
deserialization. */
+    final void setLoginTimeoutSource(final InstanceKeyDataSource source) {
+        loginTimeoutSource = source;
     }
 
     /**
@@ -1274,11 +1309,7 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
         // try to get a connection with the supplied userName/password
         PooledConnection conn = null;
         try {
-            if (userName != null) {
-                conn = cpds.getPooledConnection(userName, userPassword);
-            } else {
-                conn = cpds.getPooledConnection();
-            }
+            conn = ConnectionPoolDataSourceUtils.getPooledConnection(cpds, 
userName, userPassword, getConfiguredLoginTimeout());
             if (conn == null) {
                 throw new SQLException("Cannot connect using the supplied 
userName/password");
             }
@@ -1341,7 +1372,7 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
         builder.append(", jndiEnvironment=");
         builder.append(Utils.cloneWithoutCredentials(jndiEnvironment));
         builder.append(", loginTimeoutDuration=");
-        builder.append(loginTimeoutDuration);
+        builder.append(getLoginTimeoutDuration());
         builder.append(", logWriter=");
         builder.append(logWriter);
         builder.append(", instanceKey=");
diff --git 
a/src/main/java/org/apache/commons/dbcp2/datasources/KeyedCPDSConnectionFactory.java
 
b/src/main/java/org/apache/commons/dbcp2/datasources/KeyedCPDSConnectionFactory.java
index ca399624..14be298a 100644
--- 
a/src/main/java/org/apache/commons/dbcp2/datasources/KeyedCPDSConnectionFactory.java
+++ 
b/src/main/java/org/apache/commons/dbcp2/datasources/KeyedCPDSConnectionFactory.java
@@ -186,14 +186,7 @@ final class KeyedCPDSConnectionFactory extends 
AbstractConnectionFactory
      */
     @Override
     public synchronized PooledObject<PooledConnectionAndInfo> makeObject(final 
UserPassKey userPassKey) throws SQLException {
-        PooledConnection pooledConnection = null;
-        final String userName = userPassKey.getUserName();
-        final String password = userPassKey.getPassword();
-        if (userName == null) {
-            pooledConnection = cpds.getPooledConnection();
-        } else {
-            pooledConnection = cpds.getPooledConnection(userName, password);
-        }
+        final PooledConnection pooledConnection = 
getPooledConnection(userPassKey);
         if (pooledConnection == null) {
             throw new IllegalStateException("Connection pool data source 
returned null from getPooledConnection");
         }
diff --git 
a/src/main/java/org/apache/commons/dbcp2/datasources/PerUserPoolDataSource.java 
b/src/main/java/org/apache/commons/dbcp2/datasources/PerUserPoolDataSource.java
index 9f001229..adcfed8f 100644
--- 
a/src/main/java/org/apache/commons/dbcp2/datasources/PerUserPoolDataSource.java
+++ 
b/src/main/java/org/apache/commons/dbcp2/datasources/PerUserPoolDataSource.java
@@ -673,7 +673,9 @@ public class PerUserPoolDataSource extends 
InstanceKeyDataSource {
     @SuppressWarnings("resource")
     private void readObject(final ObjectInputStream in) throws IOException, 
ClassNotFoundException {
         in.defaultReadObject();
-        this.managers = readObjectImpl().managers;
+        final PerUserPoolDataSource source = readObjectImpl();
+        this.managers = source.managers;
+        setLoginTimeoutSource(source);
     }
 
     private PerUserPoolDataSource readObjectImpl() throws IOException, 
ClassNotFoundException {
@@ -691,6 +693,7 @@ public class PerUserPoolDataSource extends 
InstanceKeyDataSource {
         // explicitly)
         final CPDSConnectionFactory factory = new CPDSConnectionFactory(cpds, 
getValidationQuery(), getValidationQueryTimeoutDuration(),
                 isRollbackAfterValidation(), userName, 
Utils.toCharArray(password));
+        factory.setLoginTimeoutSupplier(this::getConfiguredLoginTimeout);
         factory.setMaxConn(getMaxConnDuration());
         // Create an object pool to contain our PooledConnections
         @SuppressWarnings("resource")
diff --git 
a/src/main/java/org/apache/commons/dbcp2/datasources/SharedPoolDataSource.java 
b/src/main/java/org/apache/commons/dbcp2/datasources/SharedPoolDataSource.java
index c24b1ccf..e8678891 100644
--- 
a/src/main/java/org/apache/commons/dbcp2/datasources/SharedPoolDataSource.java
+++ 
b/src/main/java/org/apache/commons/dbcp2/datasources/SharedPoolDataSource.java
@@ -159,12 +159,14 @@ public class SharedPoolDataSource extends 
InstanceKeyDataSource {
      */
     private void readObject(final ObjectInputStream in) throws IOException, 
ClassNotFoundException {
         in.defaultReadObject();
-        this.pool = readObjectImpl();
+        final SharedPoolDataSource source = readObjectImpl();
+        this.pool = source.pool;
+        setLoginTimeoutSource(source);
     }
 
-    private KeyedObjectPool<UserPassKey, PooledConnectionAndInfo> 
readObjectImpl() throws IOException, ClassNotFoundException {
+    private SharedPoolDataSource readObjectImpl() throws IOException, 
ClassNotFoundException {
         try {
-            return ((SharedPoolDataSource) new 
SharedPoolDataSourceFactory().getObjectInstance(getReference(), null, null, 
null)).pool;
+            return (SharedPoolDataSource) new 
SharedPoolDataSourceFactory().getObjectInstance(getReference(), null, null, 
null);
         } catch (final NamingException e) {
             throw new IOException("NamingException: " + e);
         }
@@ -176,6 +178,7 @@ public class SharedPoolDataSource extends 
InstanceKeyDataSource {
 
         // Create an object pool to contain our PooledConnections
         factory = new KeyedCPDSConnectionFactory(cpds, getValidationQuery(), 
getValidationQueryTimeoutDuration(), isRollbackAfterValidation());
+        factory.setLoginTimeoutSupplier(this::getConfiguredLoginTimeout);
         factory.setMaxConn(getMaxConnDuration());
 
         final GenericKeyedObjectPoolConfig<PooledConnectionAndInfo> config = 
new GenericKeyedObjectPoolConfig<>();
diff --git a/src/test/java/org/apache/commons/dbcp2/TestJdbcTimeouts.java 
b/src/test/java/org/apache/commons/dbcp2/TestJdbcTimeouts.java
new file mode 100644
index 00000000..c9d7358a
--- /dev/null
+++ b/src/test/java/org/apache/commons/dbcp2/TestJdbcTimeouts.java
@@ -0,0 +1,436 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *   https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.dbcp2;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.SQLFeatureNotSupportedException;
+import java.sql.Statement;
+import java.time.Duration;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import javax.sql.PooledConnection;
+
+import org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS;
+import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/** Tests JDBC timeout conversion and statement timeout isolation. */
+class TestJdbcTimeouts {
+
+    private static Statement createStatement(final Connection connection, 
final int variant) throws SQLException {
+        switch (variant) {
+        case 0:
+            return connection.createStatement();
+        case 1:
+            return connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, 
ResultSet.CONCUR_READ_ONLY);
+        case 2:
+            return connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, 
ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
+        case 3:
+            return connection.prepareStatement("SELECT 1");
+        case 4:
+            return connection.prepareStatement("SELECT 1", 
Statement.RETURN_GENERATED_KEYS);
+        case 5:
+            return connection.prepareStatement("SELECT 1", 
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+        case 6:
+            return connection.prepareStatement("SELECT 1", 
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, 
ResultSet.CLOSE_CURSORS_AT_COMMIT);
+        case 7:
+            return connection.prepareStatement("SELECT 1", new int[] {1});
+        case 8:
+            return connection.prepareStatement("SELECT 1", new String[] 
{"id"});
+        case 9:
+            return connection.prepareCall("SELECT 1");
+        case 10:
+            return connection.prepareCall("SELECT 1", 
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+        case 11:
+            return connection.prepareCall("SELECT 1", 
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, 
ResultSet.CLOSE_CURSORS_AT_COMMIT);
+        default:
+            throw new IllegalArgumentException("Unknown statement variant " + 
variant);
+        }
+    }
+
+    private static CallableStatement mockStatement(final AtomicInteger 
timeout) throws SQLException {
+        final CallableStatement statement = mock(CallableStatement.class);
+        when(statement.getQueryTimeout()).thenAnswer(invocation -> 
timeout.get());
+        doAnswer(invocation -> {
+            timeout.set(invocation.getArgument(0));
+            return null;
+        }).when(statement).setQueryTimeout(anyInt());
+        return statement;
+    }
+
+    private static BasicDataSource newDataSource(final Duration 
defaultTimeout) {
+        final BasicDataSource source = new BasicDataSource();
+        source.setDriverClassName(TesterDriver.class.getName());
+        source.setUrl("jdbc:apache:commons:testdriver");
+        source.setUsername("u1");
+        source.setPassword("p1");
+        source.setMaxTotal(1);
+        source.setPoolPreparedStatements(true);
+        source.setDefaultQueryTimeout(defaultTimeout);
+        return source;
+    }
+
+    static Stream<Arguments> changedDelegates() {
+        return Stream.of(false, true).flatMap(callable -> Stream.of(false, 
true).map(changeTimeout -> Arguments.of(callable, changeTimeout)));
+    }
+
+    static Stream<Arguments> failedTimeoutSetters() {
+        return Stream.of(false, true).flatMap(callable -> Stream.of(false, 
true).map(unchecked -> Arguments.of(callable, unchecked)));
+    }
+
+    static Stream<Arguments> pooledTimeouts() {
+        return Stream.of(false, true).flatMap(callable -> Stream.of(null, 
Duration.ZERO, Duration.ofMillis(100), Duration.ofSeconds(5))
+                .map(timeout -> Arguments.of(callable, timeout)));
+    }
+
+    static Stream<Arguments> statementTimeouts() {
+        return IntStream.range(0, 12).boxed().flatMap(variant -> 
timeouts().map(argument ->
+                Arguments.of(variant, argument.get()[0], argument.get()[1])));
+    }
+
+    static Stream<Arguments> timeouts() {
+        return Stream.of(
+                Arguments.of(Duration.ofSeconds(Long.MIN_VALUE), 
Integer.MIN_VALUE),
+                Arguments.of(Duration.ofSeconds((long) Integer.MIN_VALUE - 1), 
Integer.MIN_VALUE),
+                Arguments.of(Duration.ofSeconds(Integer.MIN_VALUE), 
Integer.MIN_VALUE),
+                Arguments.of(Duration.ofSeconds(-1), -1),
+                Arguments.of(Duration.ofNanos(-1), -1),
+                Arguments.of(Duration.ZERO, 0),
+                Arguments.of(Duration.ofNanos(1), 1),
+                Arguments.of(Duration.ofMillis(100), 1),
+                Arguments.of(Duration.ofNanos(999_999_999), 1),
+                Arguments.of(Duration.ofSeconds(1), 1),
+                Arguments.of(Duration.ofMillis(1_900), 1),
+                Arguments.of(Duration.ofSeconds(5), 5),
+                Arguments.of(Duration.ofSeconds(Integer.MAX_VALUE - 1), 
Integer.MAX_VALUE - 1),
+                Arguments.of(Duration.ofSeconds(Integer.MAX_VALUE, 
999_999_999), Integer.MAX_VALUE),
+                Arguments.of(Duration.ofSeconds((long) Integer.MAX_VALUE + 1), 
Integer.MAX_VALUE),
+                Arguments.of(Duration.ofSeconds(1L << 32), Integer.MAX_VALUE),
+                Arguments.of(Duration.ofSeconds(Long.MAX_VALUE, 999_999_999), 
Integer.MAX_VALUE));
+    }
+
+    @ParameterizedTest
+    @MethodSource("pooledTimeouts")
+    void testBasicDataSourceRestoresTimeoutBetweenBorrowers(final boolean 
callable, final Duration defaultTimeout) throws Exception {
+        try (BasicDataSource source = newDataSource(defaultTimeout)) {
+            final int expected = defaultTimeout == null ? 1000 : 
Utils.toJdbcSeconds(defaultTimeout);
+            for (int i = 0; i < 3; i++) {
+                try (Connection connection = source.getConnection();
+                        PreparedStatement statement = callable ? 
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1")) {
+                    assertEquals(expected, statement.getQueryTimeout());
+                    statement.setQueryTimeout(7);
+                    statement.setQueryTimeout(9);
+                }
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testCpdsAdapterRestoresTimeout(final boolean callable) throws 
Exception {
+        final DriverAdapterCPDS source = new DriverAdapterCPDS();
+        source.setDriver(TesterDriver.class.getName());
+        source.setUrl("jdbc:apache:commons:testdriver");
+        source.setPoolPreparedStatements(true);
+        final PooledConnection pooled = source.getPooledConnection("u1", "p1");
+        try {
+            for (int i = 0; i < 3; i++) {
+                try (Connection connection = pooled.getConnection();
+                        PreparedStatement statement = callable ? 
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1")) {
+                    assertEquals(1000, statement.getQueryTimeout());
+                    statement.setQueryTimeout(7);
+                }
+            }
+        } finally {
+            pooled.close();
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("statementTimeouts")
+    void testDefaultQueryTimeout(final int variant, final Duration timeout, 
final int expected) throws SQLException {
+        final Connection raw = mock(Connection.class);
+        final CallableStatement statement = mock(CallableStatement.class);
+        when(createStatement(raw, variant)).thenReturn(statement);
+        final SQLException failure = new SQLException("Negative timeout");
+        if (expected < 0) {
+            doThrow(failure).when(statement).setQueryTimeout(expected);
+        }
+        try (DelegatingConnection<Connection> connection = new 
DelegatingConnection<>(raw)) {
+            connection.setDefaultQueryTimeout(timeout);
+            if (expected < 0) {
+                assertSame(failure, assertThrows(SQLException.class, () -> 
createStatement(connection, variant)));
+                verify(statement).close();
+            } else {
+                try (Statement ignored = createStatement(connection, variant)) 
{
+                    assertFalse(ignored.isClosed());
+                }
+            }
+            if (expected == 0) {
+                verify(statement, never()).setQueryTimeout(anyInt());
+            } else {
+                verify(statement).setQueryTimeout(expected);
+            }
+        }
+    }
+
+    @Test
+    void testDefaultQueryTimeoutAvoidsRedundantSetter() throws SQLException {
+        final Connection raw = mock(Connection.class);
+        final Statement statement = mock(Statement.class);
+        when(raw.createStatement()).thenReturn(statement);
+        when(statement.getQueryTimeout()).thenReturn(1);
+        try (DelegatingConnection<Connection> connection = new 
DelegatingConnection<>(raw)) {
+            connection.setDefaultQueryTimeout(Duration.ofMillis(100));
+            try (Statement ignored = connection.createStatement()) {
+                verify(statement, never()).setQueryTimeout(anyInt());
+            }
+        }
+    }
+
+    @Test
+    void testDefaultQueryTimeoutPreservesInitializationAndCloseFailures() 
throws SQLException {
+        final Connection raw = mock(Connection.class);
+        final Statement statement = mock(Statement.class);
+        when(raw.createStatement()).thenReturn(statement);
+        final SQLException failure = new SQLException("Timeout unsupported");
+        final SQLException closeFailure = new SQLException("Close failed");
+        doThrow(failure).when(statement).setQueryTimeout(1);
+        doThrow(closeFailure).when(statement).close();
+        try (DelegatingConnection<Connection> connection = new 
DelegatingConnection<>(raw)) {
+            connection.setDefaultQueryTimeout(Duration.ofMillis(100));
+            assertSame(failure, assertThrows(SQLException.class, 
connection::createStatement));
+            assertEquals(1, failure.getSuppressed().length);
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("timeouts")
+    void testIsValid(final Duration timeout, final int expected) throws 
SQLException {
+        final Connection raw = mock(Connection.class);
+        final SQLException failure = new SQLException("Negative timeout");
+        if (expected < 0) {
+            when(raw.isValid(expected)).thenThrow(failure);
+        } else {
+            when(raw.isValid(expected)).thenReturn(true);
+        }
+        try (DelegatingConnection<Connection> connection = new 
DelegatingConnection<>(raw)) {
+            if (expected < 0) {
+                assertSame(failure, assertThrows(SQLException.class, () -> 
connection.isValid(timeout)));
+            } else {
+                assertTrue(connection.isValid(timeout));
+            }
+            verify(raw).isValid(expected);
+        }
+    }
+
+    @Test
+    void testIsValidClosedDoesNotCallDriver() throws SQLException {
+        final Connection raw = mock(Connection.class);
+        try (DelegatingConnection<Connection> connection = new 
DelegatingConnection<>(raw)) {
+            connection.setClosedInternal(true);
+            assertFalse(connection.isValid(Duration.ofMillis(100)));
+            verify(raw, never()).isValid(anyInt());
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testPoolDiscardsStatementWhenTimeoutResetFails(final boolean 
callable) throws Exception {
+        final Connection raw = mock(Connection.class);
+        final CallableStatement statement = mock(CallableStatement.class);
+        when(raw.prepareStatement("SELECT 1")).thenReturn(statement);
+        when(raw.prepareCall("SELECT 1")).thenReturn(statement);
+        when(statement.getQueryTimeout()).thenReturn(5);
+        try (PoolingConnection connection = new PoolingConnection(raw);
+                GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement> 
pool = new GenericKeyedObjectPool<>(connection)) {
+            connection.setStatementPool(pool);
+            final PreparedStatement borrowed = callable ? 
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1");
+            borrowed.setQueryTimeout(7);
+            doThrow(new SQLException("Reset 
failed")).when(statement).setQueryTimeout(5);
+            borrowed.close();
+            assertEquals(0, pool.getNumIdle());
+            verify(statement).close();
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("timeouts")
+    void testToJdbcSeconds(final Duration timeout, final int expected) {
+        assertEquals(expected, Utils.toJdbcSeconds(timeout));
+    }
+
+    @Test
+    void testToJdbcSecondsNull() {
+        assertThrows(NullPointerException.class, () -> 
Utils.toJdbcSeconds(null));
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testConnectionCloseRestoresUnclosedStatementTimeout(final boolean 
callable) throws Exception {
+        try (BasicDataSource source = newDataSource(null)) {
+            try (Connection connection = source.getConnection()) {
+                final PreparedStatement statement = callable ? 
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1");
+                statement.setQueryTimeout(7);
+            }
+            try (Connection connection = source.getConnection();
+                    PreparedStatement statement = callable ? 
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1")) {
+                assertEquals(1000, statement.getQueryTimeout());
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testUntouchedPooledStatementDoesNotReadOrWriteTimeout(final boolean 
callable) throws Exception {
+        final Connection raw = mock(Connection.class);
+        final CallableStatement statement = mock(CallableStatement.class);
+        when(raw.prepareStatement("SELECT 1")).thenReturn(statement);
+        when(raw.prepareCall("SELECT 1")).thenReturn(statement);
+        try (PoolingConnection connection = new PoolingConnection(raw);
+                GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement> 
pool = new GenericKeyedObjectPool<>(connection)) {
+            connection.setStatementPool(pool);
+            for (int i = 0; i < 2; i++) {
+                try (PreparedStatement borrowed = callable ? 
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1")) {
+                    assertFalse(borrowed.isClosed());
+                }
+            }
+            verify(statement, never()).getQueryTimeout();
+            verify(statement, never()).setQueryTimeout(anyInt());
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testNonPooledQueryTimeoutDoesNotRequireGetter(final boolean callable) 
throws SQLException {
+        final CallableStatement raw = mock(CallableStatement.class);
+        when(raw.getQueryTimeout()).thenThrow(new 
SQLFeatureNotSupportedException("Getter unavailable"));
+        try (PreparedStatement statement = callable ? new 
DelegatingCallableStatement(null, raw) : new DelegatingPreparedStatement(null, 
raw)) {
+            statement.setQueryTimeout(7);
+            verify(raw).setQueryTimeout(7);
+            verify(raw, never()).getQueryTimeout();
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("failedTimeoutSetters")
+    void testPooledTimeoutRestoredAfterSetterMutatesAndThrows(final boolean 
callable, final boolean unchecked) throws Exception {
+        final Connection raw = mock(Connection.class);
+        final CallableStatement statement = mock(CallableStatement.class);
+        final AtomicInteger timeout = new AtomicInteger(5);
+        final Exception failure = unchecked ? new 
IllegalStateException("Timeout changed before failure")
+                : new SQLException("Timeout changed before failure");
+        when(raw.prepareStatement("SELECT 1")).thenReturn(statement);
+        when(raw.prepareCall("SELECT 1")).thenReturn(statement);
+        when(statement.getQueryTimeout()).thenAnswer(invocation -> 
timeout.get());
+        doAnswer(invocation -> {
+            final int seconds = invocation.getArgument(0);
+            timeout.set(seconds);
+            if (seconds == 7) {
+                throw failure;
+            }
+            return null;
+        }).when(statement).setQueryTimeout(anyInt());
+        try (PoolingConnection connection = new PoolingConnection(raw);
+                GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement> 
pool = new GenericKeyedObjectPool<>(connection)) {
+            connection.setStatementPool(pool);
+            try (PreparedStatement borrowed = callable ? 
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1")) {
+                assertSame(failure, assertThrows(failure.getClass(), () -> 
borrowed.setQueryTimeout(7)));
+                assertEquals(7, timeout.get());
+            }
+            assertEquals(5, timeout.get());
+            assertEquals(1, pool.getNumIdle());
+            try (PreparedStatement borrowed = callable ? 
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1")) {
+                assertEquals(5, borrowed.getQueryTimeout());
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("changedDelegates")
+    void testPooledTimeoutFollowsReplacementDelegate(final boolean callable, 
final boolean changeTimeout) throws Exception {
+        final Connection raw = mock(Connection.class);
+        final AtomicInteger originalTimeout = new AtomicInteger(5);
+        final AtomicInteger replacementTimeout = new AtomicInteger(9);
+        final CallableStatement original = mockStatement(originalTimeout);
+        final CallableStatement replacement = 
mockStatement(replacementTimeout);
+        when(raw.prepareStatement("SELECT 1")).thenReturn(original);
+        when(raw.prepareCall("SELECT 1")).thenReturn(original);
+        try (PoolingConnection connection = new PoolingConnection(raw);
+                GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement> 
pool = new GenericKeyedObjectPool<>(connection)) {
+            connection.setStatementPool(pool);
+            try (DelegatingPreparedStatement borrowed = 
(DelegatingPreparedStatement)
+                    (callable ? connection.prepareCall("SELECT 1") : 
connection.prepareStatement("SELECT 1"))) {
+                borrowed.setQueryTimeout(7);
+                borrowed.setDelegate(replacement);
+                if (changeTimeout) {
+                    borrowed.setQueryTimeout(11);
+                }
+            }
+            assertEquals(9, replacementTimeout.get());
+            try (PreparedStatement borrowed = callable ? 
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1")) {
+                assertEquals(9, borrowed.getQueryTimeout());
+            }
+        } finally {
+            original.close();
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testPooledTimeoutPreservedWhenReassigningSameDelegate(final boolean 
callable) throws Exception {
+        final Connection raw = mock(Connection.class);
+        final AtomicInteger timeout = new AtomicInteger(5);
+        final CallableStatement statement = mockStatement(timeout);
+        when(raw.prepareStatement("SELECT 1")).thenReturn(statement);
+        when(raw.prepareCall("SELECT 1")).thenReturn(statement);
+        try (PoolingConnection connection = new PoolingConnection(raw);
+                GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement> 
pool = new GenericKeyedObjectPool<>(connection)) {
+            connection.setStatementPool(pool);
+            try (DelegatingPreparedStatement borrowed = 
(DelegatingPreparedStatement)
+                    (callable ? connection.prepareCall("SELECT 1") : 
connection.prepareStatement("SELECT 1"))) {
+                borrowed.setQueryTimeout(7);
+                borrowed.setDelegate(statement);
+            }
+            assertEquals(5, timeout.get());
+        }
+    }
+
+}
diff --git 
a/src/test/java/org/apache/commons/dbcp2/cpdsadapter/TestDriverAdapterCPDSReference.java
 
b/src/test/java/org/apache/commons/dbcp2/cpdsadapter/TestDriverAdapterCPDSReference.java
index 4dcb5d5c..8963f727 100644
--- 
a/src/test/java/org/apache/commons/dbcp2/cpdsadapter/TestDriverAdapterCPDSReference.java
+++ 
b/src/test/java/org/apache/commons/dbcp2/cpdsadapter/TestDriverAdapterCPDSReference.java
@@ -33,6 +33,7 @@ import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.sql.Connection;
 import java.sql.SQLException;
+import java.time.Duration;
 import java.util.Base64;
 import java.util.Hashtable;
 import java.util.Properties;
@@ -362,4 +363,62 @@ class TestDriverAdapterCPDSReference {
         assertEquals(export, restored.getReference().get("password") != null);
         assertCanConnect(restored);
     }
+    static Stream<Arguments> durationReferences() {
+        return Stream.of(Duration.ZERO, Duration.ofNanos(1), 
Duration.ofNanos(-1), Duration.ofMillis(1_901),
+                Duration.ofDays(30), Duration.ofMillis(Long.MAX_VALUE), 
Duration.ofSeconds(Long.MAX_VALUE, 999_999_999),
+                Duration.ofSeconds(Long.MIN_VALUE))
+                .flatMap(duration -> Stream.of(false, true).map(modernOnly -> 
Arguments.of(duration, modernOnly)));
+    }
+
+    @ParameterizedTest
+    @MethodSource("durationReferences")
+    void testDurationReferenceRoundTrip(final Duration duration, final boolean 
modernOnly) throws Exception {
+        final DriverAdapterCPDS source = newDataSource();
+        source.setDurationBetweenEvictionRuns(duration);
+        source.setMinEvictableIdleDuration(duration);
+        final Reference reference = source.getReference();
+        if (modernOnly) {
+            removeAddress(reference, "timeBetweenEvictionRunsMillis");
+            removeAddress(reference, "minEvictableIdleTimeMillis");
+        }
+        final DriverAdapterCPDS restored = resolve(reference);
+        assertEquals(duration, restored.getDurationBetweenEvictionRuns());
+        assertEquals(duration, restored.getMinEvictableIdleDuration());
+    }
+
+    @ParameterizedTest
+    @ValueSource(longs = {Long.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE, 
2_592_000_000L, Long.MAX_VALUE})
+    void testLegacyDurationReference(final long millis) throws Exception {
+        final Reference reference = new 
Reference(DriverAdapterCPDS.class.getName(), DriverAdapterCPDS.class.getName(), 
null);
+        reference.add(new StringRefAddr("timeBetweenEvictionRunsMillis", 
Long.toString(millis)));
+        reference.add(new StringRefAddr("minEvictableIdleTimeMillis", 
Long.toString(millis)));
+        final DriverAdapterCPDS restored = resolve(reference);
+        assertEquals(Duration.ofMillis(millis), 
restored.getDurationBetweenEvictionRuns());
+        assertEquals(Duration.ofMillis(millis), 
restored.getMinEvictableIdleDuration());
+    }
+
+    @Test
+    void testModernDurationReferenceOverridesMalformedLegacyValues() throws 
Exception {
+        final Reference reference = new 
Reference(DriverAdapterCPDS.class.getName(), DriverAdapterCPDS.class.getName(), 
null);
+        reference.add(new StringRefAddr("durationBetweenEvictionRuns", 
"PT0.001S"));
+        reference.add(new StringRefAddr("minEvictableIdleDuration", "PT720H"));
+        reference.add(new StringRefAddr("timeBetweenEvictionRunsMillis", 
"invalid"));
+        reference.add(new StringRefAddr("minEvictableIdleTimeMillis", 
"invalid"));
+        final DriverAdapterCPDS restored = resolve(reference);
+        assertEquals(Duration.ofMillis(1), 
restored.getDurationBetweenEvictionRuns());
+        assertEquals(Duration.ofDays(30), 
restored.getMinEvictableIdleDuration());
+    }
+
+    @Test
+    void testNullModernDurationReferenceFallsBackToLegacy() throws Exception {
+        final Reference reference = new 
Reference(DriverAdapterCPDS.class.getName(), DriverAdapterCPDS.class.getName(), 
null);
+        reference.add(new StringRefAddr("durationBetweenEvictionRuns", null));
+        reference.add(new StringRefAddr("minEvictableIdleDuration", null));
+        reference.add(new StringRefAddr("timeBetweenEvictionRunsMillis", 
"2592000000"));
+        reference.add(new StringRefAddr("minEvictableIdleTimeMillis", 
"2592000000"));
+        final DriverAdapterCPDS restored = resolve(reference);
+        assertEquals(Duration.ofDays(30), 
restored.getDurationBetweenEvictionRuns());
+        assertEquals(Duration.ofDays(30), 
restored.getMinEvictableIdleDuration());
+    }
+
 }
diff --git 
a/src/test/java/org/apache/commons/dbcp2/datasources/TestLoginTimeout.java 
b/src/test/java/org/apache/commons/dbcp2/datasources/TestLoginTimeout.java
new file mode 100644
index 00000000..94fa5c56
--- /dev/null
+++ b/src/test/java/org/apache/commons/dbcp2/datasources/TestLoginTimeout.java
@@ -0,0 +1,591 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *   https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.dbcp2.datasources;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.SQLTimeoutException;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Stream;
+
+import javax.naming.Context;
+import javax.naming.NamingException;
+import javax.naming.spi.InitialContextFactory;
+import javax.sql.ConnectionPoolDataSource;
+import javax.sql.PooledConnection;
+
+import org.apache.commons.dbcp2.TesterDriver;
+import org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/** Tests physical connection login timeouts, including configuration after 
pool initialization. */
+class TestLoginTimeout {
+
+    /** Isolated JNDI lookup using only the environment supplied by each test. 
*/
+    public static final class TestContextFactory implements 
InitialContextFactory {
+        @Override
+        public Context getInitialContext(final Hashtable<?, ?> environment) 
throws NamingException {
+            final Context context = mock(Context.class);
+            
when(context.lookup("timeoutTest")).thenReturn(environment.get("test.cpds"));
+            return context;
+        }
+    }
+
+    private static final class RecordingCpds extends 
ConnectionPoolDataSourceProxy {
+        private int timeout = 9;
+        private final List<Integer> attempts = new ArrayList<>();
+        private boolean enforceTimeout;
+
+        RecordingCpds() throws ClassNotFoundException {
+            super(new DriverAdapterCPDS());
+            final DriverAdapterCPDS source = (DriverAdapterCPDS) delegate;
+            source.setDriver(TesterDriver.class.getName());
+            source.setUrl("jdbc:apache:commons:testdriver");
+            source.setUser("u1");
+            source.setPassword("p1");
+        }
+
+        @Override
+        public int getLoginTimeout() {
+            return timeout;
+        }
+
+        @Override
+        public PooledConnection getPooledConnection() throws SQLException {
+            recordAttempt();
+            return super.getPooledConnection();
+        }
+
+        @Override
+        public PooledConnection getPooledConnection(final String user, final 
String password) throws SQLException {
+            recordAttempt();
+            return super.getPooledConnection(user, password);
+        }
+
+        private void recordAttempt() throws SQLTimeoutException {
+            attempts.add(timeout);
+            if (enforceTimeout && timeout == 1) {
+                throw new SQLTimeoutException("Simulated connection exceeds 
one second");
+            }
+        }
+
+        @Override
+        public void setLoginTimeout(final int seconds) {
+            timeout = seconds;
+        }
+    }
+
+    /** Serializable provider with mutable or non-identity equality, and 
controllable connection creation. */
+    private static final class SerializableCpds extends DriverAdapterCPDS {
+        private static final long serialVersionUID = 1L;
+
+        private final List<Integer> attempts = 
Collections.synchronizedList(new ArrayList<>());
+        private transient CountDownLatch entered;
+        private transient CountDownLatch release;
+        private boolean equalToOtherProviders;
+
+        SerializableCpds() throws ClassNotFoundException {
+            setDriver(TesterDriver.class.getName());
+            setUrl("jdbc:apache:commons:testdriver");
+            setUser("u1");
+            setPassword("p1");
+            setLoginTimeout(9);
+        }
+
+        @Override
+        public boolean equals(final Object other) {
+            if (!(other instanceof SerializableCpds)) {
+                return false;
+            }
+            final SerializableCpds provider = (SerializableCpds) other;
+            return equalToOtherProviders == provider.equalToOtherProviders && 
(equalToOtherProviders || getLoginTimeout() == provider.getLoginTimeout());
+        }
+
+        @Override
+        public PooledConnection getPooledConnection() throws SQLException {
+            attempts.add(getLoginTimeout());
+            if (entered != null && entered.getCount() != 0) {
+                entered.countDown();
+                try {
+                    assertTrue(release.await(10, TimeUnit.SECONDS));
+                } catch (final InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    throw new SQLException(e);
+                }
+            }
+            return super.getPooledConnection();
+        }
+
+        @Override
+        public int hashCode() {
+            return equalToOtherProviders ? 1 : getLoginTimeout();
+        }
+    }
+
+    static Stream<Duration> interruptedTimeouts() {
+        return Stream.of(null, Duration.ZERO, Duration.ofMillis(100));
+    }
+
+    static Stream<Arguments> serializationTimeouts() {
+        return Stream.of(false, true).flatMap(shared -> Stream.of(false, 
true).map(configured -> Arguments.of(shared, configured)));
+    }
+
+    static Stream<Arguments> loginTimeouts() {
+        return Stream.of(false, true).flatMap(shared -> Stream.of(false, 
true).flatMap(jndi -> Stream.of(false, true)
+                .flatMap(credentials -> Stream.of(Arguments.of(Duration.ZERO, 
0), Arguments.of(Duration.ofNanos(1), 1),
+                        Arguments.of(Duration.ofMillis(1900), 1), 
Arguments.of(Duration.ofSeconds(5), 5),
+                        Arguments.of(Duration.ofSeconds(Long.MAX_VALUE), 
Integer.MAX_VALUE))
+                        .map(timeout -> Arguments.of(shared, jndi, 
credentials, timeout.get()[0], timeout.get()[1])))));
+    }
+
+    private static ConnectionPoolDataSource mockProvider(final AtomicInteger 
timeout) throws SQLException {
+        final ConnectionPoolDataSource provider = 
mock(ConnectionPoolDataSource.class);
+        when(provider.getLoginTimeout()).thenAnswer(invocation -> 
timeout.get());
+        doAnswer(invocation -> {
+            timeout.set(invocation.getArgument(0));
+            return null;
+        }).when(provider).setLoginTimeout(anyInt());
+        return provider;
+    }
+
+    private static InstanceKeyDataSource newDataSource(final boolean shared, 
final boolean jndi, final ConnectionPoolDataSource provider) {
+        final InstanceKeyDataSource source = shared ? new 
SharedPoolDataSource() : new PerUserPoolDataSource();
+        if (jndi) {
+            final Properties environment = new Properties();
+            environment.setProperty(Context.INITIAL_CONTEXT_FACTORY, 
TestContextFactory.class.getName());
+            environment.put("test.cpds", provider);
+            source.setJndiEnvironment(environment);
+            source.setDataSourceName("timeoutTest");
+        } else {
+            source.setConnectionPoolDataSource(provider);
+        }
+        source.setDefaultMaxIdle(0);
+        return source;
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testConnectionFailureRestoresProviderTimeout(final boolean 
credentials) throws SQLException {
+        final AtomicInteger timeout = new AtomicInteger(9);
+        final ConnectionPoolDataSource provider = mockProvider(timeout);
+        final SQLTimeoutException failure = new SQLTimeoutException("Login 
exceeded timeout");
+        when(provider.getPooledConnection()).thenThrow(failure);
+        when(provider.getPooledConnection("u1", "p1")).thenThrow(failure);
+        assertSame(failure, assertThrows(SQLTimeoutException.class, () -> 
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+                credentials ? "u1" : null, "p1", Duration.ofMillis(100))));
+        assertEquals(9, timeout.get());
+    }
+
+    @Test
+    void testConnectionFailureSuppressesRestoreFailure() throws SQLException {
+        final ConnectionPoolDataSource provider = 
mock(ConnectionPoolDataSource.class);
+        final SQLTimeoutException failure = new SQLTimeoutException("Login 
timed out");
+        final SQLException restoreFailure = new SQLException("Restore failed");
+        when(provider.getLoginTimeout()).thenReturn(9);
+        when(provider.getPooledConnection()).thenThrow(failure);
+        doThrow(restoreFailure).when(provider).setLoginTimeout(9);
+        assertSame(failure, assertThrows(SQLTimeoutException.class, () -> 
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+                null, null, Duration.ofSeconds(1))));
+        assertEquals(Arrays.asList(restoreFailure), 
Arrays.asList(failure.getSuppressed()));
+    }
+
+    @Test
+    void testEqualTimeoutDoesNotCallSetter() throws SQLException {
+        final ConnectionPoolDataSource provider = 
mock(ConnectionPoolDataSource.class);
+        when(provider.getLoginTimeout()).thenReturn(1);
+        ConnectionPoolDataSourceUtils.getPooledConnection(provider, null, 
null, Duration.ofMillis(100));
+        verify(provider, never()).setLoginTimeout(anyInt());
+    }
+
+    @ParameterizedTest
+    @MethodSource("loginTimeouts")
+    void testLoginTimeoutForInitialAndLaterConnections(final boolean shared, 
final boolean jndi, final boolean credentials,
+            final Duration duration, final int expected) throws Exception {
+        final RecordingCpds provider = new RecordingCpds();
+        try (InstanceKeyDataSource source = newDataSource(shared, jndi, 
provider)) {
+            source.setLoginTimeout(duration);
+            assertEquals(duration, source.getLoginTimeoutDuration());
+            assertEquals(expected, source.getLoginTimeout());
+            try (Connection connection = credentials ? 
source.getConnection("u1", "p1") : source.getConnection()) {
+                assertFalse(connection.isClosed());
+                assertEquals(9, provider.getLoginTimeout());
+            }
+            assertFalse(provider.attempts.isEmpty());
+            provider.attempts.forEach(value -> assertEquals(expected, 
value.intValue()));
+            provider.attempts.clear();
+            source.setLoginTimeout(Duration.ofSeconds(3));
+            try (Connection connection = credentials ? 
source.getConnection("u1", "p1") : source.getConnection()) {
+                assertFalse(connection.isClosed());
+            }
+            assertFalse(provider.attempts.isEmpty());
+            provider.attempts.forEach(value -> assertEquals(3, 
value.intValue()));
+            assertEquals(9, provider.getLoginTimeout());
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testLoginTimeoutRejectsInvalidValues(final boolean shared) throws 
Exception {
+        try (InstanceKeyDataSource source = shared ? new 
SharedPoolDataSource() : new PerUserPoolDataSource()) {
+            source.setLoginTimeout(Duration.ofSeconds(5));
+            assertThrows(NullPointerException.class, () -> 
source.setLoginTimeout(null));
+            assertThrows(IllegalArgumentException.class, () -> 
source.setLoginTimeout(Duration.ofNanos(-1)));
+            assertThrows(IllegalArgumentException.class, () -> 
source.setLoginTimeout(-1));
+            assertEquals(Duration.ofSeconds(5), 
source.getLoginTimeoutDuration());
+        }
+    }
+
+    @Test
+    void testRestoreFailureClosesConnectionAndSuppressesCloseFailure() throws 
SQLException {
+        final ConnectionPoolDataSource provider = 
mock(ConnectionPoolDataSource.class);
+        final PooledConnection connection = mock(PooledConnection.class);
+        final SQLException restoreFailure = new SQLException("Restore failed");
+        final SQLException closeFailure = new SQLException("Close failed");
+        when(provider.getLoginTimeout()).thenReturn(9);
+        when(provider.getPooledConnection()).thenReturn(connection);
+        doThrow(restoreFailure).when(provider).setLoginTimeout(9);
+        doThrow(closeFailure).when(connection).close();
+        assertSame(restoreFailure, assertThrows(SQLException.class, () -> 
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+                null, null, Duration.ofSeconds(1))));
+        verify(connection).close();
+        assertEquals(Arrays.asList(closeFailure), 
Arrays.asList(restoreFailure.getSuppressed()));
+    }
+
+    @Test
+    void testSetterFailureRestoresProviderTimeout() throws SQLException {
+        final AtomicInteger timeout = new AtomicInteger(9);
+        final ConnectionPoolDataSource provider = mockProvider(timeout);
+        final SQLException failure = new SQLException("Cannot apply timeout");
+        doAnswer(invocation -> {
+            timeout.set(1);
+            throw failure;
+        }).when(provider).setLoginTimeout(1);
+        assertSame(failure, assertThrows(SQLException.class, () -> 
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+                null, null, Duration.ofSeconds(1))));
+        assertEquals(9, timeout.get());
+        verify(provider, never()).getPooledConnection();
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testSharedProviderSerializesTemporaryTimeouts(final boolean 
secondUsesProviderDefault) throws Exception {
+        final AtomicInteger timeout = new AtomicInteger(9);
+        final ConnectionPoolDataSource provider = mockProvider(timeout);
+        final PooledConnection connection = mock(PooledConnection.class);
+        final CountDownLatch firstEntered = new CountDownLatch(1);
+        final CountDownLatch releaseFirst = new CountDownLatch(1);
+        final CountDownLatch secondStarted = new CountDownLatch(1);
+        final List<Integer> observed = new ArrayList<>();
+        when(provider.getPooledConnection()).thenAnswer(invocation -> {
+            observed.add(timeout.get());
+            if (observed.size() == 1) {
+                firstEntered.countDown();
+                assertTrue(releaseFirst.await(10, TimeUnit.SECONDS));
+                assertEquals(1, timeout.get());
+            }
+            return connection;
+        });
+        final ExecutorService executor = Executors.newFixedThreadPool(2);
+        try {
+            final Future<PooledConnection> first = executor.submit(() -> 
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+                    null, null, Duration.ofSeconds(1)));
+            assertTrue(firstEntered.await(10, TimeUnit.SECONDS));
+            final Future<PooledConnection> second = executor.submit(() -> {
+                secondStarted.countDown();
+                return 
ConnectionPoolDataSourceUtils.getPooledConnection(provider, null, null, 
secondUsesProviderDefault ? null : Duration.ofSeconds(2));
+            });
+            assertTrue(secondStarted.await(10, TimeUnit.SECONDS));
+            assertThrows(TimeoutException.class, () -> second.get(100, 
TimeUnit.MILLISECONDS));
+            releaseFirst.countDown();
+            assertSame(connection, first.get(10, TimeUnit.SECONDS));
+            assertSame(connection, second.get(10, TimeUnit.SECONDS));
+            assertEquals(Arrays.asList(1, secondUsesProviderDefault ? 9 : 2), 
observed);
+            assertEquals(9, timeout.get());
+        } finally {
+            releaseFirst.countDown();
+            executor.shutdownNow();
+            assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+        }
+    }
+
+    @Test
+    void testUnconfiguredTimeoutDoesNotCallProviderTimeoutMethods() throws 
SQLException {
+        final ConnectionPoolDataSource provider = 
mock(ConnectionPoolDataSource.class);
+        ConnectionPoolDataSourceUtils.getPooledConnection(provider, null, 
null, null);
+        verify(provider).getPooledConnection();
+        verify(provider, never()).getLoginTimeout();
+        verify(provider, never()).setLoginTimeout(anyInt());
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testUnconfiguredTimeoutPreservesProviderDefault(final boolean shared) 
throws Exception {
+        final RecordingCpds provider = new RecordingCpds();
+        try (InstanceKeyDataSource source = newDataSource(shared, false, 
provider);
+                Connection connection = source.getConnection()) {
+            assertFalse(connection.isClosed());
+            assertFalse(provider.attempts.isEmpty());
+            provider.attempts.forEach(value -> assertEquals(9, 
value.intValue()));
+        }
+    }
+
+    static Stream<Throwable> uncheckedFailures() {
+        return Stream.of(new IllegalStateException("Driver failure"), new 
AssertionError("Driver error"));
+    }
+
+    @ParameterizedTest
+    @MethodSource("uncheckedFailures")
+    void testUncheckedConnectionFailureRestoresTimeout(final Throwable 
failure) throws SQLException {
+        final AtomicInteger timeout = new AtomicInteger(9);
+        final ConnectionPoolDataSource provider = mockProvider(timeout);
+        when(provider.getPooledConnection()).thenThrow(failure);
+        assertSame(failure, assertThrows(failure.getClass(), () -> 
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+                null, null, Duration.ofSeconds(1))));
+        assertEquals(9, timeout.get());
+    }
+
+    @Test
+    void testRepeatedDriverExceptionDoesNotSuppressItself() throws 
SQLException {
+        final ConnectionPoolDataSource provider = 
mock(ConnectionPoolDataSource.class);
+        final SQLException failure = new SQLException("Driver failed");
+        when(provider.getLoginTimeout()).thenReturn(9);
+        when(provider.getPooledConnection()).thenThrow(failure);
+        doThrow(failure).when(provider).setLoginTimeout(9);
+        assertSame(failure, assertThrows(SQLException.class, () -> 
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+                null, null, Duration.ofSeconds(1))));
+        assertEquals(0, failure.getSuppressed().length);
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testProviderEnforcesTimeoutForInitialAndLaterConnections(final 
boolean shared) throws Exception {
+        final RecordingCpds provider = new RecordingCpds();
+        provider.enforceTimeout = true;
+        try (InstanceKeyDataSource source = newDataSource(shared, false, 
provider)) {
+            source.setLoginTimeout(Duration.ofMillis(100));
+            assertThrows(SQLException.class, source::getConnection);
+            assertEquals(9, provider.getLoginTimeout());
+        }
+        try (InstanceKeyDataSource source = newDataSource(shared, false, 
provider)) {
+            source.setLoginTimeout(5);
+            try (Connection connection = source.getConnection()) {
+                assertFalse(connection.isClosed());
+            }
+            source.setLoginTimeout(Duration.ofMillis(100));
+            assertThrows(SQLException.class, source::getConnection);
+            assertEquals(9, provider.getLoginTimeout());
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("serializationTimeouts")
+    void testDeserializedWrappersShareLiveLoginTimeout(final boolean shared, 
final boolean configured) throws Exception {
+        final SerializableCpds provider = new SerializableCpds();
+        try (InstanceKeyDataSource source = newDataSource(shared, false, 
provider)) {
+            if (configured) {
+                source.setLoginTimeout(Duration.ofSeconds(5));
+            }
+            try (Connection connection = source.getConnection()) {
+                assertFalse(connection.isClosed());
+            }
+            final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+            try (ObjectOutputStream output = new ObjectOutputStream(bytes)) {
+                output.writeObject(source);
+            }
+            try (ObjectInputStream input = new ObjectInputStream(new 
ByteArrayInputStream(bytes.toByteArray()));
+                    InstanceKeyDataSource restored = (InstanceKeyDataSource) 
input.readObject()) {
+                assertEquals(source.getLoginTimeoutDuration(), 
restored.getLoginTimeoutDuration());
+                restored.setLoginTimeout(Duration.ofSeconds(3));
+                assertEquals(Duration.ofSeconds(3), 
source.getLoginTimeoutDuration());
+                provider.attempts.clear();
+                try (Connection connection = restored.getConnection()) {
+                    assertFalse(connection.isClosed());
+                }
+                assertFalse(provider.attempts.isEmpty());
+                provider.attempts.forEach(value -> assertEquals(3, 
value.intValue()));
+                source.setLoginTimeout(Duration.ofSeconds(7));
+                assertEquals(Duration.ofSeconds(7), 
restored.getLoginTimeoutDuration());
+                provider.attempts.clear();
+                try (Connection connection = restored.getConnection()) {
+                    assertFalse(connection.isClosed());
+                }
+                assertFalse(provider.attempts.isEmpty());
+                provider.attempts.forEach(value -> assertEquals(7, 
value.intValue()));
+                assertEquals(9, provider.getLoginTimeout());
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testProviderLocksUseIdentity(final boolean sameProvider) throws 
Exception {
+        final SerializableCpds firstProvider = new SerializableCpds();
+        final SerializableCpds secondProvider = sameProvider ? firstProvider : 
new SerializableCpds();
+        // Equal but distinct providers must not share a lock. A changing hash 
must not bypass a provider's own lock.
+        firstProvider.equalToOtherProviders = !sameProvider;
+        secondProvider.equalToOtherProviders = !sameProvider;
+        firstProvider.entered = new CountDownLatch(1);
+        firstProvider.release = new CountDownLatch(1);
+        final ExecutorService executor = Executors.newFixedThreadPool(2);
+        try {
+            final Future<PooledConnection> first = executor.submit(() -> 
ConnectionPoolDataSourceUtils.getPooledConnection(firstProvider,
+                    null, null, Duration.ofSeconds(1)));
+            assertTrue(firstProvider.entered.await(10, TimeUnit.SECONDS));
+            final Future<PooledConnection> second = executor.submit(() -> 
ConnectionPoolDataSourceUtils.getPooledConnection(secondProvider,
+                    null, null, Duration.ofSeconds(2)));
+            if (sameProvider) {
+                assertThrows(TimeoutException.class, () -> second.get(100, 
TimeUnit.MILLISECONDS));
+            } else {
+                assertNotNull(second.get(5, TimeUnit.SECONDS));
+                assertEquals(Collections.singletonList(2), 
secondProvider.attempts);
+            }
+            firstProvider.release.countDown();
+            first.get(10, TimeUnit.SECONDS).close();
+            second.get(10, TimeUnit.SECONDS).close();
+            assertEquals(sameProvider ? Arrays.asList(1, 2) : 
Collections.singletonList(1), firstProvider.attempts);
+            assertEquals(9, firstProvider.getLoginTimeout());
+            assertEquals(9, secondProvider.getLoginTimeout());
+        } finally {
+            firstProvider.release.countDown();
+            executor.shutdownNow();
+            assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("interruptedTimeouts")
+    void testProviderLockPreservesInterruption(final Duration timeout) throws 
SQLException {
+        final ConnectionPoolDataSource provider = 
mock(ConnectionPoolDataSource.class);
+        Thread.currentThread().interrupt();
+        try {
+            final SQLException failure = assertThrows(SQLException.class, () 
-> ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+                    null, null, timeout));
+            assertInstanceOf(InterruptedException.class, failure.getCause());
+            assertTrue(Thread.currentThread().isInterrupted());
+            verify(provider, never()).getPooledConnection();
+            verify(provider, never()).setLoginTimeout(anyInt());
+        } finally {
+            Thread.interrupted();
+        }
+    }
+
+    @Test
+    void testWaitingForProviderHonorsPositiveTimeout() throws Exception {
+        final SerializableCpds provider = new SerializableCpds();
+        provider.entered = new CountDownLatch(1);
+        provider.release = new CountDownLatch(1);
+        final ExecutorService executor = Executors.newFixedThreadPool(2);
+        try {
+            final Future<PooledConnection> first = executor.submit(() -> 
ConnectionPoolDataSourceUtils.getPooledConnection(provider, null, null, null));
+            assertTrue(provider.entered.await(10, TimeUnit.SECONDS));
+            final Future<SQLTimeoutException> second = executor.submit(() -> 
assertThrows(SQLTimeoutException.class,
+                    () -> 
ConnectionPoolDataSourceUtils.getPooledConnection(provider, null, null, 
Duration.ofMillis(100))));
+            assertNotNull(second.get(5, TimeUnit.SECONDS));
+            assertEquals(Collections.singletonList(9), provider.attempts);
+            provider.release.countDown();
+            first.get(10, TimeUnit.SECONDS).close();
+            assertEquals(9, provider.getLoginTimeout());
+        } finally {
+            provider.release.countDown();
+            executor.shutdownNow();
+            assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"read", "set", "connect", "restore"})
+    void testProviderLockReleasedAfterFailure(final String phase) throws 
Exception {
+        final ConnectionPoolDataSource provider = 
mock(ConnectionPoolDataSource.class);
+        final AtomicInteger timeout = new AtomicInteger(9);
+        final AtomicBoolean failOnce = new AtomicBoolean(true);
+        final SQLException failure = new SQLException("Provider failure during 
" + phase);
+        when(provider.getLoginTimeout()).thenAnswer(invocation -> {
+            if ("read".equals(phase) && failOnce.getAndSet(false)) {
+                throw failure;
+            }
+            return timeout.get();
+        });
+        doAnswer(invocation -> {
+            final int seconds = invocation.getArgument(0);
+            timeout.set(seconds);
+            if (("set".equals(phase) && seconds == 1 || 
"restore".equals(phase) && seconds == 9) && failOnce.getAndSet(false)) {
+                throw failure;
+            }
+            return null;
+        }).when(provider).setLoginTimeout(anyInt());
+        when(provider.getPooledConnection()).thenAnswer(invocation -> {
+            if ("connect".equals(phase) && failOnce.getAndSet(false)) {
+                throw failure;
+            }
+            return mock(PooledConnection.class);
+        });
+        assertSame(failure, assertThrows(SQLException.class, () -> 
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+                null, null, Duration.ofSeconds(1))));
+        assertEquals(9, timeout.get());
+        // A different thread must be able to acquire the provider lock after 
every failure path.
+        final ExecutorService executor = Executors.newSingleThreadExecutor();
+        try {
+            final Future<PooledConnection> next = executor.submit(() -> 
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+                    null, null, Duration.ofSeconds(2)));
+            final PooledConnection connection = next.get(5, TimeUnit.SECONDS);
+            assertNotNull(connection);
+            connection.close();
+            assertEquals(9, timeout.get());
+        } finally {
+            executor.shutdownNow();
+            assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+        }
+    }
+
+}

Reply via email to