How can I abort a running JDBC transaction?

As mentioned by james, Statement.cancel() will cancel the execution of a running Statement (select, update, etc). The JDBC docs specifically say that Statement.cancel() is safe to run from another thread and even suggests the usage of calling it in a timeout thread.

After canceling the statement, you’re still stuck with the job of rolling back the transaction. That is not documented as being safe to run from another thread. The Connection.rollback() should happen in the main thread doing all the other JDBC calls. You can handle that after the canceled Statement.execute…() call completes with a JDBCException (due to the cancel).

Leave a Comment