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


The following commit(s) were added to refs/heads/master by this push:
     new 3b6a4c41 Fix pooled resource close races and data source shutdown
3b6a4c41 is described below

commit 3b6a4c41137f222baeca1780184e0d0731db47d7
Author: Gary Gregory <[email protected]>
AuthorDate: Thu Nov 26 11:19:46 2026 -0500

    Fix pooled resource close races and data source shutdown
    
    Serialize statement closes and coordinate managed connection cleanup
    with
    transaction completion to prevent duplicate pool returns.
    
    Coordinate data source shutdown with initialization and password
    recovery,
    including deserialized instances. Prevent repeated closes from removing
    registrations belonging to newer data sources.
    
    Add 81 regression cases and four changelog entries.
---
 src/changes/changes.xml                            |   4 +
 .../apache/commons/dbcp2/DelegatingStatement.java  |   7 +-
 .../dbcp2/datasources/InstanceKeyDataSource.java   |  54 ++-
 .../datasources/InstanceKeyDataSourceFactory.java  |  12 +
 .../dbcp2/datasources/PerUserPoolDataSource.java   |  37 +-
 .../dbcp2/datasources/SharedPoolDataSource.java    |  41 +-
 .../commons/dbcp2/managed/ManagedConnection.java   |  44 +-
 .../commons/dbcp2/ConcurrentCloseTestSupport.java  | 106 +++++
 .../TestConcurrentManagedConnectionClose.java      | 394 +++++++++++++++++
 .../dbcp2/TestConcurrentStatementClose.java        | 234 ++++++++++
 .../apache/commons/dbcp2/TestDataSourceClose.java  | 487 +++++++++++++++++++++
 11 files changed, 1374 insertions(+), 46 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index df2f94eb..2bb2074b 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -87,6 +87,10 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="Gary Gregory">Preserve local 
login timeout settings when SharedPoolDataSource and PerUserPoolDataSource are 
deserialized before configuring a connection provider, including the 
distinction between an unset timeout and explicit zero.</action>
       <action type="fix" dev="ggregory" due-to="Ken Pritchard, Gary Gregory" 
issue="DBCP-601">Clear the transaction association when 
LocalXAResource.prepare() returns XA_RDONLY so read-only pooled connections can 
enlist in subsequent transactions #552.</action>
       <action type="fix" dev="ggregory" due-to="Vladimir Zhilin, Gary 
