vzhn opened a new pull request, #564:
URL: https://github.com/apache/commons-dbcp/pull/564

   Closing a pooled `Connection` from two threads at the same time can return 
the underlying `PoolableConnection` to the pool twice. If another thread 
borrows the connection between the two returns, the second return puts it back 
in the pool while that thread still holds it, and the next `getConnection()` 
gets the same physical connection. Borrowing it activates it again, so both 
handles work: two users share one database session. One sees the other's 
uncommitted data, and one user's `rollback()` discards the other's work while 
the other's `commit()` returns normally.
   
   The `java.sql.Connection.close()` Javadoc says: "Calling the method `close` 
on a `Connection` object that is already closed is a no-op." Here the second 
call is not a no-op: it closes and returns the connection again after another 
user has borrowed it. The API also expects a connection to be terminated from a 
thread other than the one using it: `Connection.abort()` "Insures that any 
thread that is currently accessing the connection will either progress to 
completion or throw an `SQLException`." The current JDBC specification does not 
require `Connection` objects to be thread-safe (the JDBC 1.2 guide did, in 
section 9.2), so the point here is not a spec violation by concurrent calls as 
such, but that the pool gives one physical connection to two users.
   
   There is no JIRA ticket for this yet.
   
   ### Cause
   
   `PoolGuardConnectionWrapper.close()` calls `DelegatingConnection.close()`, 
which is a check-then-act:
   
   ```java
   public void close() throws SQLException {
       if (!closed) {           // both threads can pass this check
           closeInternal();     // ... and both close the PoolableConnection
       }
   }
   ```
   
   `PoolableConnection.close()` is atomic (DBCP-49), but it checks its own 
closed flag, which is cleared again when the connection is borrowed:
   
   1. Two threads (say, a request and a timeout watchdog) call `close()` on the 
same handle; both pass `if (!closed)`.
   2. The first closes the `PoolableConnection`; it is returned, and a waiting 
thread (Alice) borrows it.
   3. The second closes the same `PoolableConnection` again. It is open, so 
`pool.returnObject()` returns it while Alice holds it.
   4. The next `getConnection()` (Bob) borrows it. Alice's and Bob's handles 
now wrap the same `PoolableConnection`.
   
   A sequential second `close()` is a no-op, as the JDBC contract requires; 
only overlapping calls get through.
   
   ### Change
   
   `PoolGuardConnectionWrapper.close()` now lets only the first call through, 
with an `AtomicBoolean`. Later calls return immediately, as a sequential second 
`close()` already does.
   
   ### Test
   
   `TestPoolingDataSource.testConcurrentCloseDoesNotReturnBorrowedConnection`: 
pool size 1; two threads close the same connection while a third borrows; then 
the pool must count one active and no idle connection. Without the change it 
fails within the first few hundred rounds (seen at round 13, 62, 114, 192 and 
231 in five runs; the test runs 500). With the change it passed 8 runs of 1,000 
rounds. The test raises `maxWait` to 5 s: with the default 100 ms, a slow round 
occasionally timed out the borrower (2 of 5 runs of 1,000 rounds), unrelated to 
this change.
   
   ### Impact, with H2
   
   The program below uses only the public API, pool size 1 and an H2 in-memory 
