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. Linux编程

    头文件一般位于usr/include目录下,各个子类的头文件位于include子目录下 不知道某个“库函数”需要哪些头文件,使用“man 函数”即可查看 sys/types.h  基本系统数据类型 s ...

  2. 189. Rotate Array -- 将数组前一半移到后一半

    Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array ...

  3. C#类和成员的修饰符

    C#中public.private.protected.internal.protected internal & (2010-09-22 13:33:45)转载 标签: 杂谈 分类: C# ...

  4. 如何查看,关闭和开启selinux

    以下介绍一下SELinux相关的工具/usr/bin/setenforce 修改SELinux的实时运行模式setenforce 1 设置SELinux 成为enforcing模式setenforce ...

  5. BZOJ2490 Zombie’s Treasure Chest

    如果n = lcm(s1, s2),那么就可以直接得到maxV = (v / s1 * v1, v / s2 *v2) 然后还剩下一点体积我们暴力枚举用s1的量,让s1为max(s1, s2)可以减少 ...

  6. Java如何将控制台上的结果保存到文件

    无论是二进制数据还是字符数据(文本数据),都可以用文件输出流java.io.FileOutputStream,以字节流的方式保存到指定文件. package test; import java.io. ...

  7. Octopus系列之开发过程各个技术点

    自定义了页面周期 使用唯一的一个VelocityEngine全局的静态实例,优化了小泥鳅blog中每次请求都要创建VelocityEngine实例对象,减少了对象的开销 通过UA判断请求来自的设备,从 ...

  8. fwite写入文件

    用双引号(")定义字符串,PHP 懂得更多特殊字符的转义序列: 转移序列 说明 \n 换行 \r 回车 \t 水平制表符 \[/td> 反斜线 \$ 美元符号 \" 双引号 ...

  9. Linux 服务器安全技巧

    毋庸置疑,对于系统管理员,提高服务器的安全性是最重要的事情之一.因此,也就有了许多针对这个话题而生的文章.博客和论坛帖子. 一台服务器由大量功能各异的部件组成,这一点使得很难根据每个人的需求去提供定制 ...

  10. 各种常用函数 (SQL)

    数学函数 1.绝对值 S:select abs(-1) value O:select abs(-1) value from dual   2.取整(大) S:select ceiling(-1.001 ...