aspose file tools*
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 Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Can I reuse connection ? " Watch "Can I reuse connection ? " New topic
Author

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 8.1.7.4 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,
Avi.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can I reuse connection ?
 
Similar Threads
Sharing Connection Object
DB2 Connection
synchronization of the connection object
To M Spritzler - Client Thread ID change
database connection in init() of servlet