📄 connectionpool.java
字号:
package pooling;
import java.sql.*;
import java.util.*;
public class ConnectionPool {
private Vector connections;
private String url, username, password;
private boolean inUse[];
final private int poolsize = 10;
// /////////////////////////////////////////////////////////////////
// Name ConnectionPool
// Description Constructor
// /////////////////////////////////////////////////////////////////
public ConnectionPool(String url, String username,
String password) throws SQLException {
this.url = url;
this.username = username;
this.password = password;
connections = new Vector(poolsize);
inUse = new boolean[poolsize];
try {
// Load the driver
Class.forName("COM.cloudscape.core.JDBCDriver").newInstance();
// Setup our pool of sources
SetupConnectionsPool();
} catch (Exception e) {
e.printStackTrace();
}
}
// /////////////////////////////////////////////////////////////////
// Name SetupConnectonsPool
// Description Pre-Create our pool of connections
// /////////////////////////////////////////////////////////////////
private void SetupConnectionsPool() throws SQLException {
for (int i = 0; i < poolsize; i++) {
Connection conn = DriverManager.getConnection(url, username,
password);
connections.addElement(conn);
inUse[i] = false;
}
}
// /////////////////////////////////////////////////////////////////
// Name freeConnection
// Description Release resource
// /////////////////////////////////////////////////////////////////
public void freeConnection(int connectionIdx) {
inUse[connectionIdx] = false;
}
// /////////////////////////////////////////////////////////////////
// Name getConnection
// Description Obtain a connection from the pool (if available)
// /////////////////////////////////////////////////////////////////
public Connection getConnection() {
Connection c = null;
for (int idx = 0; idx < connections.size(); idx++) {
if (inUse[idx] == false) {
c = (Connection) connections.elementAt(idx);
inUse[idx] = true;
}
}
return c;
}
// /////////////////////////////////////////////////////////////////
// Name dumpConnectionStatus
// Description Dump the status of pool and connections
// /////////////////////////////////////////////////////////////////
public void dumpConnectionStatus() {
System.out.println("\nConnection Pool Status");
System.out.println("\nPool Size is " + connections.size());
for (int i = 0; i < connections.size(); i++) {
System.out.println("Pool Index [" + i + "] In Use status = "
+ inUse[i]);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -