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

rmaucher pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit ea7ba66ddb01df38367a85e32ad3f9d20f51dbc5
Author: opencode <[email protected]>
AuthorDate: Tue Dec 1 15:36:09 2026 +0100

    Add rollbackOnAbandon for abandoned connections
    
    Bugzilla 60522. An abandoned connection is closed without terminating
    its
    transaction, and a driver that commits on close - Oracle is the usual
    example -
    can persist work the application never committed. Add a
    rollbackOnAbandon option
    that rolls the transaction back before the physical session is closed.
    It is
    independent of rollbackOnReturn, which only applies when a connection is
    returned to the pool, and defaults to false for compatibility.
    
    The rollback is only attempted when the abandoned connection is in a
    transaction, inferred from getAutoCommit() returning false. A failed
    rollback is
    logged and still retires the connection, because an abandoned session
    cannot be
    returned to the pool.
    
    Wire the option through PoolConfiguration, PoolProperties,
    DataSourceProxy, the
    JMX surface, DataSourceFactory and the documentation. Cover it with a
    test
    driver that records rollback and close calls, including the opt-in
    default, a
    failed rollback and an auto-commit session.
---
 modules/jdbc-pool/doc/jdbc-pool.xml                |  12 +-
 .../apache/tomcat/jdbc/pool/ConnectionPool.java    |  33 ++-
 .../apache/tomcat/jdbc/pool/DataSourceFactory.java |  14 +-
 .../apache/tomcat/jdbc/pool/DataSourceProxy.java   |  10 +
 .../apache/tomcat/jdbc/pool/PoolConfiguration.java |  27 +-
 .../apache/tomcat/jdbc/pool/PoolProperties.java    |  13 +
 .../tomcat/jdbc/pool/jmx/ConnectionPool.java       |  10 +
 .../apache/tomcat/jdbc/pool/mbeans-descriptors.xml |   6 +
 .../tomcat/jdbc/pool/util/LocalStrings.properties  |   1 +
 .../tomcat/jdbc/pool/RollbackOnAbandonBase.java    | 284 +++++++++++++++++++++
 .../tomcat/jdbc/pool/TestAbandonedSuspect.java     |   6 +-
 webapps/docs/changelog.xml                         |   6 +
 12 files changed, 415 insertions(+), 7 deletions(-)

diff --git a/modules/jdbc-pool/doc/jdbc-pool.xml 
b/modules/jdbc-pool/doc/jdbc-pool.xml
index 14046f9876..266d04ddf6 100644
--- a/modules/jdbc-pool/doc/jdbc-pool.xml
+++ b/modules/jdbc-pool/doc/jdbc-pool.xml
@@ -426,8 +426,8 @@
       <p>(boolean) Flag to remove abandoned connections if they exceed the 
<code>removeAbandonedTimeout</code>.
          If set to true a connection is considered abandoned and eligible for 
removal if it has been in use
          longer than the <code>removeAbandonedTimeout</code> Setting this to 
<code>true</code> can recover db connections from
-         applications that fail to close a connection. See also 
<code>logAbandoned</code>
-         The default value is <code>false</code>.</p>
+         applications that fail to close a connection. See also 
<code>logAbandoned</code> and
+         <code>rollbackOnAbandon</code>. The default value is 
<code>false</code>.</p>
     </attribute>
 
     <attribute name="removeAbandonedTimeout" required="false">
@@ -603,6 +603,14 @@
           Default value is <code>false</code>.<br/>
       </p>
     </attribute>
+    <attribute name="rollbackOnAbandon" required="false">
+      <p>(boolean) If <code>autoCommit==false</code> then the pool can 
terminate the transaction by calling rollback
+          on the connection as it is abandoned. The rollback runs before the 
physical connection is closed, so a
+          driver that commits on close, such as Oracle, cannot commit work the 
application left uncommitted. This is
+          independent of <code>rollbackOnReturn</code>, which only applies 
when a connection is returned to the pool.
+          Default value is <code>false</code>.<br/>
+      </p>
+    </attribute>
     <attribute name="alternateUsernameAllowed" required="false">
       <p>(boolean) By default, the jdbc-pool will ignore the
          <a 
