public class DBConnectionPool
{
// 默认的最大线程数阀值
private static final int DEFAULT_MAX = 10;
// 默认的最小线程数阀值
private static final int DEFAULT_MIN = 5;
// 默认的最长等待时间
private static final long DEFAULT_MAXWAIT = 10000L;
// 最大线程数阀值
private int max;
// 最先线程数阀值
private int min;
// 最长等待时间
private long maxWait;
// 当前请求获取连接数
private int currentRequest;
// 当前激活数
private int currentActive;
// 池
private List<Connection> pool;
// 连接源
private Entry source;
public DBConnectionPool(String driverName, String url, String userName, String password)
{
this(DEFAULT_MAX, DEFAULT_MIN, DEFAULT_MAXWAIT, driverName, url, userName, password);
}
public DBConnectionPool(int max, int min, long maxWait, String driverName, String url, String userName,
String password)
{
pool = new LinkedList<Connection>();
source = new Entry(driverName, url, userName, password);
this.max = max;
this.min = min;
this.maxWait = maxWait;
this.addPool(pool);
}
// 获取连接
public synchronized Connection getConnection()
{
currentRequest++;
System.out.println("currentRequest: " + currentRequest);
Connection con = null;
beginTransaction(maxWait);
if (pool.size() == 0)
{
try
{
con = source.getConnection();
currentActive++;
}
catch (Exception e)
{
e.printStackTrace();
}
}
else if (pool.size() < min)
{
con = pool.remove(0);
System.out.println("12312312");
currentActive++;
}
else
{
con = pool.remove(0);
currentActive++;
}
System.out.println("currentActive : " + currentActive);
return con;
}
// 判断是否超过最大数,超过等待,没有超过就唤醒
private void beginTransaction(long maxWait)
{
if (currentRequest > max)
{
try
{
if (maxWait > 0)
this.wait(maxWait);
else
{
this.wait(DEFAULT_MAXWAIT);
}
if (currentRequest > max)
{
throw new RuntimeException("获取连接超时");
}
else
{
System.out.println("等待之后获取了连接");
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
else
{
this.notifyAll();
}
}
// 注入源
private void addPool(List<Connection> pool)
{
for (int i = pool.size(); i < min; i++)
{
try
{
pool.add(source.getConnection());
}
catch (Exception e)
{
e.printStackTrace();
continue;
}
}
}
// 关闭连接
public synchronized void close(Connection con)
{
if (con != null)
{
currentRequest--;
System.out.println("currentRequest: " + currentRequest);
beginTransaction(maxWait);
if (pool.size() < max)
{
pool.add(con);
}
else
{
try
{
con.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
con = null;
}
}
currentActive--;
System.out.println("currentActive : " + currentActive);
}
}
// 连接获取实体类
private static class Entry
{
private String driverName;
private String url;
private String userName;
private String password;
public Entry(String driverName, String url, String userName, String password)
{
super();
this.driverName = driverName;
this.url = url;
this.userName = userName;
this.password = password;
}
Connection getConnection()
throws Exception
{
Class.forName(driverName);
return DriverManager.getConnection(url, userName, password);
}
}
}