In the following Connector/J reference for JDBC/MySQL it suggests we cache the instances of InitialContext and Datasource. Would just making it a private static instance solve the caching? Shouldn't one have to be concerned with thread-safety (if at all)? What is the best 'place' to cache this for a web-app (Restlet + glassfish/Java EE + mysql)??
There is a GenericDAO class that is the root of the data-access classes, so to speak. So would just having static instances actually solve the problem? It would force some of the methods to be static which we don't want. Suggestions??
Thanks!
public void doSomething() throws Exception {
/*
* Create a JNDI Initial context to be able to
* lookup the DataSource
**
In production-level code, this should be cached as
* an instance or static variable, as it can
* be quite expensive to create a JNDI context.
**
Note: This code only works when you are using servlets
* or EJBs in a Java EE application server. If you are
* using connection pooling in standalone Java code, you
* will have to create/configure datasources using whatever
* mechanisms your particular connection pooling library
* provides.
*/
InitialContext ctx = new InitialContext();
/*
* Lookup the DataSource, which will be backed by a pool
* that the application server provides. DataSource instances
* are also a good candidate for caching as an instance
* variable, as JNDI lookups can be expensive as well.
*/
DataSource ds =
(DataSource)ctx.lookup("java:comp/env/jdbc/MySQLDB");
/*
*Remaining code here...
*/
}
Following up on BalusC's link, I can confirm that we could do the same thing when using Restlet. However, as per the code in the example to get the config instance you are passing in the ServletContext as an argument. Restlet is like 'another' framework that uses Servlets as an adapter to configure itself. So it'll be tricky to pass the ServletContext as an argument from somewhere else in the code (Restlet uses it's own Context object which is conceptually similar to ServletContext)
For my case a static method returning the cached datasource seems to be 'clean enough' but there could be other design/organization approaches.