• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Share JDBC datasource connection among all servlets

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic