Best Practice: Avoiding or minimizing synchronization in servlets
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的更多相关文章
- Java性能提示(全)
http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.htmlComparing the performance of LinkedLi ...
- LVM实践
[root@ftp:/root] > fdisk -l Disk /dev/sda: 53.7 GB, 53687091200 bytes, 104857600 sectors Units = ...
- 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 ...
- Write thread-safe servlets [reproduced]
If you write Web applications in Java, the servlet is your best friend. Whether you write Java Serve ...
- Designing IP-Based Video Conferencing Systems: Dealing with Lip Synchronization(唇音同步)
转自:http://www.ciscopress.com/articles/article.asp?p=705533&seqNum=6 Correlating Timebases Using ...
- Java theory and practice
This content is part of the series: Java theory and practice A brief history of garbage collection A ...
- Synchronization in Delphi TThread class : Synchronize, Queue
http://embarcadero.newsgroups.archived.at/public.delphi.rtl/201112/1112035763.html > Hi,>> ...
- 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- ...
- 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 ...
随机推荐
- css3 translate属性
translate(x,y)水平方向和垂直方向同时移动(也就是X轴和Y轴同时移动):translateX(x)仅水平方向移动(X轴移动):translateY(Y)仅垂直方向移动(Y轴移动)默认都是从 ...
- saiku-添加数据源以及保证数据源的一致性
采用任何一种添加数据源的方式都不能保证数据源的一致和完整,所以需要两种结合来管理数据源 1.通过saiku的管理台添加数据源 ① 第一种方式:schema和ds都在管理台添加 1)上传schema文件 ...
- IP的正则表达式
首先分析IP地址0-255: 0-9: [0-9]或 \d表示数字 10-99: [1-9]\d 100-199: 1/d{2} 200-249: 2[0-4]\d 250-25 ...
- hdu 3038 How Many Answers Are Wrong ( 带 权 并 查 集 )
How Many Answers Are Wrong Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Ja ...
- 解决li在ie,firefox中行高不一致问题
转载 http://www.cnblogs.com/jikey/archive/2011/11/13/2247543.html li在ie与firefox的高度是不一样的,解决办法是li font-s ...
- AP聚类算法(Affinity propagation Clustering Algorithm )
AP聚类算法是基于数据点间的"信息传递"的一种聚类算法.与k-均值算法或k中心点算法不同,AP算法不需要在运行算法之前确定聚类的个数.AP算法寻找的"examplars& ...
- Java多线程-新特性-有返回值的线程
在Java5之前,线程是没有返回值的,常常为了“有”返回值,破费周折,而且代码很不好写.或者干脆绕过这道坎,走别的路了. 现在Java终于有可返回值的任务(也可以叫做线程)了. 可返回值的任务必须实现 ...
- JDE变量说明
BC Business view columns. Columns that are included in the attached business view. These columns are ...
- js 获得每周周日到周一日期
//得到每周的第一天(周日)function getFirstDateOfWeek(theDate){ var firstDateOfWeek; theDate.setDate(theDate.get ...
- 使用WebView加载HTML代码
使用EditText显示HTML字符串时,EditText不会对HTML标签进行任何解析,而是直接把所有HTML标签都显示出来-----就像用普通记事本显示一样:如果应用程序想重新对HTML字符串进行 ...