Introduction

Minimize the use of synchronization in servlets. Because servlets are multi-threaded, synchronization of the major code path can seriously and adversely affect performance.

Recommendation

Servlets are multithreaded. Servlet-based applications have to recognize and handle this appropriately. If large sections of code are synchronized, an application effectively becomes single threaded, and throughput decreases dramatically.

No synchronization in servlets presents the best option, however, if the application design cannot avoid synchronization, then use a "Lock Object" and lock the smallest possible code path. Do not synchronize the servlet service method or the doGet and doPost methods. These methods are the major code paths. Synchronizing these methods or any of the servlet methods will lock the entire servlet instance. The following code shows an example using a "Lock Object" to protect the servlet instance variable numberOfRows.

Minimum synchronized code path

ublic 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.prepareStatemtn
("select * from db2admin.employee");
rs = pStmt.executeQuery();
}
catch (Exception es)
{
// Error handling code here
}
}
}

Alternative

The following code shows how the major code path is synchronized to protect a servlet instance variable called numberOfRows.

Using javax.servlet.SingleThreadModel is yet another way to protect servlet instance variables, but this should be avoided as well.

Figure 1 shows the performance impact of Synchronization

Locking the major code path: excessive synchronization

public class BpAllBadThingsServletsV1a extends HttpServlet
{
private int numberOfRows = 0;
private javax.sql.DataSource ds = null; public void doGet(HttpServletRequest request, HttpServletResponse response(
throws ServletException, IOException
{
Connection conn = null;
ResultSet rs = null;
PreparedStatement pStmt = null;
int startingRows; try
{
synchronized(this) // Locks out Most of the Servlet Processing
{
startingRows = numberOfRows;
String employeeInformation = null;
conn = ds.getConnection("db2admin", "db2admin");
pStmt = conn.prepareStatemtn
("select * from db2admin.employee");
rs = pStmt.executeQuery();
}
}
catch (Exception es)
{
// Error handling code here
}
}
}

  

  

Best Practice: Avoiding or minimizing synchronization in servlets的更多相关文章

  1. Java性能提示(全)

    http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.htmlComparing the performance of LinkedLi ...

  2. LVM实践

    [root@ftp:/root] > fdisk -l Disk /dev/sda: 53.7 GB, 53687091200 bytes, 104857600 sectors Units = ...

  3. Java Concurrency In Practice -Chapter 2 Thread Safety

    Writing thread-safe code is managing access to state and in particular to shared, mutable state. Obj ...

  4. Write thread-safe servlets [reproduced]

    If you write Web applications in Java, the servlet is your best friend. Whether you write Java Serve ...

  5. Designing IP-Based Video Conferencing Systems: Dealing with Lip Synchronization(唇音同步)

    转自:http://www.ciscopress.com/articles/article.asp?p=705533&seqNum=6 Correlating Timebases Using ...

  6. Java theory and practice

    This content is part of the series: Java theory and practice A brief history of garbage collection A ...

  7. Synchronization in Delphi TThread class : Synchronize, Queue

    http://embarcadero.newsgroups.archived.at/public.delphi.rtl/201112/1112035763.html > Hi,>> ...

  8. the field is sometimes used inside synchronized block and sometimes used without synchronization

    http://stackoverflow.com/questions/28715625/is-it-safe-to-use-field-inside-and-outside-synchronized- ...

  9. Java theory and practice: Thread pools and work queues--reference

    Why thread pools? Many server applications, such as Web servers, database servers, file servers, or ...

随机推荐

  1. Android系统启动过程-uBoot+Kernel+Android

    摘要:本文是参考大量网上资源在结合自己查看源代码总结出来的,让自己同时也让大家加深对Android系统启动过程有一个更加深入的了解!再次强调,本文的大多数功劳应归功于那些原创者们,同时一些必要的参考链 ...

  2. 用过的正则(更新ing)

    http://www.debuggex.com/   这个很好用20120912 //十六进制颜色值的正则表达式 var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6} ...

  3. [转]用Python读写Excel文件

    [转]用Python读写Excel文件   转自:http://www.gocalf.com/blog/python-read-write-excel.html#xlrd-xlwt 虽然天天跟数据打交 ...

  4. NPOI相关

    总结一下工作中遇到的NPOI以及在ASP.NET MVC中的使用 http://www.cnblogs.com/fenglingyi/p/4750323.html

  5. 腾讯大规模Hadoop集群实践 [转程序员杂志]

    TDW(Tencent distributed Data Warehouse,腾讯分布式数据仓库)基于开源软件Hadoop和Hive进行构建,打破了传统数据仓库不能线性扩展.可控性差的局限,并且根据腾 ...

  6. WCF如何通过契约加编码方式调用

    WCF采用基于契约的服务调用方法,通过System.ServiceModel.ChannelFactory<TChannel>直接创建服务代理对象. 创建服务代理 public stati ...

  7. IBatis.net动态SQL语句(六)

    在学习动态SQL语句之前,首先必须对条件查询有一定了解,先来学习如何向IBatis.Net的映射文件里传入参数. 一.条件查询 1.传递单个参数 如根据Id查询: <select id=&quo ...

  8. not jquery

    var divs = document.querySelectorAll('div'); [].forEach.call(divs, function(div) { // do whatever di ...

  9. SpinEdit

    用code给value赋值会触发 change事件

  10. IT公司100题-15-求二元查找树的镜像

    问题描述: 输入一颗二元查找树,将该树转换为它的镜像树,即对每一个节点,互换左右子树.   例如输入:   6/    \4     12/ \   /   \2  5 8   16 输出:   6/ ...