AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > JSP

Servlet中jdbc应用高级篇(三)

51自学网 http://www.51zixue.net



  第二个getConnection()方法带有一个超时参数 timeout,当该参数指定的毫秒数表示客户愿意为一个连接等待的时间。这个方法调用前一个方法。


public synchronized Connection getConnection(long timeout) {

long startTime = new Date().getTime();

Connection con;

while ((con = getConnection()) == null) {

try {

wait(timeout);

}

catch (InterruptedException e) {}

if ((new Date().getTime() - startTime) >= timeout) {

// Timeout has expired

return null;

}

}

return con;

}


  局部变量startTime初始化当前的时间。一个while循环首先尝试获得一个连接,如果失败,wait()函数被调用来等待需要的时间。后面会看到,Wait()函数会在另一个进程调用notify()或者notifyAll()时返回,或者等到时间流逝完毕。为了确定wait()是因为何种原因返回,我们用开始时间减去当前时间,检查是否大于timeout。如果结果大于timeout,返回null,否则,在此调用getConnection()函数。


  四、将一个连接返回池中


  DBConnectionPool类中有一个freeConnection方法以返回的连接作为参数,将连接返回连接池。


public synchronized void freeConnection(Connection con) {

// Put the connection at the end of the Vector

freeConnections.addElement(con);

checkedOut--;

notifyAll();

}

  连接被加在freeConnections向量的最后,占用的连接数减1,调用notifyAll()函数通知其他等待的客户现在有了一个连接。

五、关闭


  大多数servlet引擎提供完整的关闭方法。数据库连接池需要得到通知以正确地关闭所有的连接。DBConnectionManager负责协调关闭事件,但连接由各个连接池自己负责关闭。方法relase()由DBConnectionManager调用。
public synchronized void release() {

Enumeration allConnections = freeConnections.elements();

while (allConnections.hasMoreElements()) {

Connection con = (Connection) allConnections.nextElement();

try {

con.close();

log("Closed connection for pool " + name);

}

catch (SQLException e) {

log(e, "Can not close connection for pool " + name);

}

}

freeConnections.removeAllElements();

}

本方法遍历freeConnections向量以关闭所有的连接。

 
 

上一篇:Servlet中jdbc应用高级篇(四)  下一篇:JBuilder2005实战JSP之创建数据库表