packagecn.hc.connectionPool;importjava.io.IOException;importjava.io.InputStream;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.SQLException;importjava.util.LinkedList;importjava.util.Properties;/*** 简单的MySql数据库连接池
*@authorhc
*@version1.0*/
public classConnectionPool {private LinkedList connections=new LinkedList();//默认的数据库连接池大小为5
private static int initSize=5;private static int maxSize=5;private int acturalSize=0;//数据库连接池的实际大小
private static Properties props = null;static{try{
InputStream in= ConnectionPool.class.getClassLoader()
.getResourceAsStream("dbconfig.properties");
props= newProperties();
props.load(in);
}catch(IOException e) {throw newRuntimeException(e);
}try{
String size=props.getProperty("initSize");
String size2=props.getProperty("maxSize");if(size!=null){
initSize=Integer.parseInt(size);
}if(size2!=null){
maxSize=Integer.parseInt(size2);
}
}catch(Exception e) {throw newRuntimeException(e);
}
}//获取连接的静态内部类
static classGetCon{static{try{
Class.forName(props.getProperty("driverClassName"));
}catch(ClassNotFoundException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}static Connection getConnection() throwsSQLException{return DriverManager.getConnection(props.getProperty("url"),
props.getProperty("username"),
props.getProperty("password"));
}
}publicConnectionPool(){//初始化数据库连接池
for (int i = 0; i
connections.addLast(GetCon.getConnection());
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
acturalSize++;
}
}/*** 该方法用来释放连接,将connection对象放回到数据库连接池,实现对数据库连接池大大小的增减
*@paramconnection 要放回数据库连接池的连接*/
public voidreleseConnection(Connection connection){if(connection!=null){synchronized(connections) {if(connections.size()>initSize){try{
connection.close();
acturalSize--;
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}else{
connections.addLast(connection);
}
connections.notifyAll();//唤醒所有等待获取连接的对象
}
}
}/*** 该方法用来从数据库连接池获取连接
*@parammills 获取连接的超时时间 单位毫秒,当设置的值为0时候,即不要求等待时间
*@returnconnection对象
*@throwsSQLException
*@throwsInterruptedException*/
public Connection getConnection(long mills) throwsSQLException, InterruptedException{synchronized(connections) {if(mills<=0){while(connections.isEmpty()) {if(acturalSize
Connection con= DriverManager.getConnection(props.getProperty("url"),
props.getProperty("username"),
props.getProperty("password"));
acturalSize++;returncon;
}else{
connections.wait();
}
}returnconnections.removeFirst();
}else{if(acturalSize
Connection con= DriverManager.getConnection(props.getProperty("url"),
props.getProperty("username"),
props.getProperty("password"));
acturalSize++;returncon;
}else{long future=System.currentTimeMillis()+mills;long remaining=mills;while(connections.isEmpty()&&remaining>0){
connections.wait(remaining);
remaining=future-System.currentTimeMillis();
}
Connection result=null;if(!connections.isEmpty()){
result=connections.removeFirst();
}returnresult;
}
}
}
}
}