DBPool.java
public class DBPool{
/**连接池容器*/
private LinkedList<Connection> pool = new LinkedList<>();
/**初始化连接池*/
public DBPool(int cap) {
if (cap > 0) {
for (int i = 0; i < cap; i ++) {
pool.addLast(SqlConnectImpl.fetchConnection());
}
}
}
}
//获取连接,最大等待时间ms(时间单位:毫秒)
public Connection getConnection(long ms) throws InterruptedException {
synchronized(pool) {
if (ms <= 0) {
while(pool.isEmpty()) {
pool.wait();
}
return pool.removeFirst();
} else {
long overTime = System.currentTimeMillis() + ms;
long remain = ms;
while (pool.isEmpty() && remain > 0) {
pool.wait(remain);
remain = overTime - System.currentTimeMillis();
}
if (!pool.isEmpty()) {
return pool.removeFirst();
}
return null;
}
}
}
//释放连接
public void releaseConnection(Connection conn) {
if (conn != null) {
synchronized (pool) {
pool.addLast(conn);
pool.notifyAll();
}
}
}
SqlConnectionImpl.java
/**数据库连接池实现类*/
public class SqlConnectImpl implements Connection {
/**
* 拿一个数据库连接
* @return
*/
public static final Connection fetchConnection() {
return new SqlConnectImpl();
}
//实现的Connection接口就不列出来了
}