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. 使用Visual Studio 2013进行单元测试--初级篇

    1.打开VS2013 --> 新建一个项目.这里我们默认创建一个控制台项目.取名为UnitTestDemo 2.在解决方案里面新增一个单元测试项目.取名为UnitTestDemoTest 创建完 ...

  2. R语言与正态性检验

    1.Kolmogorov-Smirnov正态性检验 Kolmogorov-Smirnov是比较一个频率分布f(x)与理论分布g(x)或者两个观测值分布的检验方法,若两者间的差距很小,则推论该样本取自某 ...

  3. (01)odoo8.0_Ubuntu14.04源码安装

    作者:陈伟明联系 :  QQ 942923305 | 微信 toby942923305E-mail: toby2chen@hotmail.com============================ ...

  4. SAP smartforms之Zebra print control language

    因为在做个小标签的时候需要将部分字符旋转180度,在scn上找了很久也发布了自己的提问,不过最终的结果却不尽人意.Rotated text in smartforms need use the PCL ...

  5. java 中遇到的问题及解决方法

    1.经常发现明明导入jar包,还是会报java.lang.NoSuchMethodError和java.lang.NoClassDefFoundError 试试网上的各种方法,包括重新导入jar包.重 ...

  6. 为什么 Node.js 这么火,而同样异步模式 Python 框架 Twisted 却十几年一直不温不火?

    twisted是一个强大的异步网络框架,应用的面也非常广,但是没有这几年才出现的Node.js火,社区.文档也是很少可怜我觉得二者其实在本质上差不多,而且python使用起来还是比较容易一些的 匿名用 ...

  7. 重点关注之自定义序列化方式(Protobuf和Msgpack)

    除了默认的JSON和XML序列化器外,如果想使用其它格式的(比如二进制)序列化器,也是可以的.比如著名的Protobuf和Msgpack,它们都是二进制的序列化器,特点是速度快,体积小.使用方法如下. ...

  8. QQ注册

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  9. php 采集类snoopy http://www.jb51.net/article/27568.htm | cURL、file_get_contents、snoopy.class.php 优缺点

    Snoopy是一个php类,用来模拟浏览器的功能,可以获取网页内容,发送表单. Snoopy的特点: 1.抓取网页的内容 fetch 2.抓取网页的文本内容 (去除HTML标签) fetchtext ...

  10. Redis系列-存储篇set主要操作函数小结

    最近,总是以“太忙“为借口,很久没有blog了,凡事贵在恒,希望我能够坚持不懈,毕竟在blog的时候,也能提升自己.废话不说了,直奔主题”set“ redis set 是string类型对象的无序集合 ...