Summary
Minimizes the use of synchronization in the servlet. Because the servlet is multi-threaded, synchronization of the primary code path can seriously and severely adversely affect performance.
Suggestions
The servlet is multithreaded. Servlet-based applications must recognize and handle this appropriately. If the application has many large sections of code that are synchronized, the application is actually single-threaded and the throughput is significantly reduced.
Synchronization is the best choice in the servlet, however, if the application design cannot avoid synchronization, use lock object (lock objects) and lock the code path with the least availability. Do not synchronize the Servlet's service method or Doget and DoPost methods. These methods are the primary code path. Synchronizing these methods or any of these servlet methods will lock the entire servlet instance. The following code shows an example of using the lock object to protect the servlet instance variable numberofrows.
Minimum Sync code path
public class bpallbadthingsservletsv1b extends HttpServlet
{
private int numberofrows = 0;
Private Javax.sql.DataSource ds = null;
Private Object LockObject = new Object ();
public void doget (HttpServletRequest request, httpservletresponse response)
throws Servletexception , IOException
{
Connection conn = null;
ResultSet rs = null;
PreparedStatement pstmt = null;
int startingrows = 0;
Synchronize (lockobject) {
Startingrows = numberofrows;
Try
{
String employeeinformation = null;
conn = Ds.getconnection ("Db2admin", "db2admin");
Pstmt = conn.preparestatement
("SELECT * from Db2admin.employee");
rs = Pstmt.executequery ();
}
catch (Exception es)
{
//Error handling code HEre
}
}
}