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. 离线网页制作器(beta1.0)

    package hhuarongdao; /* *使用方法: 先选择保存路径,然后输入相应的网址, *然后会得到那个网页的离线版的 内容 * */ import java.awt.BorderLayo ...

  2. MVC中使用HTML Helper类扩展HTML控件

    文章摘自:http://www.cnblogs.com/zhangziqiu/archive/2009/03/18/1415005.html MVC在view页面,经常需要用到很多封装好的HTML控件 ...

  3. perl 正则匹配代码

    36     chomp $line; 37     my @vec = split /\t/, $line; 38     my @vec2 = ($vec[1]=~/[a-z]+/g); 39   ...

  4. Windows Store App 应用设置存储

    应用设置存储主要分为本地存储和漫游存储两种方式.本地存储是指将应用的设置信息存储在本地存储空间中,而漫游存储则是指将应用的设置信息存储在网络服务器中,相对于本地存储而言,漫游存储支持多台设备之间的应用 ...

  5. MongoDB replicaSet

    MongoDB 的replication机制除了最普通的Master/Slave模式之外,更强大的就是其支持自动故障转移的Replica Sets模式了.相对于其问题多多的auto-sharding机 ...

  6. 重点关注之OData with List

    OData是什么 官方解释:The Open Data Protocol (OData) is a data access protocol for the web. OData provides a ...

  7. Windows API调用外部程序

    要在应用程序中启动其他的应用程序,有3个函数可以使用,下面我一一说说他们(我以打开D:\Program Files\zeecalls\目录下的zeecalls.exe应用程序为例): 1.Winexe ...

  8. RM报表 文本框 自动换行 相关代码

    procedure TRMCustomMemoView.WrapMemo1(aAddChar: Boolean); var lCurHeight, lOneLineHeight, lMaxWidth: ...

  9. Keil 4.0 生成bin文件

    在菜单:Flash /configuare falsh tools ... option for Tatget '项目' /User中:在Run User Programs After Build/R ...

  10. cvWaitKey

    OpenCV中的一个函数 函数原型为: C++: int waitKey(int delay=0) Python: cv2.waitKey([delay]) → retval C: int cvWai ...