JDBC: Can I share the connection in a multi-threaded application and enjoy pleasant transactions?

It seems like the classic way to handle transactions with JDBC is to set auto-commit to false. This creates a new transaction, and each commit call marks the beginning of the following transactions. In a multi-threaded application, I understand that it is common practice to open a new connection for each thread.

I am writing an RMI-based multi-user server application, so basically my server easily generates one thread for each new connection. To handle transactions correctly, do I have to go and create a new connection for each of these threads? Is the cost of such an architecture prohibitive?

+5
source share
3 answers

Yes, in general, you need to create a new connection for each thread. You do not have control over how the operating system executes temporary streams of threads (regardless of the definition of your own critical partitions), so you may inadvertently use multiple threads trying to send data on the same channel.

Please note that this applies to any network messages. For example, if you have two streams that are trying to share the same socket with an HTTP connection.

  • Topic 1 makes a request
  • Topic 2 makes a request
  • Thread 1 reads bytes from the socket, unwittingly reading the response from the request for thread 2

, , begin/commit, . , JDBC.

( ), , . . , ( StackOverflow).

update:. , ( - InterBase/Firebird).

. .

, API, JDBC ODBC, , .

+4

. , c3po.

Hibernate, , , , .

+1

-, . , JDBC, . , JDBC . PostgreSQL , ., :

http://doc.postgresintl.com/jdbc/ch10.html

, , , . , JDBC , . - , .

1. Thread 1 opens statement   
3. Thread 2 opens statement
4. Thread 1 does something         Thread 2 does something
5. ...                             ...
6. Thread 1 closes statement       ...
                                7. Thread 2 closes statement

. , - . , . - , , JDBC .

If I remember well, there should be APIs and products with a less simplified design, where the session ID and transaction ID are not equal. In these APIs you can write your server with one database connection object, even if it is a transaction. You will need to check and tell you later what these APIs and products are.

+1
source

All Articles