Reputation: 14306
I am learning about JDBC
connection pooling and it sounds relatively easy to get a DataSource
instance using JNDI
:
DataSource ds = (DataSource)ctx.lookup("jdbc/myDB");
All the tutorials I found show this code in one object only, but my question is how to use a DataSource
when I have several DAO
objects needing to fetch data from a DB.
Is it ok to use the code above for connection pooling on every new DAO
object's constructor? I think the same DataSource
will be returned every time, much like a Dictionary Singleton would do, holding a single DataSource
and returning it, or am I wrong and will it return a different DataSource
every time and use different pools, defeating my purpose?
Should I hold that DataSource
in a Singleton and only run the JNDI
search once or is the search overhead neglectable and this is a silly optimization?
Upvotes: 0
Views: 193
Reputation: 42966
- Is it ok to use the code above for connection pooling on every new DAO object's constructor? I think the same DataSource will be returned every time, much like a Dictionary Singleton would do, holding a single DataSource and returning it, or am I wrong and will it return a different DataSource every time and use different pools, defeating my purpose?
The same DataSource object ought to be returned each time. If it's not literally the same object, then it ought to at least share the same underlying connection pool.
- Should I hold that DataSource in a Singleton and only run the JNDI search once or is the search overhead neglectable and this is a silly optimization?
The search overhead of JNDI is negligible compared to performing operations on a remote database, so it's not necessary to cache the DataSource object.
Upvotes: 1