Mrinmoy
Mrinmoy

Reputation: 1639

Java JDBC Connection Sharing/relaying between methods

I am developing an WebApp and would like to know if there is any pros/cons of sharing JDBC connection object between methods

So the situation is

Now i have two approach

Approach 1 Open the connection object once and relay it across the methods

// Just a Pseudo Code

Cn = OpenJDBConnection() // This will open up the  connection 
obj.Task1(Cn, Param1, Param2);
obj.Task2(Cn, Param1, Param2);
obj.Task3(Cn, Param1, Param2);
Cn.close();

Approach 2 Open and close the connection in each method

I am leaning on Approach 1 as that way i will be able to avoid some boilerplate code. but i am unsure will it be threadsafe ? i have a poolsize of 100 connection which i think is okay for 1000 users active at a given time

is there anything else too that i should be considering before adopting one of the approach

Upvotes: 2

Views: 805

Answers (1)

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

Consider that transactions are managed at the connection level.

For your simple use-case, approach #1 may work, but it's easy to get into a situation where, for example, you have transaction pending on the connection, and call another method which does a select on the same connection, which will cause your transaction to commit (earlier than you expected).

With properly-configured connection pooling, the overhead of releasing and re-obtaining a connection should be minmal, so I'd suggest approach #2. When pooled, closing the connection doesn' really close it, it leaves it open and returns it to the pool.

Upvotes: 4

Related Questions