对于池的概念,大家都不陌生,储存昂贵的资源,比如线程,jdbc连接,线程池有现成的,这里就不献丑了,主要写下连接池吧
连接池类
public class ConnectionPool {
private static volatile ConnectionPool connPool;
private static final String url = "jdbc:mysql://localhost:3306/java?
user=root&password=root&useUnicode=true&characterEncoding=UTF8";
private final List<Connection> list = new ArrayList<Connection>();
private final PoolState poolState = new PoolState();
private int totalConnect;
private ConnectionPool(){
}
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static ConnectionPool getInstance(){
if(connPool == null){
synchronized (ConnectionPool.class) {
if(connPool == null){
connPool = new ConnectionPool();
}
}
}
return connPool;
}
public synchronized Connection getConnection() throws Exception{
int idleConnectCount = list.size();
poolState.setIdleConnectCount(idleConnectCount);
if(idleConnectCount == 0 && totalConnect != 10){
return createConnection();
}else if(idleConnectCount != 0){
Connection connection = list.get(0);
list.remove(0);
return connection;
}else{
throw new Exception("pool is full and connect all use");
}
}
private Connection createConnection(){
Connection connection = null;
try {
connection = DriverManager.getConnection(url);
totalConnect++;
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public synchronized void release(Connection connection){
//1000毫秒
if(poolState.getIdleWorkCount(1000) > 0){
try {
connection.close();//销毁连接
totalConnect--;
} catch (SQLException e) {
e.printStackTrace();
}
}else{//缓存连接
list.add(connection);
}
}
}
连接状态类
package com.wangliyong.tool.connpool;
public class PoolState {
private long duration;
private int idleConnectCount;
public void setIdleConnectCount(int idleConnectCount) {
if(this.idleConnectCount <=2 && idleConnectCount > 2){
duration = System.currentTimeMillis();
}
this.idleConnectCount = idleConnectCount;
}
public int getIdleWorkCount(long duration) {
if ((System.currentTimeMillis() - this.duration > duration)) {
return (idleConnectCount - 2);
}
return 0;
}
}