href="https://docs.oracle.com/en/java/javase/17/docs/api/java.sql/javax/sql/DataSource.html#getConnection(java.lang.String,java.lang.String)"><code>DataSource.getConnection(username,password)</code></a>
diff --git 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java
 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java
index 07a29243ab..fab599a482 100644
--- 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java
+++ 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java
@@ -1573,8 +1573,9 @@ public class ConnectionPool {
     }
 
     /**
-     * thread safe way to abandon a connection signals a connection to be 
abandoned. this will disconnect the
-     * connection, and log the stack trace if logAbandoned=true
+     * Thread safe way to abandon a connection signals a connection to be 
abandoned. When rollbackOnAbandon is
+     * configured, its transaction is rolled back before the connection is 
disconnected; the stack trace is logged if
+     * logAbandoned=true.
      *
      * @param con PooledConnection
      */
@@ -1592,6 +1593,9 @@ public class ConnectionPool {
             if (jmx != null) {
                 
jmx.notify(org.apache.tomcat.jdbc.pool.jmx.ConnectionPool.NOTIFY_ABANDON, 
trace);
             }
+            if (poolProperties.getRollbackOnAbandon()) {
+                rollbackAbandoned(con);
+            }
             // Release the connection
             removeAbandonedCount.incrementAndGet();
             release(con);
@@ -1600,6 +1604,31 @@ public class ConnectionPool {
         }
     }
 
+    /**
+     * Rolls back the transaction of an abandoned connection before it is 
closed. A connection that is not in a
+     * transaction, or whose session has already been disconnected, is left 
untouched. A rollback failure is logged and
+     * does not stop the abandonment: the session is still taken out of 
service, because it cannot be returned to the
+     * pool.
+     *
+     * @param con the abandoned connection
+     */
+    private void rollbackAbandoned(PooledConnection con) {
+        Connection connection = con.getConnection();
+        if (connection == null) {
+            return;
+        }
+        try {
+            if (!connection.getAutoCommit()) {
+                connection.rollback();
+                con.clearTransactionDirty();
+            }
+        } catch (Throwable x) {
+            ExceptionUtils.handleThrowable(x);
+            
log.warn(MessageFactory.get("connectionPool.unableToRollbackAbandonedConnection"),
+                    PoolUtilities.maskCredentials(x));
+        }
+    }
+
     /**
      * Thread safe way to suspect a connection. Similar to {@link 
#abandon(PooledConnection)}, but instead of actually
      * abandoning the connection, this marks the suspect flag on the {@link 
PooledConnection} and reports it through the
diff --git 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceFactory.java
 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceFactory.java
index a60cf12694..7bf80c560a 100644
--- 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceFactory.java
+++ 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceFactory.java
@@ -207,6 +207,9 @@ public class DataSourceFactory implements ObjectFactory {
     /** The {@code rollbackOnReturn} property name. */
     protected static final String PROP_ROLLBACKONRETURN = "rollbackOnReturn";
 
