对象池是存放一组特定的对象的容器。对象池是解决性能的一种途径,当我们使用一个对象比较频繁的时候,而且该对象不某些属性不是公有的,就需要通过创建对象池将它们存放起来,避免频繁的创建销毁的开销。
下面是数据库连接池的实现原理:
/**
* 数据库连接池
*
* @author Administrator
*
*/
public class DBConnectionPool {
private final static int MAX_SIZE = 10;
private final static int MIN_SIZE = 3;
private final static Vector pool = new Vector();
static {
for (int i = 0; i < MIN_SIZE; i++) {
pool.add(createConnection());
}
}
/**
* 得到一个数据库的连接,如果当前池里面没有连接,创建一个新的连接,如果数据库连接池里面有 连接,那么从池里面得到
*
* @return
*/
public static synchronized Connection getConnection() {
System.out.println(pool.size());
Connection conn = null;
if (pool.isEmpty()) {
conn = createConnection();
} else {
int index = pool.size() - 1;
conn = (Connection) pool.get(index );
pool.remove(conn);
}
return conn;
}
private static Connection createConnection() {
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:ysen", "ysen", "123");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static synchronized void close(Connection conn) {
if (pool.size() >= MAX_SIZE) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} else if (pool.size() < MAX_SIZE) {
pool.add(conn);
}
}
}