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 ...
随机推荐
- PLI与Pillow
PIL概念 XXXXX 注意 PIL不兼容setuptools. Pillow概念 Pillow(PIL fork)是用来处理raster图像的Python图像库,即像素数据的矩阵. 查阅PIL的 ...
- 函数内部的函数中的this都是指向window
刚看到一个问题关于this的, var name="the window"; var object={ name:"silence", packname:fun ...
- 关于WorkFlow的使用以及例子
近期做项目,项目需要用到工作流方面的技术,我在这里与大家分享一个workFlow学习的地址,共大家学习. http://www.cnblogs.com/foundation/ 各文档的说明: F资料├ ...
- Qt之模拟时钟
简述 Qt自带的示例中有一个是关于时钟,演示了如何用QPainter的转换和缩放特性来绘制自定义部件. 其中主要包含了时针.分针的绘制,并不包含秒针.下面,我们在原示例的基础上进行扩展. 简述 实现方 ...
- hdu----(3065)病毒侵袭持续中(AC自动机)
病毒侵袭持续中 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Sub ...
- SQL Server数据库(SQL Sever语言 CRUD)
使用SQL Sever语言进行数据库的操作 常用关键字identity 自增长primary key 主键unique 唯一键not null 非空references 外键(引用) 在使用查询操作数 ...
- js基础之弹性运动(四)
一.滑动菜单.图片 var iSpeed=0;var left=0;function startMove(obj,iTarg){ clearInterval(obj.timer);//记得先关定时器 ...
- USB鼠标按键驱动
现象:把USB设备接到PC 1. 右下角弹出"发现android phone" 2. 跳出一个对话框,提示你安装驱动程序 问1. 既然还没有"驱动程序",为何能 ...
- 采用EntLib5.0(Unity+Interception+Caching)实现项目中可用的Caching机制
看了园子里很多介绍Caching的文章,多数都只介绍基本机制,对于Cache更新和依赖部分,更是只简单的实现ICacheItemRefreshAction接口,这在实际项目中是远远不够的.实际项目中, ...
- android listview综合使用示例_结合数据库操作和listitem单击长按等事件处理
本示例说明: 1.自定义listview条目样式,自定义listview显示列数的多少,灵活与数据库中字段绑定. 2.实现对DB的增删改查,并且操作后listview自动刷新. 3.响应用户操作点击事 ...