Avoid or minimize synchronization in the servlet

Source: Internet
Author: User
Tags error handling

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
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.