Servlets JSP Performance Tuning Tips


Servlets JSP Performance

The following pages describe performance-tuning techniques (PTT) for developing high performance and scalable JSP (JavaServer Pages) pages and servlets. This means building applications that are reasonably and consistently fair.

1. Use the HttpServlet init() method for caching data

The server calls the servlet’s init() method after the server constructs the servlet instance and before the servlet handles any requests. It is called only once in a servlet’s lifetime. init() can be used to improve performance by caching the static data and/or completing the expensive operations that need to be performed only during initialization.

For example, it is a best practice to use JDBC (Java Database Connectivity) connection pooling, which involves the use of the javax.sql.DataSource interface. DataSource is obtained from the JNDI (Java Naming and Directory Interface) tree. Performing the JNDI lookup for DataSource for every SQL call is expensive and severely affects an application’s performance. Servlet’s init() method should be used to acquire DataSource and cache it for later reuse:

public class ControllerServlet extends HttpServlet
{
  private javax.sql.DataSource testDS = null;
  public void init(ServletConfig config) throws ServletException
  {
    super.init(config);   
    Context ctx  = null;
    try
    { 
      ctx = new InitialContext();
      testDS = (javax.sql.DataSource)ctx.lookup("jdbc/testDS");
    }
    catch(NamingException ne)
    {
      ne.printStackTrace();              
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
   }
   public javax.sql.DataSource getTestDS()
   {
     return testDS;
   }
   ...
   ...   
}

1.1 Another functionality (Use init() for static data)

Servlet is loaded into the memory by Servlet Engine (container) and calls init() method on first request and then onwards only service() method is called for every other request by creating a separate thread for each request and finally destroy() method is called when the Servlet is removed by the Servlet Engine.

The default mechanism of a Servlet Engine is to load a Servlet in multithreaded environment. In this environment, a Servlet init() method is called only once in its life time. You can improve performance using init() method. You can use this method to cache static data.

Generally a Servlet generates dynamic data and static data. Programmers often make a mistake by creating both dynamic and static data from service() method. Obviously there is a reason to create dynamic data because of its nature but there is no need to create static data every time for every request in service() method. For example, normally you would write a Servlet like this

public void service(HttpServletRequest req, HttpServletRespnse res) throws ServletException,IOException 
{
  res.setContentType(“text/html”);
  Printwriter out = req.getWriter();
  out.print("”);
  out.print("Hello world”);
  out.print(“”);
                                     // send the dynamic data here
  out.print(“”);
  out.print("”);
}

Here you are generating both static data and dynamic data. Instead you can modify the code as shown below

public class servlet extends HttpServlet 
{
  byte[] header;     
  byte[] navbar;     
  byte[] footer;   
  byte[] otherStaticData;

  public void init(ServletConfig config) throws ServletException
  {                          //create all the static data here
    StringBuffer sb = new StringBuffer(); // better to initialize the 				        
                             // StringBuffer with some size to improve performance
    sb.append("”);
    sb.append("Hello world”);
    sb.append(“”);
    
    header = sb.toString().getBytes();
			     // do same for navbar if its data is static
			     // do same for footer if its data is static
}
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 
{
  res.setContentType("text/html");
  ServletOutputStream out = res.getOutputStream();
  out.write(header);
  out.write(navbar);                                
 				// write dynamic data here
  out.write(footer);
}

Here the static data is created in init() method which means that it is created only once in the life time of Servlet and it is used in service() method to pass the data to the client. When you send a large amount of static data, then you can use this technique to see a considerable increase in performance.

2. Optimization techniques in service() method

When you write a service() method for your Servlet, you can improve performance by using following techniques.

1. Use StringBuffer rather than using + operator when you concatenate multiple strings
2. Use print() method instead of println() method
3. Use ServletOutputStream instead of PrintWriter
4. Initialize the PrintWriter with proper size
5. Flush the data partly
6. Minimize the amount of code in the synchronized block
7. Set the content length

3. Optimization techniques in destroy() method

The destroy() method is called only once in its servlet life time when the Servlet Engine removes from memory. It is always better to remove instance variable resources such as JDBC connections, sockets and other physical resources in this method. to avoid memory leaks.

4 thoughts on “Servlets JSP Performance Tuning Tips”

  1. Sir how can i create a “dsnless” (without going to control panel->administrative tools->Data Sources (ODBC)->system dsn and creating system dsn there) as like we do in, suppose we take a microsoft access driver..

    Connection con=DriverManager.getConnection(“jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=bank.MDB”);

    is there any code such like that to create system dsn ?

    and also sir i am eager to know why is system dsn neccessary for creating servlets ? (something i hav in mind that servlets gets executed on server so is it neccessary to create system dsn.. or some other reasons too) ?

  2. i have installed weblogic server and has set path and classpath but while i compile the program it shows an error package javax.servlet does not exit and other errors with classes from that package so please give the solution

Leave a Comment

Your email address will not be published.