database. With 2.14.0 and with master it reproduced in 4 of 4 runs (at attempt 
14, 30, 34 and 15; 6 to 11 s each):
   
   ```
   Attempt 14: Bob got a connection although Alice holds the only one.
     Bob and Alice share one database connection: true
     Bob sees Alice's unsaved payment: true
     Alice's commit() succeeded. Alice's payments in the table: 0
   ```
   
   With this change it found nothing in 1,000 attempts.
   
   <details><summary>LostPayment.java</summary>
   
   ```java
   import java.sql.Connection;
   import java.sql.ResultSet;
   import java.sql.SQLException;
   import java.sql.Statement;
   import java.time.Duration;
   import java.util.concurrent.CyclicBarrier;
   
   import org.apache.commons.dbcp2.BasicDataSource;
   
   /**
    * A request finishes and closes its connection. At the same moment a 
timeout watchdog closes
    * the same connection too. Meanwhile Alice's request is waiting for a 
connection.
    *
    * Alice gets the connection and starts saving a payment. Then Bob's request 
asks for a
    * connection. The pool has only one, and Alice is using it, so Bob should 
have to wait.
    * Sometimes he doesn't: the two closes put the connection back into the 
pool twice, and Bob
    * gets Alice's connection. Bob's request fails and rolls back, which also 
rolls back Alice's
    * payment. Alice's commit() succeeds anyway, and her payment is gone.
    */
   public class LostPayment {
   
       public static void main(String[] args) throws Exception {
           try (BasicDataSource pool = new BasicDataSource()) {
               pool.setUrl("jdbc:h2:mem:shop;DB_CLOSE_DELAY=-1");
               pool.setMaxTotal(1);                              // one 
connection, to make it easy to see
               pool.setMaxWait(Duration.ofMillis(250));
               pool.setAccessToUnderlyingConnectionAllowed(true); // only to 
check below that it is the same connection
   
               try (Connection c = pool.getConnection(); Statement s = 
c.createStatement()) {
                   s.execute("CREATE TABLE payments(customer VARCHAR(20), 
amount INT)");
               }
   
               // The race needs the right timing, so try a few times.
               for (int attempt = 1; attempt <= 1000; attempt++) {
                   Connection requestConnection = pool.getConnection();
                   CyclicBarrier start = new CyclicBarrier(3);
                   Connection[] alicesConnection = new Connection[1];
   
                   Thread request  = run(start, () -> 
closeQuietly(requestConnection));   // the request is done
                   Thread watchdog = run(start, () -> 
closeQuietly(requestConnection));   // the timeout fires at the same time
                   Thread alice    = run(start, () -> alicesConnection[0] = 
getQuietly(pool));
                   request.join(); watchdog.join(); alice.join();
   
                   Connection alices = alicesConnection[0];
                   if (alices == null) {
                       continue;
                   }
   
                   // Alice holds the only connection, so Bob should time out 
here.
                   Connection bobs = getQuietly(pool);
                   if (bobs == null) {
                       alices.close();
                       continue;
                   }
   
                   try {
                       alices.setAutoCommit(false);
                       insertPayment(alices, "alice", 100);
                   } catch (SQLException e) {
                       // the connection was closed under Alice instead; try 
again
                       closeQuietly(bobs);
                       closeQuietly(alices);
                       continue;
                   }
   
                   System.out.println("Attempt " + attempt + ": Bob got a 
connection although Alice holds the only one.");
                   System.out.println("  Bob and Alice share one database 
connection: " + sameConnection(alices, bobs));
                   System.out.println("  Bob sees Alice's unsaved payment: " + 
(countPayments(bobs, "alice") == 1));
   
                   bobs.setAutoCommit(false);
                   insertPayment(bobs, "bob", 50);
                   bobs.rollback();                               // Bob's 
request fails and rolls back
                   alices.commit();                               // Alice's 
request commits; no error
                   System.out.println("  Alice's commit() succeeded. Alice's 
payments in the table: " + countPayments(alices, "alice"));
                   return;
               }
               System.out.println("Not reproduced in 1000 attempts.");
           }
       }
   
       static void insertPayment(Connection c, String customer, int amount) 
throws SQLException {
           try (Statement s = c.createStatement()) {
               s.executeUpdate("INSERT INTO payments VALUES ('" + customer + 
"', " + amount + ")");
           }
       }
   
       static int countPayments(Connection c, String customer) throws 
SQLException {
           try (Statement s = c.createStatement();
                ResultSet r = s.executeQuery("SELECT COUNT(*) FROM payments 
WHERE customer = '" + customer + "'")) {
               r.next();
               return r.getInt(1);
           }
       }
   
       static boolean sameConnection(Connection a, Connection b) throws 
SQLException {
           return a.unwrap(org.h2.jdbc.JdbcConnection.class) == 
b.unwrap(org.h2.jdbc.JdbcConnection.class);
       }
   
       static Thread run(CyclicBarrier start, Runnable work) {
           Thread t = new Thread(() -> {
               try {
                   start.await();                                 // let all 
three threads start together
               } catch (Exception e) {
                   throw new RuntimeException(e);
               }
               work.run();
           });
           t.start();
           return t;
       }
   
       static void closeQuietly(Connection c) {
           try { c.close(); } catch (SQLException ignored) { }
       }
   
       static Connection getQuietly(BasicDataSource pool) {
           try { return pool.getConnection(); } catch (SQLException e) { return 
null; }
       }
   }
   ```
   </details>
   
   `PoolingDriver` and `PerUserPoolDataSource` close pooled connections through 
other wrappers; I only tested `BasicDataSource`/`PoolingDataSource`. The same 
pattern was reported for HikariCP (brettwooldridge/HikariCP#2441) and Agroal 
(agroal/agroal#229).
   
   ---
   
   - [x] Read the [contribution guidelines](CONTRIBUTING.md) for this project.
   - [x] Read the [ASF Generative Tooling 
Guidance](https://www.apache.org/legal/generative-tooling.html) if you use 
Artificial Intelligence (AI).
   - [x] I used AI to create any part of, or all of, this pull request. Which 
AI tool was used to create this pull request, and to what extent did it 
contribute? The problem was found during a study of connection pools for this 
class of bug, which started with an in-development model checker for Java (it 
led to the HikariCP report above); in DBCP it showed up in a stress test 
written for that study. Claude Code (Claude Opus 5.5) wrote the reproducer, the 
test, the fix and this description, and ran the checks described above. The 
commit carries a `Generated-by:` trailer.
   - [x] Run a successful build using the default 
[Maven](https://maven.apache.org/) goal with `mvn`; that's `mvn` on the command 
line by itself.
   - [x] Write unit tests that match behavioral changes, where the tests fail 
if the changes to the runtime are not applied. This may not always be possible, 
but it is a best practice.
   - [x] Write a pull request description that is detailed enough to understand 
what the pull request does, how, and why.
   - [x] Each commit in the pull request should have a meaningful subject line 
and body. Note that a maintainer may squash commits during the merge process.
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to