• Post Reply Bookmark Topic Watch Topic
  • New Topic

Share JDBC datasource connection among all servlets

 
manohar gunturu
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am new to java. I have recently learned JDBC connection pool in tomcat.
To make code reuse I want to share the connection among all servlets without any conflict.

Here My code snippet:



I am calling the getConnection method from different servlets like


Is this right way to do. Or I will get any problem due to concurrent threads.
 
Paul Clapham
Sheriff
Posts: 21867
36
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that's the right way to do it, almost, mostly. If you use a connection pool then there should be no danger of two callers getting the same connection.

I said "almost" because declaring the DataSource variable ds as an instance variable of the class does expose you to the possibility of race conditions, as you feared. However making it a local variable of the getConnection() method removes that vulnerability.

And I said "mostly" because the other part of your servlets' responsibility is to close the connection after they finish using it. If you don't do that then you will quickly use up all the pool's connections and make your application unusable. Remember to close the connection in a finally block, or use a try-with-resources statement when acquiring the connection.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!