+    /** The {@code rollbackOnAbandon} property name. */
+    protected static final String PROP_ROLLBACKONABANDON = "rollbackOnAbandon";
+
     /**
      * Property name for useDisposableConnectionFacade. The property is 
deprecated and has no effect; the disposable
      * connection facade is always used.
@@ -253,7 +256,8 @@ public class DataSourceFactory implements ObjectFactory {
             PROP_INITSQL, PROP_INTERCEPTORS, PROP_JMX_ENABLED, 
PROP_FAIR_QUEUE, PROP_USE_EQUALS, OBJECT_NAME,
             PROP_ABANDONWHENPERCENTAGEFULL, PROP_MAXAGE, PROP_USE_LOCK, 
PROP_DATASOURCE, PROP_DATASOURCE_JNDI,
             PROP_SUSPECT_TIMEOUT, PROP_ALTERNATE_USERNAME_ALLOWED, 
PROP_COMMITONRETURN, PROP_ROLLBACKONRETURN,
-            PROP_USEDISPOSABLECONNECTIONFACADE, PROP_LOGVALIDATIONERRORS, 
PROP_PROPAGATEINTERRUPTSTATE,
+            PROP_ROLLBACKONABANDON, PROP_USEDISPOSABLECONNECTIONFACADE, 
PROP_LOGVALIDATIONERRORS,
+            PROP_PROPAGATEINTERRUPTSTATE,
             PROP_IGNOREEXCEPTIONONPRELOAD, PROP_USESTATEMENTFACADE };
 
     /**
@@ -939,6 +943,14 @@ public class DataSourceFactory implements ObjectFactory {
             }
         }
 
+        value = properties.getProperty(PROP_ROLLBACKONABANDON);
+        if (value != null) {
+            Boolean b = parseBoolean(PROP_ROLLBACKONABANDON, value);
+            if (b != null) {
+                poolProperties.setRollbackOnAbandon(b.booleanValue());
+            }
+        }
+
         value = properties.getProperty(PROP_USEDISPOSABLECONNECTIONFACADE);
         if (value != null) {
             Boolean b = parseBoolean(PROP_USEDISPOSABLECONNECTIONFACADE, 
value);
diff --git 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java
 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java
index 3565dfd16b..c20c534eac 100644
--- 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java
+++ 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java
@@ -1725,6 +1725,16 @@ public class DataSourceProxy implements 
PoolConfiguration {
         return getPoolProperties().getRollbackOnReturn();
     }
 
+    @Override
+    public void setRollbackOnAbandon(boolean rollbackOnAbandon) {
+        getPoolProperties().setRollbackOnAbandon(rollbackOnAbandon);
+    }
+
+    @Override
+    public boolean getRollbackOnAbandon() {
+        return getPoolProperties().getRollbackOnAbandon();
+    }
+
     /**
      * {@inheritDoc}
      *
diff --git 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java
 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java
index b853fb156b..b31ee1c10b 100644
--- 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java
+++ 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java
@@ -534,7 +534,7 @@ public interface PoolConfiguration {
      * connection is considered abandoned and eligible for removal if it has 
been in use longer than the
      * {@link #getRemoveAbandonedTimeout()} and the condition for {@link 
#getAbandonWhenPercentageFull()} is met.
      * Setting this to true can recover db connections from applications that 
fail to close a connection. See also
-     * {@link #isLogAbandoned()} The default value is false.
+     * {@link #isLogAbandoned()} and {@link #setRollbackOnAbandon(boolean)}. 
The default value is false.
      *
      * @param removeAbandoned set to true if abandoned connections can be 
closed and expelled out of the pool
      */
