If a servlet has a one-time and expensive operation, incorrect coding techniques can lead to degraded performance. Use the HttpServlet init method to perform one-time expensive operations, such as acquiring thread-safe resource acquisition mechanisms. The overall performance impact significantly reduces when using the HttpServlet init method as the init method is only called once when the servlet is loaded.
This best practice applies to the following product, version, and platform:
- WebSphere Application Server Base, all platforms, versions 3.0.2.x, 3.5.x, 4.0
Because the Servlet init() method is invoked when the servlet instance is loaded, it is the perfect location to carry out expensive operations that need only be performed during initialization. By definition, the init() method is thread-safe. The results of operations in the HttpServlet.init() method can be cached safely in servlet instance variables, which become read-only in the servlet service method.
The following shows the Servlet init method used for obtaining and caching the JDBC DataSource. One effective use of the Servlet init method is the creation and caching of thread-safe resource acquisition mechanisms, such as JDBC DataSources, EJB Homes, and Web Services SOAP Mapping Registry.
Using the Servlet.init method to acquire JDBC DataSource
public class BpAllBadThingsServletV5 extends HttpServlet
{
// Caching the DataSource - It is obtained in the Servlet.init() method
private javax.sql.DataSource ds = null;
// This Happens Once and is Reused
public void init(ServletConfig config) throws ServletException
{
super.init(config);
Context ctx = null;
try
{
java.util.Hashtable env = new java.util.Hashtable();
env.put(Contex.INITIAL_CONTEXT_FACTORY,
"com.ibm.ejs.ns.jndi.CNInitialContextFactory");
ctx = new InitialContext(env);
ds = (javax.sql.DataSource)ctx.lookup("jdbc/SAMPLE");
ctx.close();
}
catch(Exception es)
{
es.printStackTrace();
}
}
}
|
The following shows an incorrect way to acquire the JDBC DataSource. It accomplishes the same task, but the performance in this case is significantly worse, because the DataSource acquisition is done every time the doGet method is invoked.
Wrong way to acquire a data source
public class BpAllBadThingsServletV2a extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Connection conn = null;
ResultSet rs = null;
PreparedStatement pStmt = null;
javax.sql.DataSource ds = null
try
{
java.util.Hashtable env = new java.util.Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.ibm.ejs.ns.jndi.CNInitialContextFactory");
ctx = new InitialContext(env);
ds = (DataSource)ctx.lookup("jdbc/SAMPLE");
ctx.close();
conn = ds.getConnection("db2admin", "db2admin");
pStmt = conn.prepareStatement
("select * from hgunther.employee");
rs = pStmt.executeQuery
}
catch(Exception(es)
{
es.printStackTrace();
}
}
}
|




