示例




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;
RersultSer 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();

//...

解决方案
不要锁定 Servlet 的主要代码路径。将它移出 synchronized 块。

public class BpAllBadThingsServletsV1a 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;
RersultSer rs = null;
PreparedStatement pStmt = null;
int startingRows;
synchronize(lockObject) {
startingRows = numberOfRows;
}
try {
String employeeInformation = null;
conn = ds.getConnection("db2admin", "db2admin");
pStmt = conn.prepareStatement ("select * from db2admin.employee");
rs = pstmt.executeQuery();

//...