Gregory">Serialize concurrent connection closes in DelegatingConnection and the 
CPDS adapter to prevent returning a pooled connection again after another 
caller has borrowed it #564.</action>
+      <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent 
duplicate connection returns when ManagedConnection.close() overlaps 
transaction completion.</action>
+      <action type="fix" dev="ggregory" due-to="Gary Gregory">Serialize 
DelegatingStatement.close() to prevent concurrent closes from returning 
prepared and callable statements after they have been borrowed again.</action>
+      <action type="fix" dev="ggregory" due-to="Gary Gregory">Coordinate 
PerUserPoolDataSource and SharedPoolDataSource shutdown with pool 
initialization, and prevent connection requests and password-change recovery 
from reopening closed data sources.</action>
+      <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent repeated 
PerUserPoolDataSource and SharedPoolDataSource closes from unregistering 
another data source that reuses the same instance key.</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/DelegatingStatement.java 
b/src/main/java/org/apache/commons/dbcp2/DelegatingStatement.java
index 4d775d59..7b09be16 100644
--- a/src/main/java/org/apache/commons/dbcp2/DelegatingStatement.java
+++ b/src/main/java/org/apache/commons/dbcp2/DelegatingStatement.java
@@ -133,9 +133,14 @@ public class DelegatingStatement extends AbandonedTrace 
implements Statement {
 
     /**
      * Closes this DelegatingStatement and closes any ResultSets that were not 
explicitly closed.
+     *
+     * <p>
+     * Concurrent calls to this implementation are serialized so a closed 
wrapper cannot return a pooled delegate again after it has been borrowed by
+     * another caller. This does not make other statement operations 
thread-safe. Overrides must provide equivalent protection against concurrent 
closing.
+     * </p>
      */
     @Override
-    public void close() throws SQLException {
+    public synchronized void close() throws SQLException {
         if (isClosed()) {
             return;
         }
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 0bba6aab..74ec73f5 100644
--- 
a/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java
+++ 
b/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java
@@ -89,6 +89,16 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
     /** Guards property setters - once true, setters throw 
IllegalStateException */
     private volatile boolean getConnectionCalled;
 
+    /**
+     * Prevents borrowing or creating pools after shutdown.
+     */
+    private volatile boolean closed;
+
+    /**
+     * Registered data source owning the shutdown state and initialization 
monitor for shared pools, or null for local pools.
+     */
+    private transient InstanceKeyDataSource lifecycleSource;
+
     /** Underlying source of PooledConnections */
     private ConnectionPoolDataSource dataSource;
 
@@ -199,7 +209,23 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
     }
 
     /**
-     * Closes the connection pool being maintained by this datasource.
+     * Checks whether this data source has been closed.
+     *
+     * @throws SQLException Thrown if this data source has been closed.
+     */
+    final void assertOpen() throws SQLException {
+        if (getLifecycleLock().closed) {
+            throw new SQLException("Data source is closed");
+        }
+    }
+
+    /**
+     * Closes the connection pools maintained by this data source and prevents 
further connection requests.
+     *
+     * <p>
+     * Connections already borrowed remain usable and are destroyed when 
returned. Repeated calls have no effect.
+     * Deserialized instances that reuse these pools share the same shutdown 
state.
+     * </p>
      */
     @Override
     public abstract void close() throws SQLException;
@@ -250,6 +276,7 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
      */
     @Override
     public Connection getConnection(final String userName, final String 
userPassword) throws SQLException {
+        assertOpen();
         if (instanceKey == null) {
             throw new SQLException("Must set the ConnectionPoolDataSource "
                     + "through setDataSourceName or 
setConnectionPoolDataSource before calling getConnection.");
@@ -601,6 +628,15 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
         return value;
     }
 
+    /**
+     * Gets the owner of the shutdown state and monitor used to initialize or 
close shared pools.
+     *
+     * @return the registered source when sharing pools, or this instance.
+     */
+    final InstanceKeyDataSource getLifecycleLock() {
+        return lifecycleSource == null ? this : lifecycleSource;
+    }
+
     /**
      * 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}.
@@ -774,6 +810,13 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
         return iface.isInstance(this);
     }
 
+    /**
+     * Marks this data source closed while holding the monitor used for pool 
initialization.
+     */
+    final void setClosed() {
+        getLifecycleLock().closed = true;
+    }
+
     /**
      * Sets the back end ConnectionPoolDataSource. This property should not be 
set if using JNDI to access the
      * data source.
@@ -1146,6 +1189,15 @@ public abstract class InstanceKeyDataSource implements 
DataSource, Referenceable
         jndiEnvironment.setProperty(key, value);
     }
 
+    /**
+     * Shares the shutdown state and initialization monitor of a registered 
data source when reusing its pools.
+     *
+     * @param source The source whose pools are reused after deserialization.
+     */
+    final void setLifecycleSource(final InstanceKeyDataSource source) {
+        lifecycleSource = instanceKey == null ? null : 
source.getLifecycleLock();
+    }
+
     /**
      * 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.
diff --git 
a/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSourceFactory.java
 
b/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSourceFactory.java
index beba3eed..349561ff 100644
--- 
a/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSourceFactory.java
+++ 
b/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSourceFactory.java
@@ -109,6 +109,18 @@ abstract class InstanceKeyDataSourceFactory implements 
ObjectFactory {
         }
     }
 
+    /**
+     * Removes a registration only if it still belongs to the specified data 
source.
+     *
+     * @param key The registration key, or null if the data source was not 
registered.
+     * @param dataSource The owner of the registration.
+     */
+    static void removeInstance(final String key, final InstanceKeyDataSource 
dataSource) {
+        if (key != null) {
+            INSTANCE_MAP.remove(key, dataSource);
+        }
+    }
+
     private Boolean booleanValueOf(final RefAddr refAddr) {
         return Boolean.valueOf(toString(refAddr));
     }
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 426750f2..fcc2d547 100644
--- 
a/src/main/java/org/apache/commons/dbcp2/datasources/PerUserPoolDataSource.java
+++ 
b/src/main/java/org/apache/commons/dbcp2/datasources/PerUserPoolDataSource.java
@@ -188,14 +188,17 @@ public class PerUserPoolDataSource extends 
InstanceKeyDataSource {
     }
 
     /**
-     * Closes pool(s) maintained by this data source.
+     * Closes pools maintained by this data source and prevents further 
connection requests.
      *
      * @see org.apache.commons.pool2.ObjectPool#close()
      */
     @Override
     public void close() {
-        managers.values().forEach(manager -> 
Utils.closeQuietly(getCPDSConnectionFactoryPool(manager)));
-        InstanceKeyDataSourceFactory.removeInstance(getInstanceKey());
+        synchronized (getLifecycleLock()) {
+            setClosed();
+            managers.values().forEach(manager -> 
Utils.closeQuietly(getCPDSConnectionFactoryPool(manager)));
+            InstanceKeyDataSourceFactory.removeInstance(getInstanceKey(), 
getLifecycleLock());
+        }
     }
 
     /**
@@ -589,7 +592,8 @@ public class PerUserPoolDataSource extends 
InstanceKeyDataSource {
         final PoolKey key = getPoolKey(userName);
         ObjectPool<PooledConnectionAndInfo> pool;
         PooledConnectionManager manager;
-        synchronized (this) {
+        synchronized (getLifecycleLock()) {
+            assertOpen();
             manager = managers.get(key);
             if (manager == null) {
                 try {
@@ -607,6 +611,7 @@ public class PerUserPoolDataSource extends 
InstanceKeyDataSource {
         } catch (final NoSuchElementException ex) {
             throw new SQLException("Could not retrieve connection info from 
pool", ex);
         } catch (final Exception e) {
+            assertOpen();
             // See if failure is due to CPDSConnectionFactory authentication 
failure
             try {
                 testCPDS(userName, password);
@@ -615,14 +620,15 @@ public class PerUserPoolDataSource extends 
InstanceKeyDataSource {
             }
             // New password works, so kill the old pool, create a new one, and 
borrow
             manager.closePool(userName);
-            synchronized (this) {
+            synchronized (getLifecycleLock()) {
+                assertOpen();
                 managers.remove(key);
-            }
-            try {
-                registerPool(userName, password);
-                pool = getPool(key);
-            } catch (final NamingException ne) {
-                throw new SQLException("RegisterPool failed", ne);
+                try {
+                    registerPool(userName, password);
+                    pool = getPool(key);
+                } catch (final NamingException ne) {
+                    throw new SQLException("RegisterPool failed", ne);
+                }
             }
             try {
                 info = pool.borrowObject();
@@ -666,8 +672,8 @@ public class PerUserPoolDataSource extends 
InstanceKeyDataSource {
      * Deserializes an instance from an ObjectInputStream.
      *
      * <p>
-     * When the registration key resolves to an existing data source, its pool 
managers and live login timeout configuration are reused. An instance serialized
-     * without a key retains its own login timeout setting.
+     * When the registration key resolves to an existing data source, its pool 
managers, shutdown state, and live login timeout configuration are reused.
+     * An instance serialized without a key retains its own login timeout 
setting.
      * </p>
      *
      * @param in The source ObjectInputStream.
@@ -679,6 +685,7 @@ public class PerUserPoolDataSource extends 
InstanceKeyDataSource {
         in.defaultReadObject();
         final PerUserPoolDataSource source = readObjectImpl();
         this.managers = source.managers;
+        setLifecycleSource(source);
         setLoginTimeoutSource(source);
     }
 
@@ -690,7 +697,9 @@ public class PerUserPoolDataSource extends 
InstanceKeyDataSource {
         }
     }
 
-    private synchronized void registerPool(final String userName, final String 
password) throws NamingException, SQLException {
+    // Called with the lifecycle monitor held, including during 
password-change recovery.
+    private void registerPool(final String userName, final String password) 
throws NamingException, SQLException {
+        assertOpen();
         final ConnectionPoolDataSource cpds = testCPDS(userName, password);
         // Set up the factory we will use (passing the pool associates
         // the factory with the pool, so we do not have to do so
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 571fd5dc..02eec3b6 100644
--- 
a/src/main/java/org/apache/commons/dbcp2/datasources/SharedPoolDataSource.java
+++ 
b/src/main/java/org/apache/commons/dbcp2/datasources/SharedPoolDataSource.java
@@ -75,19 +75,23 @@ public class SharedPoolDataSource extends 
InstanceKeyDataSource {
     }
 
     /**
-     * Closes pool being maintained by this data source.
+     * Closes the pool maintained by this data source and prevents further 
connection requests.
      */
     @Override
     public void close() throws SQLException {
-        if (pool != null) {
-            pool.close();
+        final SharedPoolDataSource source = getPoolSource();
+        synchronized (source) {
+            setClosed();
+            if (source.pool != null) {
+                source.pool.close();
+            }
+            InstanceKeyDataSourceFactory.removeInstance(getInstanceKey(), 
getLifecycleLock());
         }
-        InstanceKeyDataSourceFactory.removeInstance(getInstanceKey());
     }
 
     @Override
     protected PooledConnectionManager getConnectionManager(final UserPassKey 
userPassKey) {
-        return factory;
+        return getPoolSource().factory;
     }
 
     /**
@@ -105,6 +109,7 @@ public class SharedPoolDataSource extends 
InstanceKeyDataSource {
      * @return The number of active connections in the pool.
      */
     public int getNumActive() {
+        final KeyedObjectPool<UserPassKey, PooledConnectionAndInfo> pool = 
getPoolSource().pool;
         return pool == null ? 0 : pool.getNumActive();
     }
 
@@ -114,6 +119,7 @@ public class SharedPoolDataSource extends 
InstanceKeyDataSource {
      * @return The number of idle connections in the pool.
      */
     public int getNumIdle() {
+        final KeyedObjectPool<UserPassKey, PooledConnectionAndInfo> pool = 
getPoolSource().pool;
         return pool == null ? 0 : pool.getNumIdle();
     }
 
@@ -121,10 +127,12 @@ public class SharedPoolDataSource extends 
InstanceKeyDataSource {
     protected PooledConnectionAndInfo getPooledConnectionAndInfo(final String 
userName, final String userPassword)
             throws SQLException {
 
-        synchronized (this) {
-            if (pool == null) {
+        final SharedPoolDataSource source = getPoolSource();
+        synchronized (source) {
+            assertOpen();
+            if (source.pool == null) {
                 try {
-                    registerPool(userName, userPassword);
+                    source.registerPool(userName, userPassword);
                 } catch (final NamingException e) {
                     throw new SQLException("registerPool failed", e);
                 }
@@ -132,12 +140,21 @@ public class SharedPoolDataSource extends 
InstanceKeyDataSource {
         }
 
         try {
-            return pool.borrowObject(new UserPassKey(userName, userPassword));
+            return source.pool.borrowObject(new UserPassKey(userName, 
userPassword));
         } catch (final Exception e) {
             throw new SQLException("Could not retrieve connection info from 
pool", e);
         }
     }
 
+    /**
+     * Gets the owner of the pool, including when deserialization precedes 
pool initialization.
+     *
+     * @return the registered source when sharing pools, or this instance.
+     */
+    private SharedPoolDataSource getPoolSource() {
+        return (SharedPoolDataSource) getLifecycleLock();
+    }
+
     /**
      * Gets a new {@link Reference} to this {@link SharedPoolDataSource}.
      */
@@ -152,8 +169,8 @@ public class SharedPoolDataSource extends 
InstanceKeyDataSource {
      * Deserializes an instance from an ObjectInputStream.
      *
      * <p>
-     * When the registration key resolves to an existing data source, its pool 
and live login timeout configuration are reused. An instance serialized
-     * without a key retains its own login timeout setting.
+     * When the registration key resolves to an existing data source, its 
pool, shutdown state, and live login timeout configuration are reused.
+     * An instance serialized without a key retains its own login timeout 
setting.
      * </p>
      *
      * @param in The source ObjectInputStream.
@@ -163,7 +180,7 @@ public class SharedPoolDataSource extends 
InstanceKeyDataSource {
     private void readObject(final ObjectInputStream in) throws IOException, 
ClassNotFoundException {
         in.defaultReadObject();
         final SharedPoolDataSource source = readObjectImpl();
-        this.pool = source.pool;
+        setLifecycleSource(source);
         setLoginTimeoutSource(source);
     }
 
diff --git 
a/src/main/java/org/apache/commons/dbcp2/managed/ManagedConnection.java 
b/src/main/java/org/apache/commons/dbcp2/managed/ManagedConnection.java
index 0fe5d14d..49c01e8a 100644
--- a/src/main/java/org/apache/commons/dbcp2/managed/ManagedConnection.java
+++ b/src/main/java/org/apache/commons/dbcp2/managed/ManagedConnection.java
@@ -127,7 +127,16 @@ public class ManagedConnection<C extends Connection> 
extends DelegatingConnectio
             lock.lock();
             try {
                 if (transactionContext == null || 
transactionContext.isTransactionComplete()) {
-                    super.close();
+                    if (isSharedConnection) {
+                        setDelegate(null);
+                        isSharedConnection = false;
+                    }
+                    try {
+                        super.close();
+                    } finally {
+                        // A completion callback must not close this delegate 
after it has been borrowed again.
+                        setDelegate(null);
+                    }
                 }
             } finally {
                 try {
@@ -225,25 +234,24 @@ public class ManagedConnection<C extends Connection> 
extends DelegatingConnectio
                 setDelegate(null);
                 isSharedConnection = false;
             }
-        } finally {
-            lock.unlock();
-        }
-        // autoCommit may have been changed directly on the underlying 
connection
-        clearCachedState();
-        // If this connection was closed during the transaction and there is
-        // still a delegate present close it
-        final Connection delegate = getDelegateInternal();
-        if (isClosedInternal() && delegate != null) {
-            try {
-                setDelegate(null);
-                if (!delegate.isClosed()) {
-                    delegate.close();
+            // autoCommit may have been changed directly on the underlying 
connection
+            clearCachedState();
+            // Keep delegate cleanup under the same lock as close(), so only 
one path can return it to the pool.
+            final Connection delegate = getDelegateInternal();
+            if (isClosedInternal() && delegate != null) {
+                try {
+                    setDelegate(null);
+                    if (!delegate.isClosed()) {
+                        delegate.close();
+                    }
+                } catch (final SQLException ignored) {
+                    // Not a whole lot we can do here as connection is closed
+                    // and this is a transaction callback so there is no
+                    // way to report the error.
                 }
-            } catch (final SQLException ignored) {
-                // Not a whole lot we can do here as connection is closed
-                // and this is a transaction callback so there is no
-                // way to report the error.
             }
+        } finally {
+            lock.unlock();
         }
     }
 
diff --git 
a/src/test/java/org/apache/commons/dbcp2/ConcurrentCloseTestSupport.java 
b/src/test/java/org/apache/commons/dbcp2/ConcurrentCloseTestSupport.java
new file mode 100644
index 00000000..5c1af1aa
--- /dev/null
+++ b/src/test/java/org/apache/commons/dbcp2/ConcurrentCloseTestSupport.java
@@ -0,0 +1,106 @@
+/*
+ * 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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.junit.jupiter.api.function.Executable;
+
+/**
+ * Bounded coordination for close regression tests.
+ */
+final class ConcurrentCloseTestSupport {
+
+    /**
+     * Runs an operation and retains any failure for the test thread.
+     */
+    static final class Task implements AutoCloseable {
+        private final AtomicReference<Throwable> failure = new 
AtomicReference<>();
+        private final Thread thread;
+
+        /**
+         * Starts a daemon worker, so a failed test cannot keep the test JVM 
alive.
+         */
+        Task(final Executable operation) {
+            thread = new Thread(() -> {
+                try {
+                    operation.execute();
+                } catch (final Throwable t) {
+                    failure.set(t);
+                }
+            }, "close-regression");
+            thread.setDaemon(true);
+            thread.start();
+        }
+
+        /**
+         * Waits for lock contention, failing if the operation finishes 
without waiting.
+         */
+        void awaitBlocked() throws InterruptedException {
+            final long deadline = System.nanoTime() + 
TimeUnit.SECONDS.toNanos(10);
+            while (thread.getState() != Thread.State.BLOCKED && 
thread.getState() != Thread.State.WAITING) {
+                assertTrue(thread.isAlive(), () -> "Operation finished instead 
of waiting: " + failure.get());
+                assertTrue(System.nanoTime() < deadline, "Operation did not 
wait for the other caller");
+                Thread.sleep(1);
+            }
+        }
+
+        /**
+         * Gets the operation's failure after waiting for completion.
+         */
+        Throwable awaitFailure() throws InterruptedException {
+            thread.join(TimeUnit.SECONDS.toMillis(10));
+            assertFalse(thread.isAlive(), "Operation did not finish");
+            return failure.get();
+        }
+
+        /**
+         * Waits for successful completion.
+         */
+        void awaitSuccess() throws InterruptedException {
+            assertNull(awaitFailure());
+        }
+
+        @Override
+        public void close() throws InterruptedException {
+            thread.interrupt();
+            thread.join(TimeUnit.SECONDS.toMillis(10));
+            assertFalse(thread.isAlive(), "Worker did not terminate");
+        }
+    }
+
+    /**
+     * Waits for a test checkpoint without allowing a broken test to hang.
+     */
+    static void await(final CountDownLatch latch) {
+        try {
+            assertTrue(latch.await(10, TimeUnit.SECONDS), "Checkpoint was not 
reached");
+        } catch (final InterruptedException e) {
+            Thread.currentThread().interrupt();
+            throw new AssertionError(e);
+        }
+    }
+
+    private ConcurrentCloseTestSupport() {
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/dbcp2/TestConcurrentManagedConnectionClose.java
 
b/src/test/java/org/apache/commons/dbcp2/TestConcurrentManagedConnectionClose.java
new file mode 100644
index 00000000..76c9204b
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/dbcp2/TestConcurrentManagedConnectionClose.java
@@ -0,0 +1,394 @@
+/*
+ * 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.apache.commons.dbcp2.ConcurrentCloseTestSupport.await;
+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.assertNull;
+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 java.lang.reflect.Proxy;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.time.Duration;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.transaction.Transaction;
+
+import org.apache.commons.dbcp2.ConcurrentCloseTestSupport.Task;
+import org.apache.commons.dbcp2.managed.LocalXAConnectionFactory;
+import org.apache.commons.dbcp2.managed.ManagedConnection;
+import org.apache.commons.dbcp2.managed.PoolableManagedConnectionFactory;
+import org.apache.commons.dbcp2.managed.TransactionRegistry;
+import org.apache.commons.pool2.BaseObjectPool;
+import org.apache.commons.pool2.impl.GenericObjectPool;
+import org.apache.geronimo.transaction.manager.TransactionManagerImpl;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests ownership of managed delegates when close overlaps a transaction 
callback.
+ */
+class TestConcurrentManagedConnectionClose {
+
+    /**
+     * Failures during delegate inspection or close must not leave the 
delegate attached.
+     */
+    private enum Failure {
+        NONE, IS_CLOSED_SQL, IS_CLOSED_RUNTIME, CLOSE_SQL, CLOSE_RUNTIME
+    }
+
+    /**
+     * Uses a real transaction manager, managed connection factory, and 
single-entry H2 pool.
+     */
+    private static final class Fixture implements AutoCloseable {
+        private final TransactionManagerImpl manager = new 
TransactionManagerImpl();
+        private final LocalXAConnectionFactory factory = new 
LocalXAConnectionFactory(manager, () -> 
DriverManager.getConnection("jdbc:h2:mem:"));
+        private final GenericObjectPool<PoolableConnection> pool;
+
+        /**
+         * Creates a pool that rejects a second borrower instead of waiting 
indefinitely.
+         */
+        Fixture() throws Exception {
+            final PoolableManagedConnectionFactory connectionFactory = new 
PoolableManagedConnectionFactory(factory, null);
+            pool = new GenericObjectPool<>(connectionFactory);
+            connectionFactory.setPool(pool);
+            pool.setMaxTotal(1);
+            pool.setBlockWhenExhausted(false);
+            pool.setMaxWait(Duration.ofSeconds(1));
+        }
+
+        /**
+         * Borrows an ordinary managed handle.
+         */
+        ManagedConnection<PoolableConnection> borrow() throws SQLException {
+            return new ManagedConnection<>(pool, 
factory.getTransactionRegistry(), true);
+        }
+
+        @Override
+        public void close() throws Exception {
+            try {
+                if (manager.getTransaction() != null) {
+                    manager.rollback();
+                }
+            } finally {
+                pool.close();
+            }
+        }
+
+        /**
+         * Resumes the suspended transaction on a worker and runs the real 
completion listeners.
+         */
+        Task complete(final Transaction transaction, final boolean commit) {
+            return new Task(() -> {
+                manager.resume(transaction);
+                if (commit) {
+                    manager.commit();
+                } else {
+                    manager.rollback();
+                }
+            });
+        }
+    }
+
+    /**
+     * Coordinates a single callback with the application closing its logical 
connection.
+     */
+    private static final class Gate {
+        private final Phase phase;
+        private final CountDownLatch entered = new CountDownLatch(1);
+        private final CountDownLatch release = new CountDownLatch(1);
+        private final AtomicBoolean paused = new AtomicBoolean();
+        private volatile Thread callback;
+
+        /**
+         * Selects the callback checkpoint.
+         */
+        Gate(final Phase phase) {
+            this.phase = phase;
+        }
+
+        /**
+         * Pauses only the callback thread and only once.
+         */
+        void pause(final Phase current) {
+            if (phase == current && Thread.currentThread() == callback && 
paused.compareAndSet(false, true)) {
+                entered.countDown();
+                await(release);
+            }
+        }
+    }
+
+    /**
+     * Adds scheduling checkpoints without changing the delegate or 
closed-state values.
+     */
+    private static final class GatedConnection extends 
ManagedConnection<PoolableConnection> {
+        private final Gate gate;
+
+        /**
+         * Borrows and enlists a connection in the current transaction.
+         */
+        GatedConnection(final GenericObjectPool<PoolableConnection> pool, 
final TransactionRegistry registry, final Gate gate) throws SQLException {
+            super(pool, registry, true);
+            this.gate = gate;
+        }
+
+        @Override
+        protected boolean isClosedInternal() {
+            if (gate != null) {
+                gate.pause(Phase.CHECK_CLOSED);
+            }
+            return super.isClosedInternal();
+        }
+
+        @Override
+        protected void transactionComplete() {
+            gate.callback = Thread.currentThread();
+            try {
+                gate.pause(Phase.BEFORE_CALLBACK);
+                super.transactionComplete();
+                gate.pause(Phase.AFTER_CALLBACK);
+            } finally {
+                gate.callback = null;
+            }
+        }
+    }
+
+    /**
+     * Points at which a transaction completion callback may be paused.
+     */
+    private enum Phase {
+        BEFORE_CALLBACK, CHECK_CLOSED, AFTER_CALLBACK
+    }
+
+    /**
+     * Checks pool ownership as well as usability of the next logical 
connection.
+     */
+    private static void assertBorrowed(final Fixture fixture, final Connection 
connection) throws Exception {
+        assertEquals(1, fixture.pool.getNumActive());
+        assertEquals(0, fixture.pool.getNumIdle());
+        assertFalse(connection.isClosed());
+        assertThrows(SQLException.class, fixture::borrow);
+        try (Statement statement = connection.createStatement(); ResultSet 
result = statement.executeQuery("SELECT 42")) {
+            assertTrue(result.next());
+            assertEquals(42, result.getInt(1));
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testClosedDuringTransactionReturnsOnlyOnCompletion(final boolean 
commit) throws Exception {
+        final Gate gate = new Gate(Phase.BEFORE_CALLBACK);
+        try (Fixture fixture = new Fixture()) {
+            fixture.manager.begin();
+            final GatedConnection owner = new GatedConnection(fixture.pool, 
fixture.factory.getTransactionRegistry(), gate);
+            final ManagedConnection<PoolableConnection> shared = 
fixture.borrow();
+            shared.close();
+            owner.close();
+            assertEquals(1, fixture.pool.getNumActive());
+            assertEquals(0, fixture.pool.getNumIdle());
+            gate.release.countDown();
+            try (Task completion = fixture.complete(fixture.manager.suspend(), 
commit)) {
+                completion.awaitSuccess();
+            }
+            assertNull(owner.getDelegate());
+            assertNull(shared.getDelegate());
+            assertEquals(0, fixture.pool.getNumActive());
+            assertEquals(1, fixture.pool.getNumIdle());
+            try (ManagedConnection<PoolableConnection> next = 
fixture.borrow()) {
+                owner.close();
+                shared.close();
+                assertBorrowed(fixture, next);
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(Failure.class)
+    void testCloseDetachesDelegateOnFailure(final Failure failure) throws 
Exception {
+        final CountDownLatch entered = new CountDownLatch(1);
+        final CountDownLatch release = new CountDownLatch(1);
+        final AtomicInteger closes = new AtomicInteger();
+        final Connection delegate = (Connection) 
Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] 
{Connection.class},
+                (proxy, method, args) -> {
+                    if ("isClosed".equals(method.getName())) {
+                        entered.countDown();
+                        await(release);
+                        if (failure == Failure.IS_CLOSED_SQL) {
+                            throw new SQLException("Inspection failed");
+                        }
+                        if (failure == Failure.IS_CLOSED_RUNTIME) {
+                            throw new IllegalStateException("Inspection 
failed");
+                        }
+                        return false;
+                    }
+                    if ("close".equals(method.getName())) {
+                        closes.incrementAndGet();
+                        if (failure == Failure.CLOSE_SQL) {
+                            throw new SQLException("Close failed");
+                        }
+                        if (failure == Failure.CLOSE_RUNTIME) {
+                            throw new IllegalStateException("Close failed");
+                        }
+                        return null;
+                    }
+                    throw new AssertionError("Unexpected call: " + 
method.getName());
+                });
+        final BaseObjectPool<Connection> pool = new 
BaseObjectPool<Connection>() {
+            @Override
+            public Connection borrowObject() {
+                return delegate;
+            }
+
+            @Override
+            public void invalidateObject(final Connection connection) {
+                throw new AssertionError("Unexpected invalidation");
+            }
+
+            @Override
+            public void returnObject(final Connection connection) {
+                throw new AssertionError("Unexpected pool return");
+            }
+        };
+        final ManagedConnection<Connection> connection = new 
ManagedConnection<>(pool, new TransactionRegistry(new 
TransactionManagerImpl()), true);
+        try (Task first = new Task(connection::close)) {
+            await(entered);
+            try (Task second = new Task(connection::close)) {
+                try {
+                    second.awaitBlocked();
+                } finally {
+                    release.countDown();
+                }
+                final Throwable error = first.awaitFailure();
+                if (failure == Failure.IS_CLOSED_RUNTIME || failure == 
Failure.CLOSE_RUNTIME) {
+                    assertInstanceOf(IllegalStateException.class, error);
+                } else if (failure == Failure.CLOSE_SQL) {
+                    assertInstanceOf(SQLException.class, error);
+                } else {
+                    assertNull(error);
+                }
+                second.awaitSuccess();
+            }
+            assertNull(connection.getDelegate());
+            assertTrue(connection.isClosed());
+            connection.close();
+            assertEquals(failure == Failure.IS_CLOSED_RUNTIME ? 0 : 1, 
closes.get());
+        } finally {
+            release.countDown();
+            pool.close();
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testCloseWaitsForCompletionCleanup(final boolean commit) throws 
Exception {
+        final Gate gate = new Gate(Phase.CHECK_CLOSED);
+        try (Fixture fixture = new Fixture()) {
+            fixture.manager.begin();
+            final GatedConnection original = new GatedConnection(fixture.pool, 
fixture.factory.getTransactionRegistry(), gate);
+            final Connection physical = 
original.getInnermostDelegateInternal();
+            try (Task completion = fixture.complete(fixture.manager.suspend(), 
commit)) {
+                await(gate.entered);
+                try (Task close = new Task(original::close)) {
+                    try {
+                        close.awaitBlocked();
+                        assertEquals(1, fixture.pool.getNumActive());
+                    } finally {
+                        gate.release.countDown();
+                    }
+                    completion.awaitSuccess();
+                    close.awaitSuccess();
+                }
+                assertNull(original.getDelegate());
+                assertEquals(1, fixture.pool.getNumIdle());
+                try (ManagedConnection<PoolableConnection> next = 
fixture.borrow()) {
+                    assertSame(physical, next.getInnermostDelegateInternal());
+                    original.close();
+                    assertBorrowed(fixture, next);
+                }
+            } finally {
+                gate.release.countDown();
+                original.close();
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testCompletionAfterCloseDoesNotReturnBorrowedConnection(final boolean 
commit) throws Exception {
+        final Gate gate = new Gate(Phase.BEFORE_CALLBACK);
+        try (Fixture fixture = new Fixture()) {
+            fixture.manager.begin();
+            final GatedConnection original = new GatedConnection(fixture.pool, 
fixture.factory.getTransactionRegistry(), gate);
+            try (Task completion = fixture.complete(fixture.manager.suspend(), 
commit)) {
+                await(gate.entered);
+                // Another handle's completion listener can mark the shared 
context complete before this listener runs.
+                original.getTransactionContext().completeTransaction();
+                original.close();
+                try (ManagedConnection<PoolableConnection> next = 
fixture.borrow()) {
+                    gate.release.countDown();
+                    completion.awaitSuccess();
+                    assertNull(original.getDelegate());
+                    assertBorrowed(fixture, next);
+                    original.close();
+                    assertBorrowed(fixture, next);
+                }
+            } finally {
+                gate.release.countDown();
+                original.close();
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testSharedCloseDoesNotReturnOwnersConnection(final boolean commit) 
throws Exception {
+        final Gate gate = new Gate(Phase.AFTER_CALLBACK);
+        try (Fixture fixture = new Fixture()) {
+            fixture.manager.begin();
+            final GatedConnection owner = new GatedConnection(fixture.pool, 
fixture.factory.getTransactionRegistry(), gate);
+            final ManagedConnection<PoolableConnection> shared = 
fixture.borrow();
+            assertSame(owner.getDelegate(), shared.getDelegate());
+            try (Task completion = fixture.complete(fixture.manager.suspend(), 
commit)) {
+                await(gate.entered);
+                shared.close();
+                assertNull(shared.getDelegate());
+                assertBorrowed(fixture, owner);
+                gate.release.countDown();
+                completion.awaitSuccess();
+                assertBorrowed(fixture, owner);
+                owner.close();
+                assertEquals(0, fixture.pool.getNumActive());
+                assertEquals(1, fixture.pool.getNumIdle());
+            } finally {
+                gate.release.countDown();
+                shared.close();
+                owner.close();
+            }
+        }
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/dbcp2/TestConcurrentStatementClose.java 
b/src/test/java/org/apache/commons/dbcp2/TestConcurrentStatementClose.java
new file mode 100644
index 00000000..94eac765
--- /dev/null
+++ b/src/test/java/org/apache/commons/dbcp2/TestConcurrentStatementClose.java
@@ -0,0 +1,234 @@
+/*
+ * 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.apache.commons.dbcp2.ConcurrentCloseTestSupport.await;
+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.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Proxy;
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Stream;
+
+import org.apache.commons.dbcp2.ConcurrentCloseTestSupport.Task;
+import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+/**
+ * Tests concurrent explicit and connection-driven statement cleanup.
+ */
+class TestConcurrentStatementClose {
+
+    /**
+     * Cleanup failures must still leave the wrapper closed and its delegate 
detached.
+     */
+    private enum Failure {
+        NONE, RESULT_SET_SQL, RESULT_SET_RUNTIME, DELEGATE_SQL, 
DELEGATE_RUNTIME
+    }
+
+    /**
+     * JDBC statement wrapper types that inherit the common close 
implementation.
+     */
+    private enum Kind {
+        STATEMENT, PREPARED, CALLABLE
+    }
+
+    /**
+     * Combines each inherited implementation with every cleanup failure.
+     */
+    static Stream<Arguments> cleanupCases() {
+        return Stream.of(Kind.values()).flatMap(kind -> 
Stream.of(Failure.values()).map(failure -> Arguments.of(kind, failure)));
+    }
+
+    /**
+     * Combines both pooled statement types with both closing entry points and 
return outcomes.
+     */
+    static Stream<Arguments> poolingCases() {
+        return Stream.of(false, true).flatMap(callable -> Stream.of(false, 
true)
+                .flatMap(connectionClose -> Stream.of(false, true).map(fail -> 
Arguments.of(callable, connectionClose, fail))));
+    }
+
+    /**
+     * Prepares a statement that uses a single reusable pool entry.
+     */
+    private static PreparedStatement prepare(final Connection connection, 
final boolean callable) throws SQLException {
+        return callable ? connection.prepareCall("CALL ABS(?)") : 
connection.prepareStatement("SELECT ?");
+    }
+
+    @ParameterizedTest
+    @MethodSource("cleanupCases")
+    void testConcurrentCleanup(final Kind kind, final Failure failure) throws 
Exception {
+        final CountDownLatch entered = new CountDownLatch(1);
+        final CountDownLatch release = new CountDownLatch(1);
+        final AtomicInteger statementCloses = new AtomicInteger();
+        final AtomicInteger resultSetCloses = new AtomicInteger();
+        final CallableStatement delegate = (CallableStatement) 
Proxy.newProxyInstance(getClass().getClassLoader(),
+                new Class<?>[] {CallableStatement.class}, (proxy, method, 
args) -> {
+                    if ("close".equals(method.getName())) {
+                        statementCloses.incrementAndGet();
+                        if (failure == Failure.DELEGATE_SQL) {
+                            throw new SQLException("Statement close failed");
+                        }
+                        if (failure == Failure.DELEGATE_RUNTIME) {
+                            throw new IllegalStateException("Statement close 
failed");
+                        }
+                        return null;
+                    }
+                    throw new AssertionError("Unexpected call: " + 
method.getName());
+                });
+        try (DelegatingConnection<Connection> connection = new 
DelegatingConnection<>(new TesterConnection("test", "test"))) {
+            final DelegatingStatement statement;
+            switch (kind) {
+            case PREPARED:
+                statement = new DelegatingPreparedStatement(connection, 
delegate);
+                break;
+            case CALLABLE:
+                statement = new DelegatingCallableStatement(connection, 
delegate);
+                break;
+            default:
+                statement = new DelegatingStatement(connection, delegate);
+                break;
+            }
+            final ResultSet resultSet = (ResultSet) 
Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] 
{ResultSet.class},
+                    (proxy, method, args) -> {
+                        if ("close".equals(method.getName())) {
+                            resultSetCloses.incrementAndGet();
+                            entered.countDown();
+                            await(release);
+                            if (failure == Failure.RESULT_SET_SQL) {
+                                throw new SQLException("Result set close 
failed");
+                            }
+                            if (failure == Failure.RESULT_SET_RUNTIME) {
+                                throw new IllegalStateException("Result set 
close failed");
+                            }
+                            return null;
+                        }
+                        throw new AssertionError("Unexpected call: " + 
method.getName());
+                    });
+            // Retain the wrapper because the trace uses weak references.
+            final ResultSet traced = 
DelegatingResultSet.wrapResultSet(statement, resultSet);
+            try (Task first = new Task(statement::close)) {
+                await(entered);
+                try (Task second = new Task(statement::close)) {
+                    try {
+                        second.awaitBlocked();
+                        assertEquals(1, resultSetCloses.get());
+                    } finally {
+                        release.countDown();
+                    }
+                    if (failure == Failure.NONE) {
+                        first.awaitSuccess();
+                    } else {
+                        assertInstanceOf(SQLExceptionList.class, 
first.awaitFailure());
+                    }
+                    second.awaitSuccess();
+                }
+                assertEquals(1, statementCloses.get());
+                assertEquals(1, resultSetCloses.get());
+                assertTrue(statement.isClosed());
+                assertNull(statement.getDelegateInternal());
+                assertTrue(statement.getTrace().isEmpty());
+                assertTrue(connection.getTrace().isEmpty());
+                statement.close();
+                assertEquals(1, statementCloses.get());
+                assertNull(traced.getStatement());
+            } finally {
+                release.countDown();
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("poolingCases")
+    void testConcurrentCloseDoesNotReturnBorrowedStatement(final boolean 
callable, final boolean connectionClose, final boolean failAfterReturn)
+            throws Exception {
+        final CountDownLatch returned = new CountDownLatch(1);
+        final CountDownLatch release = new CountDownLatch(1);
+        final AtomicInteger returns = new AtomicInteger();
+        try (PoolingConnection pooling = new 
PoolingConnection(DriverManager.getConnection("jdbc:h2:mem:"))) {
+            final GenericKeyedObjectPool<PStmtKey, 
DelegatingPreparedStatement> pool = new GenericKeyedObjectPool<PStmtKey, 
DelegatingPreparedStatement>(pooling) {
+                @Override
+                public void returnObject(final PStmtKey key, final 
DelegatingPreparedStatement statement) {
+                    super.returnObject(key, statement);
+                    if (returns.incrementAndGet() == 1) {
+                        returned.countDown();
+                        await(release);
+                        if (failAfterReturn) {
+                            throw new IllegalStateException("Return completed 
but close failed");
+                        }
+                    }
+                }
+            };
+            pooling.setStatementPool(pool);
+            pool.setMaxTotal(1);
+            pool.setMaxTotalPerKey(1);
+            pool.setBlockWhenExhausted(false);
+            // A separate wrapper lets us borrow again while the original 
connection wrapper is still closing.
+            final DelegatingConnection<Connection> originalConnection = new 
DelegatingConnection<>(pooling);
+            final DelegatingConnection<Connection> nextConnection = new 
DelegatingConnection<>(pooling);
+            final PreparedStatement original = prepare(originalConnection, 
callable);
+            try (Task first = new Task(connectionClose ? 
originalConnection::close : original::close)) {
+                await(returned);
+                try (PreparedStatement next = prepare(nextConnection, 
callable); Task second = new Task(original::close)) {
+                    try {
+                        second.awaitBlocked();
+                        assertEquals(1, returns.get());
+                        assertEquals(1, pool.getNumActive());
+                        assertEquals(0, pool.getNumIdle());
+                    } finally {
+                        release.countDown();
+                    }
+                    if (failAfterReturn) {
+                        assertInstanceOf(SQLException.class, 
first.awaitFailure());
+                    } else {
+                        first.awaitSuccess();
+                    }
+                    second.awaitSuccess();
+                    // Closing a connection also closes its statement pool; 
use the assertions above for that path.
+                    if (!connectionClose) {
+                        assertEquals(1, pool.getNumActive());
+                        assertEquals(0, pool.getNumIdle());
+                        assertFalse(next.isClosed());
+                        assertThrows(SQLException.class, () -> 
prepare(nextConnection, callable));
+                        next.setInt(1, 42);
+                        try (ResultSet result = next.executeQuery()) {
+                            assertTrue(result.next());
+                            assertEquals(42, result.getInt(1));
+                        }
+                    }
+                    original.close();
+                    assertEquals(1, returns.get());
+                }
+            } finally {
+                release.countDown();
+            }
+        }
+    }
+}
diff --git a/src/test/java/org/apache/commons/dbcp2/TestDataSourceClose.java 
b/src/test/java/org/apache/commons/dbcp2/TestDataSourceClose.java
new file mode 100644
index 00000000..94a214b7
--- /dev/null
+++ b/src/test/java/org/apache/commons/dbcp2/TestDataSourceClose.java
@@ -0,0 +1,487 @@
+/*
+ * 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.apache.commons.dbcp2.ConcurrentCloseTestSupport.await;
+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.assertNull;
+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 java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.time.Duration;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Stream;
+
+import javax.naming.spi.ObjectFactory;
+import javax.sql.PooledConnection;
+
+import org.apache.commons.dbcp2.ConcurrentCloseTestSupport.Task;
+import org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS;
+import org.apache.commons.dbcp2.datasources.InstanceKeyDataSource;
+import org.apache.commons.dbcp2.datasources.PerUserPoolDataSource;
+import org.apache.commons.dbcp2.datasources.PerUserPoolDataSourceFactory;
+import org.apache.commons.dbcp2.datasources.SharedPoolDataSource;
+import org.apache.commons.dbcp2.datasources.SharedPoolDataSourceFactory;
+import org.apache.commons.lang3.SerializationUtils;
+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 terminal data-source shutdown, including initialization and 
password-recovery races.
+ */
+class TestDataSourceClose {
+
+    /**
+     * Data-source lifecycle states in which shutdown must prevent new 
requests.
+     */
+    private enum State {
+        UNCONFIGURED, CONFIGURED, INITIALIZED
+    }
+
+    /**
+     * Records physical connections and optionally pauses or fails an 
individual creation attempt.
+     */
+    private static final class TrackingCPDS extends DriverAdapterCPDS {
+        private final AtomicInteger attempts = new AtomicInteger();
+        private final List<PooledConnection> connections = new 
CopyOnWriteArrayList<>();
+        private final CountDownLatch entered = new CountDownLatch(1);
+        private final CountDownLatch release = new CountDownLatch(1);
+        private volatile int pauseAt;
+        private volatile int failAt;
+
+        /**
+         * Uses independent in-memory databases so tests do not share 
credentials or state.
+         */
+        TrackingCPDS() throws ClassNotFoundException {
+            setDriver("org.h2.Driver");
+            setUrl("jdbc:h2:mem:");
+        }
+
+        /**
+         * Asserts physical shutdown, including the connection used to 
validate the provider.
+         */
+        void assertClosed() {
+            assertFalse(connections.isEmpty());
+            connections.forEach(connection -> assertThrows(SQLException.class, 
connection::getConnection));
+        }
+
+        @Override
+        public PooledConnection getPooledConnection(final String user, final 
String password) throws SQLException {
+            final int attempt = attempts.incrementAndGet();
+            if (attempt == pauseAt) {
+                entered.countDown();
+                await(release);
+            }
+            if (attempt == failAt) {
+                throw new SQLException("Simulated creation failure during 
password change");
+            }
+            final PooledConnection connection = 
super.getPooledConnection(user, password);
+            connections.add(connection);
+            return connection;
+        }
+    }
+
+    /**
+     * Checks that shutdown cannot be undone through either borrowing overload.
+     */
+    private static void assertRejectsBorrowing(final InstanceKeyDataSource 
dataSource, final TrackingCPDS cpds) {
+        final int attempts = cpds.attempts.get();
+        assertThrows(SQLException.class, dataSource::getConnection);
+        assertThrows(SQLException.class, () -> dataSource.getConnection("sa", 
""));
+        assertEquals(attempts, cpds.attempts.get(), "A closed data source 
contacted its provider");
+    }
+
+    /**
+     * Combines each data-source implementation, lifecycle state, and 
getConnection overload.
+     */
+    static Stream<Arguments> closeCases() {
+        return Stream.of(false, true).flatMap(shared -> 
Stream.of(State.values())
+                .flatMap(state -> Stream.of(false, true).map(credentials -> 
Arguments.of(shared, state, credentials))));
+    }
+
+    /**
+     * Configures a small pool without changing the close behavior under test.
+     */
+    private static void configure(final InstanceKeyDataSource dataSource, 
final TrackingCPDS cpds) {
+        dataSource.setConnectionPoolDataSource(cpds);
+        dataSource.setDefaultMaxTotal(1);
+        dataSource.setDefaultMaxWait(Duration.ofSeconds(5));
+    }
+
+    /**
+     * Creates an unconfigured data source.
+     */
+    private static InstanceKeyDataSource create(final boolean shared) {
+        return shared ? new SharedPoolDataSource() : new 
PerUserPoolDataSource();
+    }
+
+    /**
+     * Combines both implementations with initialization and post-registration 
physical creation.
+     */
+    static Stream<Arguments> creationCases() {
+        return Stream.of(false, true).flatMap(shared -> Stream.of(1, 
2).map(attempt -> Arguments.of(shared, attempt)));
+    }
+
+    /**
+     * Accepts either outcome of an in-flight borrow, but returns any acquired 
connection before checking shutdown.
+     */
+    private static void finishBorrow(final Task borrower, final 
AtomicReference<Connection> connection) throws Exception {
+        final Throwable failure = borrower.awaitFailure();
+        if (failure != null) {
+            assertInstanceOf(SQLException.class, failure);
+        } else {
+            assertNotNull(connection.get());
+            connection.get().close();
+        }
+    }
+
+    /**
+     * Combines shared-pool shutdown through either instance, before or after 
initial pool creation.
+     */
+    static Stream<Arguments> serializationCases() {
+        return Stream.of(false, true).flatMap(shared -> Stream.of(false, true)
+                .flatMap(initialized -> Stream.of(false, true).map(closeCopy 
-> Arguments.of(shared, initialized, closeCopy))));
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testBorrowWaitingToInitializeRechecksClosedState(final boolean 
shared) throws Exception {
+        final TrackingCPDS cpds = new TrackingCPDS();
+        try (InstanceKeyDataSource dataSource = create(shared)) {
+            configure(dataSource, cpds);
+            Task borrower = null;
+            try {
+                synchronized (dataSource) {
+                    borrower = new Task(() -> 
dataSource.getConnection().close());
+                    borrower.awaitBlocked();
+                    dataSource.close();
+                }
+                assertInstanceOf(SQLException.class, borrower.awaitFailure());
+            } finally {
+                if (borrower != null) {
+                    borrower.close();
+                }
+            }
+            assertEquals(0, cpds.attempts.get());
+        }
+    }
+
+    @Test
+    void testClearDoesNotCloseDataSource() throws Exception {
+        final TrackingCPDS cpds = new TrackingCPDS();
+        try (PerUserPoolDataSource dataSource = new PerUserPoolDataSource()) {
+            configure(dataSource, cpds);
+            dataSource.getConnection().close();
+            dataSource.clear();
+            cpds.assertClosed();
+            try (Connection connection = dataSource.getConnection()) {
+                assertTrue(connection.isValid(1));
+            }
+        }
+        cpds.assertClosed();
+    }
+
+    @Test
+    void testCloseAllUserPools() throws Exception {
+        final TrackingCPDS cpds = new TrackingCPDS();
+        try (PerUserPoolDataSource dataSource = new PerUserPoolDataSource()) {
+            configure(dataSource, cpds);
+            dataSource.getConnection("first", "").close();
+            dataSource.getConnection("second", "").close();
+            try (Connection active = dataSource.getConnection("third", "")) {
+                dataSource.close();
+                assertTrue(active.isValid(1));
+                assertThrows(SQLException.class, () -> 
dataSource.getConnection("first", ""));
+                assertThrows(SQLException.class, () -> 
dataSource.getConnection("fourth", ""));
+            }
+            cpds.assertClosed();
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("serializationCases")
+    void testClosedPoolIsNotRecreatedThroughDeserializedDataSource(final 
boolean shared, final boolean initialized, final boolean closeCopy) throws 
Exception {
+        final DriverAdapterCPDS cpds = new DriverAdapterCPDS();
+        cpds.setDriver("org.h2.Driver");
+        cpds.setUrl("jdbc:h2:mem:");
+        try (InstanceKeyDataSource dataSource = create(shared)) {
+            dataSource.setConnectionPoolDataSource(cpds);
+            if (initialized) {
+                dataSource.getConnection().close();
+            }
+            try (InstanceKeyDataSource copy = 
SerializationUtils.clone(dataSource)) {
+                copy.getConnection().close();
+                assertEquals(1, shared ? ((SharedPoolDataSource) 
dataSource).getNumIdle() : ((PerUserPoolDataSource) dataSource).getNumIdle());
+                if (closeCopy) {
+                    copy.close();
+                } else {
+                    dataSource.close();
+                }
+                assertEquals(0, shared ? ((SharedPoolDataSource) 
dataSource).getNumIdle() : ((PerUserPoolDataSource) dataSource).getNumIdle());
+                final ObjectFactory factory = shared ? new 
SharedPoolDataSourceFactory() : new PerUserPoolDataSourceFactory();
+                
assertNull(factory.getObjectInstance(dataSource.getReference(), null, null, 
null));
+                assertThrows(SQLException.class, dataSource::getConnection);
+                assertThrows(SQLException.class, copy::getConnection);
+                assertThrows(SQLException.class, () -> 
dataSource.getConnection("new-user", ""));
+                assertThrows(SQLException.class, () -> 
copy.getConnection("new-user", ""));
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("creationCases")
+    void testCloseDuringConnectionCreation(final boolean shared, final int 
pauseAt) throws Exception {
+        final TrackingCPDS cpds = new TrackingCPDS();
+        cpds.pauseAt = pauseAt;
+        try (InstanceKeyDataSource dataSource = create(shared)) {
+            configure(dataSource, cpds);
+            final AtomicReference<Connection> connection = new 
AtomicReference<>();
+            try (Task borrower = new Task(() -> 
connection.set(dataSource.getConnection()))) {
+                await(cpds.entered);
+                try (Task closer = new Task(dataSource::close)) {
+                    try {
+                        if (pauseAt == 1) {
+                            // Initialization owns the data-source monitor 
until the new pool is published.
+                            closer.awaitBlocked();
+                        } else {
+                            // Ordinary physical connection creation must not 
prevent shutdown of a published pool.
+                            closer.awaitSuccess();
+                        }
+                    } finally {
+                        cpds.release.countDown();
+                    }
+                    finishBorrow(borrower, connection);
+                    closer.awaitSuccess();
+                }
+                cpds.assertClosed();
+                assertRejectsBorrowing(dataSource, cpds);
+            } finally {
+                cpds.release.countDown();
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = {4, 5})
+    void testCloseDuringPasswordRecovery(final int pauseAt) throws Exception {
+        final TrackingCPDS cpds = new TrackingCPDS();
+        try (PerUserPoolDataSource dataSource = new PerUserPoolDataSource()) {
+            configure(dataSource, cpds);
+            dataSource.setDefaultMaxIdle(0);
+            dataSource.getConnection().close();
+            assertEquals(2, cpds.attempts.get());
+            cpds.failAt = 3;
+            cpds.pauseAt = pauseAt;
+            final AtomicReference<Connection> connection = new 
AtomicReference<>();
+            try (Task borrower = new Task(() -> 
connection.set(dataSource.getConnection()))) {
+                await(cpds.entered);
+                try (Task closer = new Task(dataSource::close)) {
+                    try {
+                        if (pauseAt == 4) {
+                            // The recovery probe runs outside the 
initialization monitor.
+                            closer.awaitSuccess();
+                        } else {
+                            // Replacement pool registration must be 
coordinated with shutdown too.
+                            closer.awaitBlocked();
+                        }
+                    } finally {
+                        cpds.release.countDown();
+                    }
+                    finishBorrow(borrower, connection);
+                    closer.awaitSuccess();
+                }
+                cpds.assertClosed();
+                assertRejectsBorrowing(dataSource, cpds);
+                if (pauseAt == 4) {
+                    assertEquals(4, cpds.attempts.get(), "Shutdown allowed 
replacement pool registration");
+                }
+            } finally {
+                cpds.release.countDown();
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("closeCases")
+    void testCloseIsTerminal(final boolean shared, final State state, final 
boolean credentials) throws Exception {
+        final TrackingCPDS cpds = new TrackingCPDS();
+        try (InstanceKeyDataSource dataSource = create(shared)) {
+            if (state != State.UNCONFIGURED) {
+                configure(dataSource, cpds);
+            }
+            if (state == State.INITIALIZED) {
+                try (Connection connection = credentials ? 
dataSource.getConnection("sa", "") : dataSource.getConnection()) {
+                    assertFalse(connection.isClosed());
+                }
+            }
+            dataSource.close();
+            dataSource.close();
+            assertRejectsBorrowing(dataSource, cpds);
+            if (state == State.INITIALIZED) {
+                cpds.assertClosed();
+            } else {
+                assertEquals(0, cpds.attempts.get());
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testCloseWakesWaitersAndPreservesBorrowedConnection(final boolean 
shared) throws Exception {
+        final TrackingCPDS cpds = new TrackingCPDS();
+        try (InstanceKeyDataSource dataSource = create(shared)) {
+            configure(dataSource, cpds);
+            dataSource.setDefaultMaxWait(Duration.ofMillis(-1));
+            try (Connection connection = dataSource.getConnection(); Task 
waiting = new Task(() -> {
+                try (Connection unexpected = dataSource.getConnection()) {
+                    throw new AssertionError("Unexpected second connection: " 
+ unexpected);
+                }
+            })) {
+                waiting.awaitBlocked();
+                dataSource.close();
+                assertInstanceOf(SQLException.class, waiting.awaitFailure());
+                assertFalse(connection.isClosed());
+                assertTrue(connection.isValid(1));
+                assertRejectsBorrowing(dataSource, cpds);
+            }
+            cpds.assertClosed();
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testDeserializedDataSourceSharesInitializationMonitor(final boolean 
shared) throws Exception {
+        final DriverAdapterCPDS cpds = new DriverAdapterCPDS();
+        cpds.setDriver("org.h2.Driver");
+        cpds.setUrl("jdbc:h2:mem:");
+        try (InstanceKeyDataSource dataSource = create(shared)) {
+            dataSource.setConnectionPoolDataSource(cpds);
+            try (InstanceKeyDataSource copy = 
SerializationUtils.clone(dataSource)) {
+                Task borrower = null;
+                try {
+                    synchronized (dataSource) {
+                        borrower = new Task(() -> 
copy.getConnection().close());
+                        borrower.awaitBlocked();
+                        copy.close();
+                    }
+                    assertInstanceOf(SQLException.class, 
borrower.awaitFailure());
+                    assertThrows(SQLException.class, 
dataSource::getConnection);
+                } finally {
+                    if (borrower != null) {
+                        borrower.close();
+                    }
+                }
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testPasswordChangeThroughDeserializedDataSource(final boolean shared) 
throws Exception {
+        final String url = "jdbc:h2:mem:" + UUID.randomUUID();
+        final DriverAdapterCPDS cpds = new DriverAdapterCPDS();
+        cpds.setDriver("org.h2.Driver");
+        cpds.setUrl(url);
+        // Keep the database alive while password recovery replaces its pooled 
connections.
+        try (Connection anchor = DriverManager.getConnection(url, "sa", 
"before"); InstanceKeyDataSource dataSource = create(shared)) {
+            dataSource.setConnectionPoolDataSource(cpds);
+            dataSource.setDefaultMaxTotal(1);
+            dataSource.setDefaultBlockWhenExhausted(false);
+            dataSource.getConnection("sa", "before").close();
+            try (InstanceKeyDataSource copy = 
SerializationUtils.clone(dataSource)) {
+                try (Statement statement = anchor.createStatement()) {
+                    statement.execute("ALTER USER SA SET PASSWORD 'after'");
+                }
+                try (Connection connection = copy.getConnection("sa", 
"after")) {
+                    assertTrue(connection.isValid(1));
+                    assertEquals(1, shared ? ((SharedPoolDataSource) 
dataSource).getNumActive() : ((PerUserPoolDataSource) 
dataSource).getNumActive("sa"));
+                    assertEquals(1, shared ? ((SharedPoolDataSource) 
copy).getNumActive() : ((PerUserPoolDataSource) copy).getNumActive("sa"));
+                }
+                try (Connection connection = dataSource.getConnection("sa", 
"after")) {
+                    assertTrue(connection.isValid(1));
+                }
+                assertThrows(SQLException.class, () -> 
copy.getConnection("sa", "before"));
+                copy.close();
+                assertThrows(SQLException.class, () -> 
dataSource.getConnection("sa", "after"));
+            }
+        }
+    }
+
+    @Test
+    void testPasswordRecoveryWhileOpen() throws Exception {
+        final TrackingCPDS cpds = new TrackingCPDS();
+        try (PerUserPoolDataSource dataSource = new PerUserPoolDataSource()) {
+            configure(dataSource, cpds);
+            dataSource.setDefaultMaxIdle(0);
+            dataSource.getConnection().close();
+            cpds.failAt = 3;
+            try (Connection connection = dataSource.getConnection()) {
+                assertTrue(connection.isValid(1));
+                assertEquals(6, cpds.attempts.get());
+            }
+        }
+        cpds.assertClosed();
+    }
+
+    @ParameterizedTest
+    @MethodSource("serializationCases")
+    void testRepeatedClosePreservesNewRegistration(final boolean shared, final 
boolean initialized, final boolean closeCopy) throws Exception {
+        final DriverAdapterCPDS cpds = new DriverAdapterCPDS();
+        cpds.setDriver("org.h2.Driver");
+        cpds.setUrl("jdbc:h2:mem:");
+        final ObjectFactory factory = shared ? new 
SharedPoolDataSourceFactory() : new PerUserPoolDataSourceFactory();
+        try (InstanceKeyDataSource first = create(shared)) {
+            first.setConnectionPoolDataSource(cpds);
+            if (initialized) {
+                first.getConnection().close();
+            }
+            try (InstanceKeyDataSource copy = SerializationUtils.clone(first)) 
{
+                first.close();
+                try (InstanceKeyDataSource next = create(shared)) {
+                    next.setConnectionPoolDataSource(cpds);
+                    
assertEquals(first.getReference().get("instanceKey").getContent(), 
next.getReference().get("instanceKey").getContent());
+                    assertSame(next, 
factory.getObjectInstance(next.getReference(), null, null, null));
+                    if (closeCopy) {
+                        copy.close();
+                    } else {
+                        first.close();
+                    }
+                    assertSame(next, 
factory.getObjectInstance(next.getReference(), null, null, null));
+                    try (Connection connection = next.getConnection()) {
+                        assertTrue(connection.isValid(1));
+                    }
+                }
+            }
+        }
+    }
+}

Reply via email to