postgresql - JDBC: Can I share a connection in a multithreading app, and enjoy nice transactions? -
it seems classical way handle transactions jdbc set auto-commit false. creates new transaction, , each call commit marks beginning next transactions. on multithreading app, understand common practice open new connection each thread.
i writing rmi based multi-client server application, server seamlessly spawning 1 thread each new connection. handle transactions correctly should go , create new connection each of thread ? isn't cost of such architecture prohibitive?
yes, in general need create new connection each thread. don't have control on how operating system timeslices execution of threads (notwithstanding defining own critical sections), inadvertently have multiple threads trying send data down 1 pipe.
note same applies network communications. if had 2 threads trying share 1 socket http connection, instance.
- thread 1 makes request
- thread 2 makes request
- thread 1 reads bytes socket, unwittingly reading response thread 2's request
if wrapped transactions in critical sections, , therefore lock out other threads entire begin/commit cycle, might able share database connection between threads. wouldn't then, unless have innate knowledge of jdbc protocol.
if of threads have infrequent need database connections (or no need @ all), might able designate 1 thread database work, , have other threads queue requests 1 thread. reduce overhead of many connections. you'll have figure out how manage connections per thread in environment (or ask specific question on stackoverflow).
update: answer question in comment, database brands don't support multiple concurrent transactions on single connection (interbase/firebird exception know of).
it'd nice have separate transaction object, , able start , commit multiple transactions per connection. vendors don't support it.
likewise, standard vendor-independent apis jdbc , odbc make same assumption, transaction state merely property of connection object.
Comments
Post a Comment