Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

javax.sql.DataSource as ServletContext Attribute  RSS feed

 
amit punekar
Ranch Hand
Posts: 544
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
Whenever we need DB connection we lookup the InitialContext for the datasource name. After that we invoke getConnection() on it.
If we plan to store the reference to already lookedup javax.sql.DataSource in the application scope , what might go wrong?
I want to understand in terms of the multithreaded environment in which servlet runs. Or is it better to lookup the Datasource as and when necessary and get connection using that?
Regards
Amit
 
amit punekar
Ranch Hand
Posts: 544
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Here are my thoughts to my own post.
1)Whenever we lookup the Datasource using InitialContext it is retrieved from the JNDI tree and returned to us.
2) We invoke the getConnection() which returns a Connection back to us.
When I ask about storing the reference of the DataSource in ServletContext it would mean I will only be doing lookup at the Start of webapplication. After that instead of looking up JNDI , I will get it from Application scope.
Based on this I feel I should not see problem doing this in multithreaded environment.

Regards
Amit
 
Scott Escue
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amit,

Looking up the DataSource once and caching it is definitely a good idea since, as you mentioned, it saves you from doing a JNDI lookup each time you need to use it. A couple of things you may want to consider about it:

1) You need to make sure the DataSource implementation your using is thread-safe. If your using an implementation provided by your database vendor, say Oracle or MySql, it's probably safe to assume thread-safety has been taken care of. Of course it never hurts to verify that!

2) If you store the DataSource in the ServletContext you will be forced to retrieve the DataSource in your servlet/controller layer and pass it through to any business/DAO methods that need to actually use it. If you have a very simple application maybe that's not a big deal for you. But you can use a service locator to get the same result of looking up the DataSource once and caching it. The advantage is that the service locator can be used in any layer of your application to retrieve the cached DataSource, which keeps you from having to pass a DataSource argument to each method that needs to use it.
http://java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceLocator.html
[ April 01, 2008: Message edited by: Scott Escue ]
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!