File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes Query related to JNDI datasource Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Query related to JNDI datasource" Watch "Query related to JNDI datasource" New topic

Query related to JNDI datasource

Abhishek Yadav

Joined: Nov 15, 2006
Posts: 26
I am using apache common DBCP for connectiion pooling in tomcat. I am working on a web application. Following is the lookup code:-
initContext=new InitialContext();
ds=(DataSource) initContext.lookup("java:comp/env/jdbc/yourrail");
Every time, when i need a connection object, i am always executing the above code(lookung up for datasource in JNDI tree).

My Question is:-
(1)I have a servlet as a front controller. If say 10 threads are executing the above code, they all 10 thread get a reference to the same datasource object?(I think they all get the reference to same data source object.)
(2)If it is the same data source object, then
is thread safe?(I think it is thread safe. Implementation of DBCP provides that)
(3)If i am getting the same Datasource object after lookup, it would be better to lookup only once, and store this datasource object as attribute in servlet context?

Please validate above queries. Thanks in advance for your support.

Abhishek Yadav

Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33130

1) Yes. You are correct.
2) Also yes. DBCP is well used. It's unlikely anything threading bugs are left (if they ever existed)
3) Caching JNDI resources locally is an accepted practice.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
I agree. Here's the link:
subject: Query related to JNDI datasource
It's not a secret anymore!