This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes JDBC and the fly likes Can I reuse connection ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Can I reuse connection ? " Watch "Can I reuse connection ? " New topic

Can I reuse connection ?

Sun LiWei
Ranch Hand

Joined: Aug 10, 2002
Posts: 49
o ne of the policy of general database connection pool is creating new connection for every thread who request database connection by calling getConnection() method(normally,this method is synchronized.I wondered is there any synchronization problem if give the same connection object to mutiple threads.On the other words,is it safe if two thread use the same connection object concurrency?
[ June 16, 2003: Message edited by: Sun LiWei ]
Andy Bowes
Ranch Hand

Joined: Jan 14, 2003
Posts: 171
This policy is no where near safe. You will encounter huge problems if multiple threads are attempting to use the same connection simultaneously.
The best way to use connections is to create a pool of connections then each thread can request a connection from the pool, have exclusive use of the connectiona nd then release it back into the pool when it has completed it's database operations.

Andy Bowes<br />SCJP, SCWCD<br />I like deadlines, I love the whoosing noise they make as they go flying past - Douglas Adams
Avi Abrami
Ranch Hand

Joined: Oct 11, 2000
Posts: 1121

Hi Sun,
In my experience with Oracle database on SUN [sparc] Solaris 7 and J2SE 1.3.1_02, when two threads attempt to access the same "Connection" object simultaneously, the second one will block until the first one completes its request.
For example, if two separate threads invoke the "executeQuery()" method (in class "java.sql.Statement"), the second thread is blocked, until the first thread invokes the "close()" method. Then the second thread's invocation (of "executeQuery()") is executed. Note that both threads, eventually, receive their requested "ResultSet".
Obviously you need to decide whether this constitutes being "thread safe" (or not).
Hope this has helped.
Good Luck,
I agree. Here's the link:
subject: Can I reuse connection ?
Similar Threads
DB2 Connection
database connection in init() of servlet
synchronization of the connection object
To M Spritzler - Client Thread ID change
Sharing Connection Object