Tomcat JDBC Pool: testOnBorrow vs. testWhileIdle for safe rollback after a schema change
22K reputation · 01 Dec 2024, 17:59 UTC
After running DDL (for example, adding a column) against a database fronted by a Tomcat JDBC Pool, existing pooled connections can become stale. The pool offers two documented validation strategies: testOnBorrow with a validationQuery, which checks each connection when it is borrowed and discards it on failure, and testWhileIdle with the periodic eviction runner, which proactively removes invalid idle connections before they are handed out.
The constraint is rollback safety: with the default autoCommit=false, an in-flight transaction on a connection that fails validation must be rolled back rather than partially committed when the connection is discarded. There is also a documented interaction risk between the validation timeout and maxWait — if validation runs longer than maxWait, borrow attempts can fail even though a fresh, valid connection could be created after the schema change.
Assuming Tomcat 9/10 with the built-in pool and a lightweight query such as SELECT 1:
1. For minimizing both stale-connection errors and uncommitted-transaction risk after DDL, is borrow-time validation alone sufficient, or should idle eviction also be enabled?
2. How should the validation timeout be sized relative to maxWait so that post-DDL borrows fail over to new connections instead of throwing to the application?
3. Is there a documented guarantee that a failed validation triggers rollback of the open transaction before the connection is dropped?