1.简单连接池实例
public class DataSourcePool {
private LinkedList<Connection> pool = new LinkedList<Connection>();
private int COUNT_INIT;
private int COUNT_MAX;
private volatile int COUNT_CURRENT = 0;
private String DRIVER_CLASS;
private String URL;
private String USER_NAME;
private String PASSWORD;
private Lock lock = new ReentrantLock();
private Condition c = lock.newCondition();
public DataSourcePool(Properties properties) {
COUNT_INIT = Integer.parseInt(properties.getProperty("initialSize"));
COUNT_MAX = Integer.parseInt(properties.getProperty("maxActive"));
DRIVER_CLASS = properties.getProperty("driverClass");
URL = properties.getProperty("url");
USER_NAME = properties.getProperty("userName");
PASSWORD = properties.getProperty("password");
try {
Class.forName(DRIVER_CLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
for(int i=0;i<COUNT_INIT;i++){
try {
pool.add(DriverManager.getConnection(URL,USER_NAME,PASSWORD));
COUNT_CURRENT++;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public Connection getConnection(){
Connection result = null;
lock.lock();
try {
while (pool.isEmpty() && COUNT_CURRENT >= COUNT_MAX) {
c.await();
}
if (pool.isEmpty()&&COUNT_CURRENT < COUNT_MAX) {
result = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
COUNT_CURRENT++;
}
else{
result = pool.removeLast();
}
}catch(Exception e){
e.printStackTrace();
}
finally{
lock.unlock();
}
return result;
}
public void release(Connection connection){
lock.lock();
try {
if(pool.size()<COUNT_INIT){
pool.push(connection);
c.signal();
}
else{
connection.close();
COUNT_CURRENT--;
}
}catch(Exception e){
e.printStackTrace();
}
finally{
lock.unlock();
}
}
}