Posted by:bruce
Posted on:2003-11-01 00:11
在 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
}
}
}