程序设计中,通常会涉及各类池,如锁池,等待池,jdbc数据库连接池。
下面以数据库连接池来展示各种池的实现:
1.利用LinkedList数据结构来来保存池中的应用对象。
2.为了保证并发请求对池的访问,对池设置同步操作了。
3.对池的容量进行设定。兼容以前池中对象的操作方式,满足池中对象以前的使用方式,但又不影响到池,通过代理实现。
4. 组合优先于继承。
public class MyDataSource {
private static String url = "jdbc:mysql://localhost:3306/jdbc";
private static String user = "root";
private static String password = "";
private static int initCount = 5;
private static int maxCount = 10;
private int currentCount = 0;
LinkedList<Connection> connectionsPool = new LinkedList<Connection>();
public MyDataSource() {
try {
for (int i = 0; i < initCount; i++) {
this.connectionsPool.addLast(this.createConnection());
this.currentCount++;
}
} catch (SQLException e) {
throw new ExceptionInInitializerError(e);
}
}
public Connection getConnection() throws SQLException {
synchronized (connectionsPool) {
if (this.connectionsPool.size() > 0)
return this.connectionsPool.removeFirst();
if (this.currentCount < maxCount) {
this.currentCount++;
return this.createConnection();
}
throw new SQLException("已没有链接");
}
}
public void free(Connection conn) {
this.connectionsPool.addLast(conn);
}
private Connection createConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
}