服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

最佳实践:避免或最小化 servlet 中的同步


  关键字:servlet,jsp

摘要

最小化 servlet 中同步的使用。因为 servlet 是多线程的,主要代码路径的同步会严重地且极为有害地影响性能。

建议

servlet 是多线程的。基于 servlet 的应用程序必须认识并适当地处理这一点。如果应用程序有很多大段的代码是同步的,那么这个应用程序实际上就变成单线程的,而且吞吐量会显著下降。

在 servlet 中不出现同步是最佳选择,然而,如果应用程序设计无法避免同步,那么请使用“锁对象(lock object)”并且锁定可用性最小的代码路径。请不要同步 servlet 的 service 方法或 doget 以及 dopost 方法。这些方法是主要代码路径。同步这些方法或任何这些 servlet 方法之一将锁定整个 servlet 实例。下列代码显示了一个使用“锁对象”来保护 servlet 实例变量 numberofrows 的示例。

最小同步代码路径

public 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.preparestatement
("select * from db2admin.employee");
rs = pstmt.executequery();
}
catch (exception es)
{
// error handling code here
}
}
}

应被取代的方法

以下代码显示如何同步主要代码路径来保护称为 numberofrows 的 servlet 实例变量。

使用 javax.servlet.singlethreadmodel 仍是另一种保护 servlet 实例变量的方法,但最好还是避免使用这种方法。

下面的图 1 显示了同步的性能影响

锁定主要代码路径:过度的同步

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.preparestatement
("select * from db2admin.employee");
rs = pstmt.executequery();
}
}
catch (exception es)
{
// error handling code here
}
}
}

参考资料

websphere application server development best practices for performance and scalability
作者

harvey w. gunther 是 ibm 在北卡罗莱纳州 raleigh 的 websphere 产品开发小组中的资深性能分析师。可以通过 hgunther@us.ibm.com 与他联系。

扫描关注微信公众号