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

王朝other·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

要害字: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 与他联系。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航