Thread interruption and concurrent close
Mark Rotteveel
mark at lawinegevaar.nl
Mon May 19 07:14:22 UTC 2025
On 19/05/2025 03:47, David Bullock wrote:
> As a mere spec user, I agree that the doc could be clearer. Only
> #setNetworkTimeout(Executor) makes mention of an 'administrative thread'
> in connection with #abort(Executer), but #abort(Executor) itself is
> silent about this. Further, although mention of an 'administrative
> thread' implies that the Connection is visible to multiple threads, a
> class-level doc about the thread-safety of the object along the lines
> of: "not guaranteed to be thread safe, except for #abort(Executor) and
> #setNetworkTimeout(Executor)" would still be helpful.
There used to be a soft requirement about thread safety in the JDBC
specification (version 1.20, chapter 9 Asynchrony, Threading, and
Transactions), and it was removed in JDBC 2.1. I'm not sure why it was
removed, but probably because not all implementations could or wanted to
do so.
Basically, a connection should be used by one thread during a unit of
work, and if you want to access it from multiple threads during a unit
of work, beyond statement cancellation or connection abort, you need to
coordinate access yourself. If only because you don't want one thread to
do a lot of work, for another thread to call commit() or switch to
auto-commit when the work isn't done yet.
In the JDBC driver I maintain (Jaybird), I do (try to) guarantee thread
safety, and it's not always pretty, and it won't even protect against a
scenario like the previous paragraph.
Also, there is no such thing as an "administrative thread" in JDBC. The
setNetworkTimeout method only talks about an "administrator thread", and
that refers to a thread *outside* of the JDBC connection (and JDBC in
its entirety) that calls abort to cancel misbehaving or stuck
connections (e.g. a connection pool implementation killing connections
if they fail timeout checks, or maybe something that guards liveness of
an application).
Also, please keep in mind that JDBC is an API, and that different
drivers can and do solve things differently, so the API documentation
can't specify everything to death.
For example, for the question that started this thread: for Type 4 (pure
Java) implementations, I'd generally expect that thread interruption has
an effect like stopping what it is doing and maybe even forcibly closing
the connection. However, the other types, especially Type 1 and Type 2,
maybe Type 3, have native components, and once you cross the barrier
into native, Java thread interruption is out of the window. So, if JDBC
had specified that a connection should respond to thread interruption,
Type 1 and Type 2 drivers would have been a lot harder (maybe even
impossible) to write.
Mark
--
Mark Rotteveel
More information about the jdbc-spec-discuss
mailing list