WebReference.com - Chapter 16 of Java Servlets Developer's Guide, from Osborne/McGraw-Hill (3/4) | WebReference

WebReference.com - Chapter 16 of Java Servlets Developer's Guide, from Osborne/McGraw-Hill (3/4)

To page 1To page 2current pageTo page 4
[previous] [next]

Java Servlets Developer's Guide

Use a Connection Pool

Chapter 9 covered the benefits of using a JDBC connection pool, but it deserves another mention. I cannot stress enough how performance-critical it is to use a pool of JDBC connections to provide the response times that your users will demand.

You should find that using a connection pool will take your average connection times from seconds to milliseconds.

Use a PreparedStatement

When using JDBC it is tempting to always use a java.sql.Statement object to execute your queries. While this is easy, it may not be the most efficient way to query your database. If you are executing the same query multiple times, you may want to consider using a java.sql.PreparedStatement instead. By using a PreparedStatement the database engine will only have to evaluate the SQL statement you are using once. Evaluating a SQL statement can tend to be expensive. The use of a PreparedStatement is covered in Chapter 9.

Cache Expensive Objects

In the early days of Java, it was advantageous to cache just about every kind of object in an effort to eliminate object creation altogether. With today's Virtual Machines, object creation is not nearly as taxing on the system, and the additional overhead of maintaining a cache may outweigh the benefits of avoiding another object instantiation. There are some types of objects, however, that may prove to be expensive to instantiate. Certainly, a JDBC Connection object classifies as being expensive to create, but there are many other objects that you may want to consider caching. Which ones? This is where some time with a code profiler comes in handy. Most of the time, these objects will be ones that you have developed. I would suggest taking a hard look to see what is going on in the constructors of your objects; if lots of other objects are being created during construction, your single object may actually result in many smaller objects being created as well. If this is the case, you may be better off creating a cache (or pool) of these objects, much like we did in Chapter 9 for JDBC connections.

One simple technique that I like to use is to create a java.util.Stack to serve as a cache. When you need an object, pop() one off the Stack; if the Stack is empty, create a new instance of the object you need. When you are finished with the object, push() it back onto the Stack. The Stack will grow as the number of concurrent users increases. The technique is shown in the following servlet, which uses a Stack to cache SimpleDateFormat objects (which are expensive to instantiate and are not thread-safe):

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Stack;
import java.util.Date;
import java.util.EmptyStackException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
/**
 * Simple servlet that gets the current date and time. Uses a simple
 * cache (a Stack) for the Date objects.
 */
public class GetDate
        extends HttpServlet
{
    // The cache of Date objects
    Stack dateCache = new Stack();
    public void doGet(HttpServletRequest req,
                      HttpServletResponse resp)
        throws ServletException, IOException
    {
        // Get an output stream that takes into account
        // the proper character encoding
        PrintWriter out = resp.getWriter();
        // Print the HTML header to the output stream
        out.println("<html>");
        out.println("<head>");
        out.println("<title>The Server Date</title>");
        out.println("</head>");
        out.println("<h2>");
        // Get a DateFormat from the cache
        DateFormat dateFormat = getDateFormat();
        String now = dateFormat.format(new Date());
        out.println("The date/time on the server is: " + now);
        out.println("<br>");
        // We're done with the DateFormat. Put it back
        putDateFormat(dateFormat);
        // Wrap up
        out.println("</html>");
        out.flush();
    }
    /**
     * Get a DateFormat object from the cache. If one does not
     * exist, create a new one
     */
    public DateFormat getDateFormat()
    {
        DateFormat dateFormat = null;
        try
        {
            dateFormat = (DateFormat) dateCache.pop();
        }
        catch (EmptyStackException ex)
        {
            // Create a new Date object if the stack is empty
            dateFormat = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss z");
        }
        return dateFormat;
    }
    /**
     * Puts the DateFormat object back into the cache
     */
    public void putDateFormat(DateFormat dateFormat)
    {
        dateCache.push(dateFormat);
    }
}

To page 1To page 2current pageTo page 4
[previous] [next]

Created: July 31, 2002
Revised: July 31, 2002

URL: http://webreference.com/programming/java/servletsguide/3.html