@@ -1094,6 +1094,31 @@ public interface PoolConfiguration {
      */
     boolean getRollbackOnReturn();
 
+    /**
+     * Set to true if you want the connection pool to roll back any pending 
transaction when a connection is
+     * abandoned. The default value is false. The rollback runs before the 
physical connection is closed, so a driver
+     * that commits on close - Oracle is the usual example - cannot commit 
work the application left uncommitted. This
+     * is independent of {@link #setRollbackOnReturn(boolean)}: that option 
applies only when a connection is returned
+     * to the pool, not when the pool takes an abandoned connection out of 
service.
+     * <p>
+     * The rollback is only performed when the abandoned connection is 
actually in a transaction, inferred from
+     * {@link java.sql.Connection#getAutoCommit()} returning false; a 
transaction a driver or raw SQL leaves open while
+     * auto-commit is true is outside this handling. A rollback failure is 
logged and the connection is still closed,
+     * because an abandoned session cannot be returned to the pool.
+     *
+     * @param rollbackOnAbandon set to true if the pool should call {@link 
java.sql.Connection#rollback()} before
+     *                              closing an abandoned connection. Default 
is false
+     */
+    void setRollbackOnAbandon(boolean rollbackOnAbandon);
+
+    /**
+     * Returns whether the pool rolls back any pending transaction when a 
connection is abandoned. See
+     * {@link PoolConfiguration#setRollbackOnAbandon(boolean)} for details.
+     *
+     * @return {@code true} if the pool should rollback before closing an 
abandoned connection
+     */
+    boolean getRollbackOnAbandon();
+
     /**
      * Stores the value of the deprecated {@code 
useDisposableConnectionFacade} property. The pool always wraps the
      * connection handle in a facade that disallows use of the connection 
after {@link java.sql.Connection#close()} has
diff --git 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java
 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java
index 11f76b808d..e6e2544f39 100644
--- 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java
+++ 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java
@@ -212,6 +212,8 @@ public class PoolProperties implements PoolConfiguration, 
Cloneable, Serializabl
     private volatile boolean commitOnReturn = false;
     /** Whether to rollback on connection return. */
     private volatile boolean rollbackOnReturn = false;
+    /** Whether to rollback an abandoned connection before closing it. */
+    private volatile boolean rollbackOnAbandon = false;
     /**
      * Whether to use a disposable connection facade.
      *
@@ -2556,6 +2558,16 @@ public class PoolProperties implements 
PoolConfiguration, Cloneable, Serializabl
         return this.rollbackOnReturn;
     }
 
+    @Override
+    public void setRollbackOnAbandon(boolean rollbackOnAbandon) {
+        this.rollbackOnAbandon = rollbackOnAbandon;
+    }
+
+    @Override
+    public boolean getRollbackOnAbandon() {
+        return this.rollbackOnAbandon;
+    }
+
     /**
      * {@inheritDoc}
      *
@@ -2711,6 +2723,7 @@ public class PoolProperties implements PoolConfiguration, 
Cloneable, Serializabl
             copy.alternateUsernameAllowed = from.alternateUsernameAllowed;
             copy.commitOnReturn = from.commitOnReturn;
             copy.rollbackOnReturn = from.rollbackOnReturn;
+            copy.rollbackOnAbandon = from.rollbackOnAbandon;
             copy.useDisposableConnectionFacade = 
from.useDisposableConnectionFacade;
             copy.logValidationErrors = from.logValidationErrors;
             copy.propagateInterruptState = from.propagateInterruptState;
diff --git 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java
 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java
index 553f270309..de32951001 100644
--- 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java
+++ 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java
@@ -1258,6 +1258,16 @@ public class ConnectionPool extends 
NotificationBroadcasterSupport implements Co
         return getPoolProperties().getRollbackOnReturn();
     }
 
+    @Override
+    public void setRollbackOnAbandon(boolean rollbackOnAbandon) {
+        getPoolProperties().setRollbackOnAbandon(rollbackOnAbandon);
+    }
+
+    @Override
+    public boolean getRollbackOnAbandon() {
+        return getPoolProperties().getRollbackOnAbandon();
+    }
+
     /**
      * {@inheritDoc}
      *
diff --git 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/mbeans-descriptors.xml
 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/mbeans-descriptors.xml
index a597ed9ab0..a9adb7245f 100644
--- 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/mbeans-descriptors.xml
+++ 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/mbeans-descriptors.xml
@@ -278,6 +278,12 @@
                     is="false"
              writeable="false"/>
 
+    <attribute    name="rollbackOnAbandon"
+           description="If autoCommit==false then the pool can terminate the 
transaction by calling rollback on an abandoned connection before closing it"
+                  type="java.lang.Boolean"
+                    is="false"
+             writeable="false"/>
+
     <attribute    name="alternateUsernameAllowed"
            description="If true, getConnection(username,password) is allowed"
                   type="java.lang.Boolean"
diff --git 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/util/LocalStrings.properties
 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/util/LocalStrings.properties
index 5811c6125f..67128b257e 100644
--- 
a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/util/LocalStrings.properties
+++ 
b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/util/LocalStrings.properties
@@ -83,6 +83,7 @@ connectionPool.unableToResetInterceptor=Unable to reset 
interceptor [{0}].
 connectionPool.unableToReturnConnection=Unable to return connection [{0}] to 
the pool, closing it.
 connectionPool.unableToStartJmx=Unable to start JMX integration for connection 
pool. Instance[{0}] can''t be monitored.
 connectionPool.unableToTestIdleConnection=Unable to test idle connection 
[{0}], closing it.
+connectionPool.unableToRollbackAbandonedConnection=Unable to roll back the 
transaction of an abandoned connection before closing it.
 connectionPool.unableToTerminateTransaction=Unable to terminate transaction, 
connection will be closed.
 connectionPool.unresolvedXaBranchReturned=Connection [{0}] was returned with 
XA transaction branches that were never resolved. The session is closed and 
replaced instead of being pooled, so no other borrower inherits a branch or the 
database locks held for it, and the late commit or rollback of the abandoned 
branch fails against the closed session. Complete every branch - commit, 
rollback or forget - before closing a pooled XA handle.
 connectionPool.validationQueryFailed=Validation Query Failed, enable 
logValidationErrors for more details.
diff --git 
a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/RollbackOnAbandonBase.java
 
b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/RollbackOnAbandonBase.java
new file mode 100644
index 0000000000..c790046d7e
--- /dev/null
+++ 
b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/RollbackOnAbandonBase.java
@@ -0,0 +1,284 @@
+/*
+ *  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
+ *
+ *      http://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.tomcat.jdbc.pool;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Properties;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import org.apache.tomcat.jdbc.JdbcPoolBaseTest;
+
+/**
+ * Bugzilla 60522: an abandoned connection is closed without terminating its
+ * transaction. Drivers such as Oracle commit on close, so work the application
+ * did not commit can become durable. The pool must be able to roll back the
+ * session before it closes it, independently of rollbackOnReturn (which only
+ * covers a connection returned to the pool).
+ *
+ * <p>The tests use a driver wrapper that counts rollback() and close() calls
+ * on the physical connections, so the assertion is about what the pool asked
+ * the driver to do, not about H2's own close behaviour.
+ */
+abstract class RollbackOnAbandonBase extends JdbcPoolBaseTest {
+
+    /**
+     * H2 driver whose physical connections count rollback() and close()
+     * calls. The pool obtains connections through it, so the counters prove
+     * whether the abandonment path terminated the transaction before closing
+     * the session.
+     */
+    public static class RollbackRecordingDriver extends org.h2.Driver {
+
+        static final AtomicInteger ROLLBACKS = new AtomicInteger();
+        static final AtomicInteger CLOSES = new AtomicInteger();
+        static final AtomicBoolean FAIL_ROLLBACK = new AtomicBoolean();
+
+        static void reset() {
+            ROLLBACKS.set(0);
+            CLOSES.set(0);
+            FAIL_ROLLBACK.set(false);
+        }
+
+        @Override
+        public Connection connect(String url, Properties info) throws 
SQLException {
+            Connection delegate = super.connect(url, info);
+            if (delegate == null) {
+                return null;
+            }
+            InvocationHandler handler = new InvocationHandler() {
+                @Override
+                public Object invoke(Object proxy, Method method, Object[] 
args) throws Throwable {
+                    if ("rollback".equals(method.getName())) {
+                        if (FAIL_ROLLBACK.get()) {
+                            throw new SQLException("rollback refused by test 
driver");
+                        }
+                        ROLLBACKS.incrementAndGet();
+                    } else if ("close".equals(method.getName())) {
+                        CLOSES.incrementAndGet();
+                    }
+                    try {
+                        return method.invoke(delegate, args);
+                    } catch (InvocationTargetException x) {
+                        throw x.getCause();
+                    }
+                }
+            };
+            return (Connection) 
Proxy.newProxyInstance(RollbackRecordingDriver.class.getClassLoader(),
+                    new Class<?>[] { Connection.class }, handler);
+        }
+    }
+
+    private String createTable() throws SQLException {
+        String table = uniqueTable();
+        try (Connection admin = adminConnection(); Statement st = 
admin.createStatement()) {
+            st.execute("CREATE TABLE " + table + " (v INT)");
+        }
+        return table;
+    }
+
+    private DataSource poolForAbandonment(boolean rollbackOnAbandon) {
+        DataSource ds = newDataSource();
+        ds.setDriverClassName(RollbackRecordingDriver.class.getName());
+        ds.getPoolProperties().setInitialSize(1);
+        ds.getPoolProperties().setMinIdle(0);
+        ds.getPoolProperties().setMaxActive(1);
+        ds.getPoolProperties().setMaxIdle(1);
+        ds.getPoolProperties().setRemoveAbandoned(true);
+        ds.getPoolProperties().setRemoveAbandonedTimeout(1); // seconds
+        ds.getPoolProperties().setAbandonWhenPercentageFull(0);
+        ds.getPoolProperties().setTimeBetweenEvictionRunsMillis(200);
+        if (rollbackOnAbandon) {
+            ds.getPoolProperties().setRollbackOnAbandon(true);
+        }
+        return ds;
+    }
+
+    private Connection borrowAndOpenTransaction(DataSource ds, String table) 
throws SQLException {
+        Connection connection = ds.getConnection();
+        connection.setAutoCommit(false);
+        try (Statement st = connection.createStatement()) {
+            st.executeUpdate("INSERT INTO " + table + " VALUES (1)");
+        }
+        return connection;
+    }
+
+    private void awaitAbandoned(DataSource ds) {
+        ConnectionPool pool = ds.getPool();
+        awaitUntil(() -> pool.getRemoveAbandonedCount() >= 1);
+        awaitUntil(() -> RollbackRecordingDriver.CLOSES.get() >= 1);
+    }
+
+    @Test
+    void rollbackOnAbandonIsPartOfTheConfigurationSurface() throws Exception {
+        Assertions.assertFalse(new PoolProperties().getRollbackOnAbandon(),
+                "rollbackOnAbandon must default to false");
+
+        Properties attributes = new Properties();
+        attributes.setProperty("rollbackOnAbandon", "true");
+        PoolConfiguration configured = 
DataSourceFactory.parsePoolProperties(attributes);
+        Assertions.assertTrue(configured.getRollbackOnAbandon(),
+                "the factory must parse rollbackOnAbandon");
+
+        DataSource ds = new DataSource();
+        try {
+            ds.setRollbackOnAbandon(true);
+            Assertions.assertTrue(ds.getRollbackOnAbandon(),
+                    "the data source must delegate rollbackOnAbandon to its 
configuration");
+        } finally {
+            ds.close();
+        }
+    }
+
+    @Test
+    void rollbackOnAbandonCanBeChangedOnALivePool() throws Exception {
+        DataSource ds = newDataSource();
+        ds.createPool();
+        try {
+            ds.setRollbackOnAbandon(true);
+            
Assertions.assertTrue(ds.getPoolProperties().getRollbackOnAbandon(),
+                    "the live configuration must accept rollbackOnAbandon");
+            ds.setRollbackOnAbandon(false);
+            
Assertions.assertFalse(ds.getPoolProperties().getRollbackOnAbandon(),
+                    "the live configuration must accept disabling 
rollbackOnAbandon");
+        } finally {
+            ds.close();
+        }
+    }
+
+    @Test
+    void rollbackOnAbandonRollsBackBeforeClosingTheAbandonedSession() throws 
Exception {
+        RollbackRecordingDriver.reset();
+        String table = createTable();
+        DataSource ds = poolForAbandonment(true);
+        ds.createPool();
+        try {
+            Connection held = borrowAndOpenTransaction(ds, table);
+            try {
+                awaitAbandoned(ds);
+                Assertions.assertEquals(1, 
RollbackRecordingDriver.ROLLBACKS.get(),
+                        "the abandoned connection's transaction must be rolled 
back");
+                Assertions.assertEquals(1, 
RollbackRecordingDriver.CLOSES.get(),
+                        "the abandoned connection must still be closed");
+                Assertions.assertEquals(0, adminRowCount(table),
+                        "the aborted insert must not survive the abandonment");
+                awaitUntil(() -> ds.getPool().getSize() == 0);
+                Assertions.assertEquals(0, ds.getPool().getSize(),
+                        "the abandoned session must be taken out of the pool");
+            } finally {
+                held.close();
+            }
+        } finally {
+            ds.close();
+        }
+    }
+
+    @Test
+    void rollbackOnAbandonIsOptIn() throws Exception {
+        RollbackRecordingDriver.reset();
+        String table = createTable();
+        DataSource ds = poolForAbandonment(false);
+        ds.createPool();
+        try {
+            
Assertions.assertFalse(ds.getPoolProperties().getRollbackOnAbandon(),
+                    "rollbackOnAbandon must default to false");
+            Connection held = borrowAndOpenTransaction(ds, table);
+            try {
+                awaitAbandoned(ds);
+                Assertions.assertEquals(0, 
RollbackRecordingDriver.ROLLBACKS.get(),
+                        "without the option the pool must not call 
rollback()");
+                Assertions.assertEquals(1, 
RollbackRecordingDriver.CLOSES.get(),
+                        "the abandoned connection must still be closed");
+            } finally {
+                held.close();
+            }
+        } finally {
+            ds.close();
+        }
+    }
+
+    @Test
+    void aFailedAbandonRollbackStillRetiresTheConnection() throws Exception {
+        RollbackRecordingDriver.reset();
+        RollbackRecordingDriver.FAIL_ROLLBACK.set(true);
+        String table = createTable();
+        DataSource ds = poolForAbandonment(true);
+        ds.createPool();
+        try {
+            Connection held = borrowAndOpenTransaction(ds, table);
+            try {
+                awaitAbandoned(ds);
+                Assertions.assertEquals(0, 
RollbackRecordingDriver.ROLLBACKS.get(),
+                        "the driver refused the rollback, so no successful 
call is counted");
+                Assertions.assertEquals(1, 
RollbackRecordingDriver.CLOSES.get(),
+                        "a failed rollback must not keep the connection from 
being closed");
+                Assertions.assertEquals(0, adminRowCount(table),
+                        "the refused insert must not survive the abandonment");
+                awaitUntil(() -> ds.getPool().getSize() == 0);
+                // The pool must remain usable after the failed rollback.
+                try (Connection replacement = ds.getConnection();
+                        Statement st = replacement.createStatement();
+                        ResultSet rs = st.executeQuery("SELECT 1")) {
+                    Assertions.assertTrue(rs.next(),
+                            "the replacement connection must serve a query");
+                }
+            } finally {
+                held.close();
+            }
+        } finally {
+            RollbackRecordingDriver.FAIL_ROLLBACK.set(false);
+            ds.close();
+        }
+    }
+
+    @Test
+    void rollbackOnAbandonDoesNotTouchAnAutoCommitSession() throws Exception {
+        RollbackRecordingDriver.reset();
+        String table = createTable();
+        DataSource ds = poolForAbandonment(true);
+        ds.createPool();
+        try {
+            Connection held = ds.getConnection();
+            try (Statement st = held.createStatement()) {
+                st.executeUpdate("INSERT INTO " + table + " VALUES (2)");
+            }
+            try {
+                awaitAbandoned(ds);
+                Assertions.assertEquals(0, 
RollbackRecordingDriver.ROLLBACKS.get(),
+                        "an auto-commit session has no transaction to roll 
back");
+                Assertions.assertEquals(1, 
RollbackRecordingDriver.CLOSES.get(),
+                        "the abandoned connection must still be closed");
+                Assertions.assertEquals(1, adminRowCount(table),
+                        "the auto-committed insert must remain durable");
+            } finally {
+                held.close();
+            }
+        } finally {
+            ds.close();
+        }
+    }
+}
diff --git 
a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/TestAbandonedSuspect.java
 
b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/TestAbandonedSuspect.java
index 646f6e24b3..3311ffbcf5 100644
--- 
a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/TestAbandonedSuspect.java
+++ 
b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/TestAbandonedSuspect.java
@@ -46,4 +46,8 @@ class TestAbandonedSuspect {
     class ForcedShutdownDoesNotAbandon extends 
ForcedShutdownDoesNotAbandonBase {
     }
 
-}
\ No newline at end of file
+    @Nested
+    class RollbackOnAbandon extends RollbackOnAbandonBase {
+    }
+
+}
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 38f829f7fa..8f1b7956b5 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -558,6 +558,12 @@
         Revert pull request <pr>677</pr> which added request hints from JDBC
         4.3, causing statement cache issues on many databases. (remm)
       </add>
+      <add>
+        Add a <code>rollbackOnAbandon</code> attribute that rolls back the
+        transaction of an abandoned connection before closing it, so a driver
+        that commits on close cannot commit work the application left
+        uncommitted. (remm)
+      </add>
       <update>
         Introduce an immutable configuration snapshot and a single validated
         apply path for live pool reconfiguration. Connection establishment and


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to