我正在尝试使用我自己的连接池形式来处理数据库连接但是由于某种原因它似乎是阻塞的,即使我使用了一个帖子,有人可以帮助我指出我的错误。
这是带有线程类的servlet代码。
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// PrintWriter out = response.getWriter();
OutputStream ostream = response.getOutputStream();
PrintStream out = new PrintStream(ostream, true, "UTF8");
try {
response.setContentType("text/html");
String test = request.getParameter("test");
System.out.println("Received text: " + test);
if(test.equals("free"))
{
for (int i = 0; i < list.size(); i++) {
dbcm.freeConnection(list.get(i));
}
list.clear();
}else
{
GetConnThread gct = new GetConnThread(test, dbcm);
gct.start();
}
} catch (Exception e) {
e.printStackTrace();
out.println("fail");
} finally {
out.close();
}
}
private class GetConnThread extends Thread
{
private String test;
private DBConnectionManager dbcm;
public GetConnThread(String test, DBConnectionManager dbcm)
{
this.test = test;
this.dbcm = dbcm;
}
public void run()
{
try {
Connection conn = dbcm.getConnection(test);
list.add(conn);
System.out.println(conn);
System.out.println("list size: " + list.size());
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是DBConnectionManager中的getConnection方法
public synchronized Connection getConnection(String test) throws CGFatalException {
Connection con = null;
boolean connectionIsValid = false;
if (freeConnections.size() > 0) {
con = (Connection) freeConnections.firstElement();
freeConnections.removeElementAt(0);
connectionIsValid = validateConnection(con);
if (connectionIsValid == false) {
con = getConnection(test);
}
} else if (maxConn == 0 || checkedOut < maxConn) {
con = newConnection();
connectionIsValid = validateConnection(con);
if (connectionIsValid == false) {
con = getConnection(test);
}
}else
{
System.out.println("No available connections for " + test + ", try again in 2 secs....");
try {
Thread.sleep(2000);
con = getConnection(test);
} catch (Exception e) {
e.printStackTrace();
}
}
if (con != null && connectionIsValid == true) {
checkedOut++;
}
System.out.println("checkedOut: " + checkedOut);
System.out.println("maxConn: " + maxConn);
return con;
}
我将最大连接数设置为2,所以在我第三次调用servlet之后它转到这行代码:
System.out.println("No available connections for " + test + ", try again in 2 secs....");
当我第四次打电话时,我期待
System.out.println("No available connections for " + test + ", try again in 2 secs....");
作为一个单独的线程开始,但是第三个调用似乎阻止它,无限循环是预期的,因为我希望通过“免费”调用来清除连接,一切都恢复正常。
答案 0 :(得分:2)
您的getConnection方法已同步。
,每个其他线程都会阻止该锁获取,直到“第三个”请求成功获得连接为止。